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/tests/generated/src/test/java/com/thoughtworks/selenium/ResourceAvailabilityTest.java b/tests/generated/src/test/java/com/thoughtworks/selenium/ResourceAvailabilityTest.java index 961c8e55..a8ab51fb 100644 --- a/tests/generated/src/test/java/com/thoughtworks/selenium/ResourceAvailabilityTest.java +++ b/tests/generated/src/test/java/com/thoughtworks/selenium/ResourceAvailabilityTest.java @@ -1,17 +1,17 @@ /* * Created on Mar 17, 2006 * */ package com.thoughtworks.selenium; import java.io.*; import junit.framework.*; public class ResourceAvailabilityTest extends TestCase { public void testResourceAvailable() { - InputStream s = ResourceAvailabilityTest.class.getResourceAsStream("/core/SeleneseRunner.html"); - assertNotNull("SeleneseRunner can't be found!", s); + InputStream s = ResourceAvailabilityTest.class.getResourceAsStream("/core/RemoteRunner.html"); + assertNotNull("RemoteRunner can't be found!", s); } }
true
true
public void testResourceAvailable() { InputStream s = ResourceAvailabilityTest.class.getResourceAsStream("/core/SeleneseRunner.html"); assertNotNull("SeleneseRunner can't be found!", s); }
public void testResourceAvailable() { InputStream s = ResourceAvailabilityTest.class.getResourceAsStream("/core/RemoteRunner.html"); assertNotNull("RemoteRunner can't be found!", s); }
diff --git a/src/com/wolvencraft/prison/mines/CommandManager.java b/src/com/wolvencraft/prison/mines/CommandManager.java index b6ba816..728e4cf 100644 --- a/src/com/wolvencraft/prison/mines/CommandManager.java +++ b/src/com/wolvencraft/prison/mines/CommandManager.java @@ -1,187 +1,188 @@ /* * CommandManager.java * * PrisonMine * Copyright (C) 2013 bitWolfy <http://www.wolvencraft.com> and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.wolvencraft.prison.mines; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import com.wolvencraft.prison.hooks.CommandHook; import com.wolvencraft.prison.mines.cmd.*; import com.wolvencraft.prison.mines.util.Message; /** * <b>Command manager</b><br /> * Handles subcommands and current command sender * @author bitWolfy * */ public enum CommandManager implements CommandHook { BLACKLIST (BlacklistCommand.class, "prison.mine.edit", true, "blacklist", "bl", "whitelist", "wl"), DEBUG(DebugCommand.class, "prison.mine.debug", true, "import", "debug", "setregion", "tp", "unload", "locale"), EDIT (EditCommand.class, "prison.mine.edit", true, "edit", "add", "+", "remove", "-", "delete", "del", "name", "link", "setparent", "cooldown", "setwarp"), FLAG (FlagCommand.class, "prison.mine.edit", true, "flag"), HELP (HelpCommand.class, null, true, "help"), INFO (InfoCommand.class, "prison.mine.info.time", true, "info"), LIST (ListCommand.class, "prison.mine.info.list", true, "list"), META (MetaCommand.class, "prison.mine.about", true, "meta", "about"), PROTECTION (ProtectionCommand.class, "prison.mine.edit", true, "protection", "prot"), RESET (ResetCommand.class, null, true, "reset"), SAVE (SaveCommand.class, "prison.mine.edit", false, "save", "create", "new"), TIME (TimeCommand.class, "prison.mine.info.time", true, "time"), TRIGGER (TriggerCommand.class, "prison.mine.edit", true, "trigger"), VARIABLES (VariablesCommand.class, "prison.mine.edit", true, "variables"), UTIL (UtilCommand.class, "prison.mine.admin", true, "reload", "saveall"), WARNING (WarningCommand.class, "prison.mine.edit", true, "warning"); private static CommandSender sender = null; private BaseCommand command; private String permission; private boolean allowConsole; private List<String> alias; CommandManager(Class<?> command, String permission, boolean allowConsole, String... args) { try { this.command = (BaseCommand) command.newInstance(); } catch (InstantiationException e) { Message.log(Level.SEVERE, "Error while instantiating a command! InstantiationException"); return; } catch (IllegalAccessException e) { Message.log(Level.SEVERE, "Error while instantiating a command! IllegalAccessException"); return; } this.permission = permission; this.allowConsole = allowConsole; alias = new ArrayList<String>(); for(String arg : args) { alias.add(arg); } } /** * Returns the command instance * @return Command instance */ public BaseCommand get() { return command; } /** * Checks if the specified alias corresponds to the command * @param alias Alias to check */ public boolean isCommand(String alias) { return this.alias.contains(alias); } /** * Returns the verbose help message for the command */ public void getHelp() { command.getHelp(); } /** * Returns the single-line help message for the command */ public void getHelpLine() { command.getHelpLine(); } /** * Returns the full list of aliases for the corresponding command * @return List of aliases */ public List<String> getAlias() { List<String> temp = new ArrayList<String>(); for(String str : alias) temp.add(str); return temp; } /** * Executes the corresponding command with specified arguments.<br /> * Checks for player's permissions before passing the arguments to the command * @param args Arguments to pass on to the command */ public boolean run(String[] args) { if(sender != null) { if(sender instanceof Player) Message.debug("Command issued by player: " + sender.getName()); else if(sender instanceof ConsoleCommandSender) Message.debug("Command issued by CONSOLE"); else Message.debug("Command issued by GHOSTS and WIZARDS"); } if(!allowConsole && !(sender instanceof Player)) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_SENDERISNOTPLAYER); return false; } if(permission != null && (sender instanceof Player) && !sender.hasPermission(permission)) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_ACCESS); return false; } try { return command.run(args); } catch (Exception e) { Message.sendFormattedError("An internal error occurred while running the command", false); Message.log(Level.SEVERE, "=== An error occurred while executing command ==="); + Message.log(Level.SEVERE, "Version = " + PrisonMine.getInstance().getDescription().getVersion()); Message.log(Level.SEVERE, "Exception = " + e.toString()); Message.log(Level.SEVERE, "CommandSender = " + sender.getName()); Message.log(Level.SEVERE, "isConsole = " + (sender instanceof ConsoleCommandSender)); String fullArgs = ""; for(String arg : args) fullArgs += arg + " "; Message.log(Level.SEVERE, "Command: /mine " + fullArgs); Message.log(Level.SEVERE, "Permission = " + permission); if(permission != null) Message.log(Level.SEVERE, "hasPermission = " + sender.hasPermission(permission)); Message.log(Level.SEVERE, ""); Message.log(Level.SEVERE, "=== === === === === Error log === === === === ==="); e.printStackTrace(); Message.log(Level.SEVERE, "=== === === === End of error log === === === ==="); return false; } } /** * Executes the corresponding command with specified arguments.<br /> * Checks for player's permissions before passing the arguments to the command.<br /> * Wraps around <code>run(String[] arg)</code> with one argument. * @param args Arguments to pass on to the command */ public boolean run(String arg) { String[] args = {"", arg}; return run(args); } /** * Returns the CommandSender for the command that is currently being processed. * @return Command sender, or <b>null</b> if there is no command being processed */ public static CommandSender getSender() { return sender; } /** * Sets the CommandSender to the one specified * @param sender Sender to be set */ public static void setSender(CommandSender sender) { CommandManager.sender = sender; } /** * Resets the active command sender to null */ public static void resetSender() { sender = null; } }
true
true
public boolean run(String[] args) { if(sender != null) { if(sender instanceof Player) Message.debug("Command issued by player: " + sender.getName()); else if(sender instanceof ConsoleCommandSender) Message.debug("Command issued by CONSOLE"); else Message.debug("Command issued by GHOSTS and WIZARDS"); } if(!allowConsole && !(sender instanceof Player)) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_SENDERISNOTPLAYER); return false; } if(permission != null && (sender instanceof Player) && !sender.hasPermission(permission)) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_ACCESS); return false; } try { return command.run(args); } catch (Exception e) { Message.sendFormattedError("An internal error occurred while running the command", false); Message.log(Level.SEVERE, "=== An error occurred while executing command ==="); Message.log(Level.SEVERE, "Exception = " + e.toString()); Message.log(Level.SEVERE, "CommandSender = " + sender.getName()); Message.log(Level.SEVERE, "isConsole = " + (sender instanceof ConsoleCommandSender)); String fullArgs = ""; for(String arg : args) fullArgs += arg + " "; Message.log(Level.SEVERE, "Command: /mine " + fullArgs); Message.log(Level.SEVERE, "Permission = " + permission); if(permission != null) Message.log(Level.SEVERE, "hasPermission = " + sender.hasPermission(permission)); Message.log(Level.SEVERE, ""); Message.log(Level.SEVERE, "=== === === === === Error log === === === === ==="); e.printStackTrace(); Message.log(Level.SEVERE, "=== === === === End of error log === === === ==="); return false; } }
public boolean run(String[] args) { if(sender != null) { if(sender instanceof Player) Message.debug("Command issued by player: " + sender.getName()); else if(sender instanceof ConsoleCommandSender) Message.debug("Command issued by CONSOLE"); else Message.debug("Command issued by GHOSTS and WIZARDS"); } if(!allowConsole && !(sender instanceof Player)) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_SENDERISNOTPLAYER); return false; } if(permission != null && (sender instanceof Player) && !sender.hasPermission(permission)) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_ACCESS); return false; } try { return command.run(args); } catch (Exception e) { Message.sendFormattedError("An internal error occurred while running the command", false); Message.log(Level.SEVERE, "=== An error occurred while executing command ==="); Message.log(Level.SEVERE, "Version = " + PrisonMine.getInstance().getDescription().getVersion()); Message.log(Level.SEVERE, "Exception = " + e.toString()); Message.log(Level.SEVERE, "CommandSender = " + sender.getName()); Message.log(Level.SEVERE, "isConsole = " + (sender instanceof ConsoleCommandSender)); String fullArgs = ""; for(String arg : args) fullArgs += arg + " "; Message.log(Level.SEVERE, "Command: /mine " + fullArgs); Message.log(Level.SEVERE, "Permission = " + permission); if(permission != null) Message.log(Level.SEVERE, "hasPermission = " + sender.hasPermission(permission)); Message.log(Level.SEVERE, ""); Message.log(Level.SEVERE, "=== === === === === Error log === === === === ==="); e.printStackTrace(); Message.log(Level.SEVERE, "=== === === === End of error log === === === ==="); return false; } }
diff --git a/M-GOV_android/mGOV_android/src/tw/edu/ntu/mgov/caseviewer/CaseViewer.java b/M-GOV_android/mGOV_android/src/tw/edu/ntu/mgov/caseviewer/CaseViewer.java index 28ca2f3..89875cc 100644 --- a/M-GOV_android/mGOV_android/src/tw/edu/ntu/mgov/caseviewer/CaseViewer.java +++ b/M-GOV_android/mGOV_android/src/tw/edu/ntu/mgov/caseviewer/CaseViewer.java @@ -1,187 +1,188 @@ /* * * mgov.java * 2010/10/04 * sodas * * Base class of application. Main Activity. * * Copyright 2010 NTU CSIE Mobile & HCI Lab * * 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 tw.edu.ntu.mgov.caseviewer; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import org.json.JSONException; import tw.edu.ntu.mgov.R; import tw.edu.ntu.mgov.gae.GAECase; import tw.edu.ntu.mgov.gae.GAEQuery; import tw.edu.ntu.mgov.typeselector.QidToDescription; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; import android.app.ProgressDialog; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ImageView; import android.widget.TextView; /** * @author shou * 2010/10/13 * @company NTU CSIE Mobile HCI Lab */ public class CaseViewer extends MapActivity implements Runnable { // Views private ImageView photoView; private MapView mapView; private TextView caseID; private TextView date; private TextView caseStatus; private TextView caseType; private TextView description; private TextView caseAddress; private GAEQuery qGAE; private GAECase queryResult; private ProgressDialog loadingView; protected Drawable image; @Override protected void onCreate(Bundle savedInstanceState) { loadingView = ProgressDialog.show(this, "", getResources().getString(R.string.loading_message), false); Thread thread = new Thread(this); thread.start(); super.onCreate(savedInstanceState); setTitle(getResources().getString(R.string.caseviewer_activity_title)); setContentView(R.layout.caseviewer); findAllViews(); } // Load Data in another thread private Handler handler = new Handler() { public void handleMessage(Message msg) { loadingView.cancel(); setAllAttributes(); } }; @Override public void run() { qGAE = new GAEQuery(); try { queryResult = qGAE.getID(getIntent().getExtras().getString("caseID")); } catch (JSONException e) { e.printStackTrace(); } String [] imageURL = queryResult.getImage(); if (imageURL.length!=0) image = LoadImageFromWebOperations(imageURL[0].replace("GET_SHOW_PHOTO.CFM?photo_filename=", "photo/")); handler.sendEmptyMessage(0); } private void findAllViews() { photoView = (ImageView) findViewById(R.id.CaseViewer_Photo); mapView = (MapView) findViewById(R.id.CaseViewer_Map); caseID = (TextView) findViewById(R.id.CaseViewer_CaseID); date = (TextView) findViewById(R.id.CaseViewer_Date); caseStatus = (TextView) findViewById(R.id.CaseViewer_CaseStatus); caseType = (TextView) findViewById(R.id.CaseViewer_CaseType); description = (TextView) findViewById(R.id.CaseViewer_Description); caseAddress = (TextView) findViewById(R.id.CaseViewer_Address); } protected class MapOverlay extends ItemizedOverlay<OverlayItem> { private ArrayList<OverlayItem> gList = new ArrayList<OverlayItem>(); Drawable marker; public MapOverlay(Drawable defaultMarker) { super(defaultMarker); marker = defaultMarker; } protected void addOverlayItem(OverlayItem oItem) { gList.add(oItem); populate(); } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, false); boundCenterBottom(marker); } @Override protected OverlayItem createItem(int i) { return gList.get(i); } @Override public int size() { return gList.size(); } } private void setAllAttributes() { caseID.setText(queryResult.getform("key")); date.setText(queryResult.getform("date")); caseStatus.setText(queryResult.getform("status")); caseType.setText(QidToDescription.getDetailByQID(this, Integer.parseInt(queryResult.getform("typeid")))); description.setText(queryResult.getform("detail")); caseAddress.setText(queryResult.getform("address")); photoView.setImageDrawable(image); TextView tv = (TextView) findViewById(R.id.CaseViewer_NoPhotoMessege); if (image==null) tv.setVisibility(View.VISIBLE); else tv.setVisibility(View.INVISIBLE); Drawable marker = this.getResources().getDrawable(R.drawable.okspot); MapOverlay mapOverlay = new MapOverlay(marker); OverlayItem overlayItem = new OverlayItem(queryResult.getGeoPoint(), "", ""); mapOverlay.addOverlayItem(overlayItem); mapView.getOverlays().add(mapOverlay); mapView.getController().animateTo(queryResult.getGeoPoint()); + mapView.getController().setZoom(16); } private Drawable LoadImageFromWebOperations(String url) { InputStream is; try { is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "caseviewer photo"); return d; } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected boolean isRouteDisplayed() { return false; } }
true
true
private void setAllAttributes() { caseID.setText(queryResult.getform("key")); date.setText(queryResult.getform("date")); caseStatus.setText(queryResult.getform("status")); caseType.setText(QidToDescription.getDetailByQID(this, Integer.parseInt(queryResult.getform("typeid")))); description.setText(queryResult.getform("detail")); caseAddress.setText(queryResult.getform("address")); photoView.setImageDrawable(image); TextView tv = (TextView) findViewById(R.id.CaseViewer_NoPhotoMessege); if (image==null) tv.setVisibility(View.VISIBLE); else tv.setVisibility(View.INVISIBLE); Drawable marker = this.getResources().getDrawable(R.drawable.okspot); MapOverlay mapOverlay = new MapOverlay(marker); OverlayItem overlayItem = new OverlayItem(queryResult.getGeoPoint(), "", ""); mapOverlay.addOverlayItem(overlayItem); mapView.getOverlays().add(mapOverlay); mapView.getController().animateTo(queryResult.getGeoPoint()); }
private void setAllAttributes() { caseID.setText(queryResult.getform("key")); date.setText(queryResult.getform("date")); caseStatus.setText(queryResult.getform("status")); caseType.setText(QidToDescription.getDetailByQID(this, Integer.parseInt(queryResult.getform("typeid")))); description.setText(queryResult.getform("detail")); caseAddress.setText(queryResult.getform("address")); photoView.setImageDrawable(image); TextView tv = (TextView) findViewById(R.id.CaseViewer_NoPhotoMessege); if (image==null) tv.setVisibility(View.VISIBLE); else tv.setVisibility(View.INVISIBLE); Drawable marker = this.getResources().getDrawable(R.drawable.okspot); MapOverlay mapOverlay = new MapOverlay(marker); OverlayItem overlayItem = new OverlayItem(queryResult.getGeoPoint(), "", ""); mapOverlay.addOverlayItem(overlayItem); mapView.getOverlays().add(mapOverlay); mapView.getController().animateTo(queryResult.getGeoPoint()); mapView.getController().setZoom(16); }
diff --git a/src/com/android/bluetooth/btservice/AdapterState.java b/src/com/android/bluetooth/btservice/AdapterState.java old mode 100755 new mode 100644 index 5f9c30b..7dba484 --- a/src/com/android/bluetooth/btservice/AdapterState.java +++ b/src/com/android/bluetooth/btservice/AdapterState.java @@ -1,392 +1,394 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.bluetooth.btservice; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.os.Message; import android.util.Log; import com.android.internal.util.State; import com.android.internal.util.StateMachine; /** * This state machine handles Bluetooth Adapter State. * States: * {@link OnState} : Bluetooth is on at this state * {@link OffState}: Bluetooth is off at this state. This is the initial * state. * {@link PendingCommandState} : An enable / disable operation is pending. * TODO(BT): Add per process on state. */ final class AdapterState extends StateMachine { private static final boolean DBG = true; private static final boolean VDBG = false; private static final String TAG = "BluetoothAdapterState"; static final int USER_TURN_ON = 1; static final int STARTED=2; static final int ENABLED_READY = 3; static final int USER_TURN_OFF = 20; static final int BEGIN_DISABLE = 21; static final int ALL_DEVICES_DISCONNECTED = 22; static final int DISABLED = 24; static final int STOPPED=25; static final int START_TIMEOUT = 100; static final int ENABLE_TIMEOUT = 101; static final int DISABLE_TIMEOUT = 103; static final int STOP_TIMEOUT = 104; static final int SET_SCAN_MODE_TIMEOUT = 105; static final int USER_TURN_OFF_DELAY_MS=500; //TODO: tune me private static final int ENABLE_TIMEOUT_DELAY = 8000; private static final int DISABLE_TIMEOUT_DELAY = 8000; private static final int START_TIMEOUT_DELAY = 5000; private static final int STOP_TIMEOUT_DELAY = 5000; private static final int PROPERTY_OP_DELAY =2000; private AdapterService mAdapterService; private AdapterProperties mAdapterProperties; private PendingCommandState mPendingCommandState = new PendingCommandState(); private OnState mOnState = new OnState(); private OffState mOffState = new OffState(); public boolean isTurningOn() { boolean isTurningOn= mPendingCommandState.isTurningOn(); if (VDBG) Log.d(TAG,"isTurningOn()=" + isTurningOn); return isTurningOn; } public boolean isTurningOff() { boolean isTurningOff= mPendingCommandState.isTurningOff(); if (VDBG) Log.d(TAG,"isTurningOff()=" + isTurningOff); return isTurningOff; } private AdapterState(AdapterService service, AdapterProperties adapterProperties) { super("BluetoothAdapterState:"); addState(mOnState); addState(mOffState); addState(mPendingCommandState); mAdapterService = service; mAdapterProperties = adapterProperties; setInitialState(mOffState); } public static AdapterState make(AdapterService service, AdapterProperties adapterProperties) { Log.d(TAG, "make"); AdapterState as = new AdapterState(service, adapterProperties); as.start(); return as; } public void doQuit() { quitNow(); } public void cleanup() { if(mAdapterProperties != null) mAdapterProperties = null; if(mAdapterService != null) mAdapterService = null; } private class OffState extends State { @Override public void enter() { infoLog("Entering OffState"); } @Override public boolean processMessage(Message msg) { AdapterService adapterService = mAdapterService; if (adapterService == null) { Log.e(TAG,"receive message at OffState after cleanup:" + msg.what); return false; } switch(msg.what) { case USER_TURN_ON: if (DBG) Log.d(TAG,"CURRENT_STATE=OFF, MESSAGE = USER_TURN_ON"); notifyAdapterStateChange(BluetoothAdapter.STATE_TURNING_ON); mPendingCommandState.setTurningOn(true); transitionTo(mPendingCommandState); sendMessageDelayed(START_TIMEOUT, START_TIMEOUT_DELAY); adapterService.processStart(); break; case USER_TURN_OFF: if (DBG) Log.d(TAG,"CURRENT_STATE=OFF, MESSAGE = USER_TURN_OFF"); //TODO: Handle case of service started and stopped without enable break; default: if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=OFF, MESSAGE = " + msg.what ); return false; } return true; } } private class OnState extends State { @Override public void enter() { infoLog("Entering On State"); AdapterService adapterService = mAdapterService; if (adapterService == null) { Log.e(TAG,"enter OnState after cleanup"); return; } adapterService.autoConnect(); } @Override public boolean processMessage(Message msg) { AdapterProperties adapterProperties = mAdapterProperties; if (adapterProperties == null) { Log.e(TAG,"receive message at OnState after cleanup:" + msg.what); return false; } switch(msg.what) { case USER_TURN_OFF: if (DBG) Log.d(TAG,"CURRENT_STATE=ON, MESSAGE = USER_TURN_OFF"); notifyAdapterStateChange(BluetoothAdapter.STATE_TURNING_OFF); mPendingCommandState.setTurningOff(true); transitionTo(mPendingCommandState); // Invoke onBluetoothDisable which shall trigger a // setScanMode to SCAN_MODE_NONE Message m = obtainMessage(SET_SCAN_MODE_TIMEOUT); sendMessageDelayed(m, PROPERTY_OP_DELAY); adapterProperties.onBluetoothDisable(); break; case USER_TURN_ON: if (DBG) Log.d(TAG,"CURRENT_STATE=ON, MESSAGE = USER_TURN_ON"); Log.i(TAG,"Bluetooth already ON, ignoring USER_TURN_ON"); break; default: if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=ON, MESSAGE = " + msg.what ); return false; } return true; } } private class PendingCommandState extends State { private boolean mIsTurningOn; private boolean mIsTurningOff; public void enter() { infoLog("Entering PendingCommandState State: isTurningOn()=" + isTurningOn() + ", isTurningOff()=" + isTurningOff()); } public void setTurningOn(boolean isTurningOn) { mIsTurningOn = isTurningOn; } public boolean isTurningOn() { return mIsTurningOn; } public void setTurningOff(boolean isTurningOff) { mIsTurningOff = isTurningOff; } public boolean isTurningOff() { return mIsTurningOff; } @Override public boolean processMessage(Message msg) { boolean isTurningOn= isTurningOn(); boolean isTurningOff = isTurningOff(); AdapterService adapterService = mAdapterService; AdapterProperties adapterProperties = mAdapterProperties; if ((adapterService == null) || (adapterProperties == null)) { Log.e(TAG,"receive message at Pending State after cleanup:" + msg.what); return false; } switch (msg.what) { case USER_TURN_ON: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON" + ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); if (isTurningOn) { Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning on bluetooth... Ignoring USER_TURN_ON..."); } else { Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_ON"); deferMessage(msg); } break; case USER_TURN_OFF: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON" + ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); if (isTurningOff) { Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning off bluetooth... Ignoring USER_TURN_OFF..."); } else { Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_OFF"); deferMessage(msg); } break; case STARTED: { if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STARTED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); //Remove start timeout removeMessages(START_TIMEOUT); //Enable boolean ret = adapterService.enableNative(); if (!ret) { Log.e(TAG, "Error while turning Bluetooth On"); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); transitionTo(mOffState); } else { sendMessageDelayed(ENABLE_TIMEOUT, ENABLE_TIMEOUT_DELAY); } } break; case ENABLED_READY: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_READY, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); removeMessages(ENABLE_TIMEOUT); adapterProperties.onBluetoothReady(); mPendingCommandState.setTurningOn(false); transitionTo(mOnState); notifyAdapterStateChange(BluetoothAdapter.STATE_ON); break; case SET_SCAN_MODE_TIMEOUT: Log.w(TAG,"Timeout will setting scan mode..Continuing with disable..."); //Fall through case BEGIN_DISABLE: { if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = BEGIN_DISABLE, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); removeMessages(SET_SCAN_MODE_TIMEOUT); sendMessageDelayed(DISABLE_TIMEOUT, DISABLE_TIMEOUT_DELAY); boolean ret = adapterService.disableNative(); if (!ret) { removeMessages(DISABLE_TIMEOUT); Log.e(TAG, "Error while turning Bluetooth Off"); //FIXME: what about post enable services mPendingCommandState.setTurningOff(false); notifyAdapterStateChange(BluetoothAdapter.STATE_ON); } } break; case DISABLED: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); if (isTurningOn) { removeMessages(ENABLE_TIMEOUT); errorLog("Error enabling Bluetooth - hardware init failed"); mPendingCommandState.setTurningOn(false); transitionTo(mOffState); adapterService.stopProfileServices(); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; } removeMessages(DISABLE_TIMEOUT); sendMessageDelayed(STOP_TIMEOUT, STOP_TIMEOUT_DELAY); if (adapterService.stopProfileServices()) { Log.d(TAG,"Stopping profile services that were post enabled"); break; } //Fall through if no services or services already stopped case STOPPED: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOPPED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); removeMessages(STOP_TIMEOUT); setTurningOff(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; case START_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = START_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error enabling Bluetooth"); mPendingCommandState.setTurningOn(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; case ENABLE_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error enabling Bluetooth"); mPendingCommandState.setTurningOn(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; case STOP_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOP_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error stopping Bluetooth profiles"); mPendingCommandState.setTurningOff(false); transitionTo(mOffState); break; case DISABLE_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error disabling Bluetooth"); mPendingCommandState.setTurningOff(false); - transitionTo(mOnState); - notifyAdapterStateChange(BluetoothAdapter.STATE_ON); + transitionTo(mOffState); + notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); + errorLog("Killing the process to force a restart as part cleanup"); + android.os.Process.killProcess(android.os.Process.myPid()); break; default: if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=PENDING, MESSAGE = " + msg.what ); return false; } return true; } } private void notifyAdapterStateChange(int newState) { AdapterService adapterService = mAdapterService; AdapterProperties adapterProperties = mAdapterProperties; if ((adapterService == null) || (adapterProperties == null)) { Log.e(TAG,"notifyAdapterStateChange after cleanup:" + newState); return; } int oldState = adapterProperties.getState(); adapterProperties.setState(newState); infoLog("Bluetooth adapter state changed: " + oldState + "-> " + newState); adapterService.updateAdapterState(oldState, newState); } void stateChangeCallback(int status) { if (status == AbstractionLayer.BT_STATE_OFF) { sendMessage(DISABLED); } else if (status == AbstractionLayer.BT_STATE_ON) { // We should have got the property change for adapter and remote devices. sendMessage(ENABLED_READY); } else { errorLog("Incorrect status in stateChangeCallback"); } } private void infoLog(String msg) { if (DBG) Log.i(TAG, msg); } private void errorLog(String msg) { Log.e(TAG, msg); } }
true
true
public boolean processMessage(Message msg) { boolean isTurningOn= isTurningOn(); boolean isTurningOff = isTurningOff(); AdapterService adapterService = mAdapterService; AdapterProperties adapterProperties = mAdapterProperties; if ((adapterService == null) || (adapterProperties == null)) { Log.e(TAG,"receive message at Pending State after cleanup:" + msg.what); return false; } switch (msg.what) { case USER_TURN_ON: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON" + ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); if (isTurningOn) { Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning on bluetooth... Ignoring USER_TURN_ON..."); } else { Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_ON"); deferMessage(msg); } break; case USER_TURN_OFF: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON" + ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); if (isTurningOff) { Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning off bluetooth... Ignoring USER_TURN_OFF..."); } else { Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_OFF"); deferMessage(msg); } break; case STARTED: { if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STARTED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); //Remove start timeout removeMessages(START_TIMEOUT); //Enable boolean ret = adapterService.enableNative(); if (!ret) { Log.e(TAG, "Error while turning Bluetooth On"); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); transitionTo(mOffState); } else { sendMessageDelayed(ENABLE_TIMEOUT, ENABLE_TIMEOUT_DELAY); } } break; case ENABLED_READY: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_READY, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); removeMessages(ENABLE_TIMEOUT); adapterProperties.onBluetoothReady(); mPendingCommandState.setTurningOn(false); transitionTo(mOnState); notifyAdapterStateChange(BluetoothAdapter.STATE_ON); break; case SET_SCAN_MODE_TIMEOUT: Log.w(TAG,"Timeout will setting scan mode..Continuing with disable..."); //Fall through case BEGIN_DISABLE: { if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = BEGIN_DISABLE, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); removeMessages(SET_SCAN_MODE_TIMEOUT); sendMessageDelayed(DISABLE_TIMEOUT, DISABLE_TIMEOUT_DELAY); boolean ret = adapterService.disableNative(); if (!ret) { removeMessages(DISABLE_TIMEOUT); Log.e(TAG, "Error while turning Bluetooth Off"); //FIXME: what about post enable services mPendingCommandState.setTurningOff(false); notifyAdapterStateChange(BluetoothAdapter.STATE_ON); } } break; case DISABLED: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); if (isTurningOn) { removeMessages(ENABLE_TIMEOUT); errorLog("Error enabling Bluetooth - hardware init failed"); mPendingCommandState.setTurningOn(false); transitionTo(mOffState); adapterService.stopProfileServices(); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; } removeMessages(DISABLE_TIMEOUT); sendMessageDelayed(STOP_TIMEOUT, STOP_TIMEOUT_DELAY); if (adapterService.stopProfileServices()) { Log.d(TAG,"Stopping profile services that were post enabled"); break; } //Fall through if no services or services already stopped case STOPPED: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOPPED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); removeMessages(STOP_TIMEOUT); setTurningOff(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; case START_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = START_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error enabling Bluetooth"); mPendingCommandState.setTurningOn(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; case ENABLE_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error enabling Bluetooth"); mPendingCommandState.setTurningOn(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; case STOP_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOP_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error stopping Bluetooth profiles"); mPendingCommandState.setTurningOff(false); transitionTo(mOffState); break; case DISABLE_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error disabling Bluetooth"); mPendingCommandState.setTurningOff(false); transitionTo(mOnState); notifyAdapterStateChange(BluetoothAdapter.STATE_ON); break; default: if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=PENDING, MESSAGE = " + msg.what ); return false; } return true; }
public boolean processMessage(Message msg) { boolean isTurningOn= isTurningOn(); boolean isTurningOff = isTurningOff(); AdapterService adapterService = mAdapterService; AdapterProperties adapterProperties = mAdapterProperties; if ((adapterService == null) || (adapterProperties == null)) { Log.e(TAG,"receive message at Pending State after cleanup:" + msg.what); return false; } switch (msg.what) { case USER_TURN_ON: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON" + ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); if (isTurningOn) { Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning on bluetooth... Ignoring USER_TURN_ON..."); } else { Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_ON"); deferMessage(msg); } break; case USER_TURN_OFF: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = USER_TURN_ON" + ", isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); if (isTurningOff) { Log.i(TAG,"CURRENT_STATE=PENDING: Alreadying turning off bluetooth... Ignoring USER_TURN_OFF..."); } else { Log.i(TAG,"CURRENT_STATE=PENDING: Deferring request USER_TURN_OFF"); deferMessage(msg); } break; case STARTED: { if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STARTED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); //Remove start timeout removeMessages(START_TIMEOUT); //Enable boolean ret = adapterService.enableNative(); if (!ret) { Log.e(TAG, "Error while turning Bluetooth On"); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); transitionTo(mOffState); } else { sendMessageDelayed(ENABLE_TIMEOUT, ENABLE_TIMEOUT_DELAY); } } break; case ENABLED_READY: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_READY, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); removeMessages(ENABLE_TIMEOUT); adapterProperties.onBluetoothReady(); mPendingCommandState.setTurningOn(false); transitionTo(mOnState); notifyAdapterStateChange(BluetoothAdapter.STATE_ON); break; case SET_SCAN_MODE_TIMEOUT: Log.w(TAG,"Timeout will setting scan mode..Continuing with disable..."); //Fall through case BEGIN_DISABLE: { if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = BEGIN_DISABLE, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); removeMessages(SET_SCAN_MODE_TIMEOUT); sendMessageDelayed(DISABLE_TIMEOUT, DISABLE_TIMEOUT_DELAY); boolean ret = adapterService.disableNative(); if (!ret) { removeMessages(DISABLE_TIMEOUT); Log.e(TAG, "Error while turning Bluetooth Off"); //FIXME: what about post enable services mPendingCommandState.setTurningOff(false); notifyAdapterStateChange(BluetoothAdapter.STATE_ON); } } break; case DISABLED: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); if (isTurningOn) { removeMessages(ENABLE_TIMEOUT); errorLog("Error enabling Bluetooth - hardware init failed"); mPendingCommandState.setTurningOn(false); transitionTo(mOffState); adapterService.stopProfileServices(); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; } removeMessages(DISABLE_TIMEOUT); sendMessageDelayed(STOP_TIMEOUT, STOP_TIMEOUT_DELAY); if (adapterService.stopProfileServices()) { Log.d(TAG,"Stopping profile services that were post enabled"); break; } //Fall through if no services or services already stopped case STOPPED: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOPPED, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); removeMessages(STOP_TIMEOUT); setTurningOff(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; case START_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = START_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error enabling Bluetooth"); mPendingCommandState.setTurningOn(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; case ENABLE_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = ENABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error enabling Bluetooth"); mPendingCommandState.setTurningOn(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); break; case STOP_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = STOP_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error stopping Bluetooth profiles"); mPendingCommandState.setTurningOff(false); transitionTo(mOffState); break; case DISABLE_TIMEOUT: if (DBG) Log.d(TAG,"CURRENT_STATE=PENDING, MESSAGE = DISABLE_TIMEOUT, isTurningOn=" + isTurningOn + ", isTurningOff=" + isTurningOff); errorLog("Error disabling Bluetooth"); mPendingCommandState.setTurningOff(false); transitionTo(mOffState); notifyAdapterStateChange(BluetoothAdapter.STATE_OFF); errorLog("Killing the process to force a restart as part cleanup"); android.os.Process.killProcess(android.os.Process.myPid()); break; default: if (DBG) Log.d(TAG,"ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=PENDING, MESSAGE = " + msg.what ); return false; } return true; }
diff --git a/server/src/edu/rpi/cct/webdav/servlet/common/WebdavServlet.java b/server/src/edu/rpi/cct/webdav/servlet/common/WebdavServlet.java index d996036..32efcc1 100644 --- a/server/src/edu/rpi/cct/webdav/servlet/common/WebdavServlet.java +++ b/server/src/edu/rpi/cct/webdav/servlet/common/WebdavServlet.java @@ -1,511 +1,515 @@ /* Copyright (c) 2000-2005 University of Washington. All rights reserved. Redistribution and use of this distribution in source and binary forms, with or without modification, are permitted provided that: The above copyright notice and this permission notice appear in all copies and supporting documentation; The name, identifiers, and trademarks of the University of Washington are not used in advertising or publicity without the express prior written permission of the University of Washington; Recipients acknowledge that this distribution is made available as a research courtesy, "as is", potentially with defects, without any obligation on the part of the University of Washington to provide support, services, or repair; THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* ********************************************************************** Copyright 2005 Rensselaer Polytechnic Institute. All worldwide rights reserved. Redistribution and use of this distribution in source and binary forms, with or without modification, are permitted provided that: The above copyright notice and this permission notice appear in all copies and supporting documentation; The name, identifiers, and trademarks of Rensselaer Polytechnic Institute are not used in advertising or publicity without the express prior written permission of Rensselaer Polytechnic Institute; DISCLAIMER: The software is distributed" AS IS" without any express or implied warranty, including but not limited to, any implied warranties of merchantability or fitness for a particular purpose or any warrant)' of non-infringement of any current or pending patent rights. The authors of the software make no representations about the suitability of this software for any particular purpose. The entire risk as to the quality and performance of the software is with the user. Should the software prove defective, the user assumes the cost of all necessary servicing, repair or correction. In particular, neither Rensselaer Polytechnic Institute, nor the authors of the software are liable for any indirect, special, consequential, or incidental damages related to the software, to the maximum extent the law permits. */ package edu.rpi.cct.webdav.servlet.common; import edu.rpi.cct.webdav.servlet.common.MethodBase.MethodInfo; import edu.rpi.cct.webdav.servlet.shared.WebdavException; import edu.rpi.cct.webdav.servlet.shared.WebdavForbidden; import edu.rpi.cct.webdav.servlet.shared.WebdavNsIntf; import edu.rpi.sss.util.servlets.io.CharArrayWrappedResponse; import edu.rpi.sss.util.xml.XmlEmit; import edu.rpi.sss.util.xml.tagdefs.WebdavTags; import java.io.InputStream; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.xml.namespace.QName; import org.apache.log4j.Logger; /** WebDAV Servlet. * This abstract servlet handles the request/response nonsense and calls * abstract routines to interact with an underlying data source. * * @author Mike Douglass [email protected] * @version 1.0 */ public abstract class WebdavServlet extends HttpServlet implements HttpSessionListener { protected boolean debug; protected boolean dumpContent; protected transient Logger log; /** Global resources for the servlet - not to be modified. */ protected Properties props; /** Table of methods - set at init */ protected HashMap<String, MethodInfo> methods = new HashMap<String, MethodInfo>(); /* Try to serialize requests from a single session * This is very imperfect. */ static class Waiter { boolean active; int waiting; } private static volatile HashMap<String, Waiter> waiters = new HashMap<String, Waiter>(); /** Some sort of identifying string for logging * * @return String id */ public abstract String getId(); public void init(ServletConfig config) throws ServletException { super.init(config); dumpContent = "true".equals(config.getInitParameter("dumpContent")); getResources(config); addMethods(); } /** Get an interface for the namespace * * @param req HttpServletRequest * @return WebdavNsIntf or subclass of * @throws WebdavException */ public abstract WebdavNsIntf getNsIntf(HttpServletRequest req) throws WebdavException; protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { WebdavNsIntf intf = null; boolean serverError = false; try { String debugStr = getInitParameter("debug"); if (debugStr != null) { debug = !"0".equals(debugStr); } if (debug) { debugMsg("entry: " + req.getMethod()); dumpRequest(req); } tryWait(req, true); intf = getNsIntf(req); if (req.getCharacterEncoding() == null) { req.setCharacterEncoding("UTF-8"); if (debug) { debugMsg("No charset specified in request; forced to UTF-8"); } } if (debug && dumpContent) { resp = new CharArrayWrappedResponse(resp, getLogger(), debug); } String methodName = req.getMethod(); MethodBase method = intf.getMethod(methodName); //resp.addHeader("DAV", intf.getDavHeader()); if (method == null) { logIt("No method for '" + methodName + "'"); // ================================================================ // Set the correct response // ================================================================ } else { method.doMethod(req, resp); } } catch (WebdavForbidden wdf) { sendError(intf, wdf, resp); } catch (Throwable t) { serverError = handleException(intf, t, resp, serverError); } finally { if (intf != null) { try { intf.close(); } catch (Throwable t) { serverError = handleException(intf, t, resp, serverError); } } try { tryWait(req, false); } catch (Throwable t) {} - if (debug && dumpContent) { + if (debug && dumpContent && + (resp instanceof CharArrayWrappedResponse)) { + /* instanceof check because we might get a subsequent exception before + * we wrap the response + */ CharArrayWrappedResponse wresp = (CharArrayWrappedResponse)resp; if (wresp.getUsedOutputStream()) { debugMsg("------------------------ response written to output stream -------------------"); } else { String str = wresp.toString(); debugMsg("------------------------ Dump of response -------------------"); debugMsg(str); debugMsg("---------------------- End dump of response -----------------"); byte[] bs = str.getBytes(); resp = (HttpServletResponse)wresp.getResponse(); debugMsg("contentLength=" + bs.length); resp.setContentLength(bs.length); resp.getOutputStream().write(bs); } } /* WebDAV is stateless - toss away the session */ try { HttpSession sess = req.getSession(false); if (sess != null) { sess.invalidate(); } } catch (Throwable t) {} } } /* Return true if it's a server error */ private boolean handleException(WebdavNsIntf intf, Throwable t, HttpServletResponse resp, boolean serverError) { if (serverError) { return true; } try { if (t instanceof WebdavException) { WebdavException wde = (WebdavException)t; int status = wde.getStatusCode(); if (status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { getLogger().error(this, wde); serverError = true; } sendError(intf, wde, resp); return serverError; } getLogger().error(this, t); sendError(intf, t, resp); return true; } catch (Throwable t1) { // Pretty much screwed if we get here return true; } } private void sendError(WebdavNsIntf intf, Throwable t, HttpServletResponse resp) { try { if (t instanceof WebdavException) { WebdavException wde = (WebdavException)t; QName errorTag = wde.getErrorTag(); if (errorTag != null) { if (debug) { debugMsg("setStatus(" + wde.getStatusCode() + ")"); } resp.setStatus(wde.getStatusCode()); if (!emitError(intf, errorTag, resp.getWriter())) { StringWriter sw = new StringWriter(); emitError(intf, errorTag, sw); try { if (debug) { debugMsg("setStatus(" + wde.getStatusCode() + ")"); } resp.sendError(wde.getStatusCode(), sw.toString()); } catch (Throwable t1) { } } } else { if (debug) { debugMsg("setStatus(" + wde.getStatusCode() + ")"); } resp.sendError(wde.getStatusCode(), wde.getMessage()); } } else { if (debug) { debugMsg("setStatus(" + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ")"); } resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.getMessage()); } } catch (Throwable t1) { // Pretty much screwed if we get here } } private boolean emitError(WebdavNsIntf intf, QName errorTag, Writer wtr) { try { XmlEmit xml = new XmlEmit(); intf.addNamespace(xml); xml.startEmit(wtr); xml.openTag(WebdavTags.error); xml.emptyTag(errorTag); xml.closeTag(WebdavTags.error); xml.flush(); return true; } catch (Throwable t1) { // Pretty much screwed if we get here return false; } } /** Add methods for this namespace * */ protected void addMethods() { methods.put("ACL", new MethodInfo(AclMethod.class, false)); methods.put("COPY", new MethodInfo(CopyMethod.class, false)); methods.put("GET", new MethodInfo(GetMethod.class, false)); methods.put("HEAD", new MethodInfo(HeadMethod.class, false)); methods.put("OPTIONS", new MethodInfo(OptionsMethod.class, false)); methods.put("PROPFIND", new MethodInfo(PropFindMethod.class, false)); methods.put("DELETE", new MethodInfo(DeleteMethod.class, true)); methods.put("MKCOL", new MethodInfo(MkcolMethod.class, true)); methods.put("MOVE", new MethodInfo(MoveMethod.class, true)); methods.put("POST", new MethodInfo(PostMethod.class, true)); methods.put("PROPPATCH", new MethodInfo(PropPatchMethod.class, true)); methods.put("PUT", new MethodInfo(PutMethod.class, true)); //methods.put("LOCK", new MethodInfo(LockMethod.class, true)); //methods.put("UNLOCK", new MethodInfo(UnlockMethod.class, true)); } private void getResources(ServletConfig config) throws ServletException { String resname = config.getInitParameter("application"); if (resname != null) { InputStream is; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = this.getClass().getClassLoader(); } is = classLoader.getResourceAsStream(resname + ".properties"); props = new Properties(); try { props.load(is); } catch (IOException ie) { log.error(ie); throw new ServletException(ie); } } } private void tryWait(HttpServletRequest req, boolean in) throws Throwable { Waiter wtr = null; synchronized (waiters) { //String key = req.getRequestedSessionId(); String key = req.getRemoteUser(); if (key == null) { return; } wtr = waiters.get(key); if (wtr == null) { if (!in) { return; } wtr = new Waiter(); wtr.active = true; waiters.put(key, wtr); return; } } synchronized (wtr) { if (!in) { wtr.active = false; wtr.notify(); return; } wtr.waiting++; while (wtr.active) { if (debug) { log.debug("in: waiters=" + wtr.waiting); } wtr.wait(); } wtr.waiting--; wtr.active = true; } } /* (non-Javadoc) * @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent) */ public void sessionCreated(HttpSessionEvent se) { } /* (non-Javadoc) * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent) */ public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); String sessid = session.getId(); if (sessid == null) { return; } synchronized (waiters) { waiters.remove(sessid); } } /** Debug * * @param req */ public void dumpRequest(HttpServletRequest req) { Logger log = getLogger(); try { Enumeration names = req.getHeaderNames(); String title = "Request headers"; log.debug(title); while (names.hasMoreElements()) { String key = (String)names.nextElement(); String val = req.getHeader(key); log.debug(" " + key + " = \"" + val + "\""); } names = req.getParameterNames(); title = "Request parameters"; log.debug(title + " - global info and uris"); log.debug("getRemoteAddr = " + req.getRemoteAddr()); log.debug("getRequestURI = " + req.getRequestURI()); log.debug("getRemoteUser = " + req.getRemoteUser()); log.debug("getRequestedSessionId = " + req.getRequestedSessionId()); log.debug("HttpUtils.getRequestURL(req) = " + req.getRequestURL()); log.debug("contextPath=" + req.getContextPath()); log.debug("query=" + req.getQueryString()); log.debug("contentlen=" + req.getContentLength()); log.debug("request=" + req); log.debug("parameters:"); log.debug(title); while (names.hasMoreElements()) { String key = (String)names.nextElement(); String val = req.getParameter(key); log.debug(" " + key + " = \"" + val + "\""); } } catch (Throwable t) { } } /** * @return LOgger */ public Logger getLogger() { if (log == null) { log = Logger.getLogger(this.getClass()); } return log; } /** Debug * * @param msg */ public void debugMsg(String msg) { getLogger().debug(msg); } /** Info messages * * @param msg */ public void logIt(String msg) { getLogger().info(msg); } protected void error(Throwable t) { getLogger().error(this, t); } }
true
true
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { WebdavNsIntf intf = null; boolean serverError = false; try { String debugStr = getInitParameter("debug"); if (debugStr != null) { debug = !"0".equals(debugStr); } if (debug) { debugMsg("entry: " + req.getMethod()); dumpRequest(req); } tryWait(req, true); intf = getNsIntf(req); if (req.getCharacterEncoding() == null) { req.setCharacterEncoding("UTF-8"); if (debug) { debugMsg("No charset specified in request; forced to UTF-8"); } } if (debug && dumpContent) { resp = new CharArrayWrappedResponse(resp, getLogger(), debug); } String methodName = req.getMethod(); MethodBase method = intf.getMethod(methodName); //resp.addHeader("DAV", intf.getDavHeader()); if (method == null) { logIt("No method for '" + methodName + "'"); // ================================================================ // Set the correct response // ================================================================ } else { method.doMethod(req, resp); } } catch (WebdavForbidden wdf) { sendError(intf, wdf, resp); } catch (Throwable t) { serverError = handleException(intf, t, resp, serverError); } finally { if (intf != null) { try { intf.close(); } catch (Throwable t) { serverError = handleException(intf, t, resp, serverError); } } try { tryWait(req, false); } catch (Throwable t) {} if (debug && dumpContent) { CharArrayWrappedResponse wresp = (CharArrayWrappedResponse)resp; if (wresp.getUsedOutputStream()) { debugMsg("------------------------ response written to output stream -------------------"); } else { String str = wresp.toString(); debugMsg("------------------------ Dump of response -------------------"); debugMsg(str); debugMsg("---------------------- End dump of response -----------------"); byte[] bs = str.getBytes(); resp = (HttpServletResponse)wresp.getResponse(); debugMsg("contentLength=" + bs.length); resp.setContentLength(bs.length); resp.getOutputStream().write(bs); } } /* WebDAV is stateless - toss away the session */ try { HttpSession sess = req.getSession(false); if (sess != null) { sess.invalidate(); } } catch (Throwable t) {} } }
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { WebdavNsIntf intf = null; boolean serverError = false; try { String debugStr = getInitParameter("debug"); if (debugStr != null) { debug = !"0".equals(debugStr); } if (debug) { debugMsg("entry: " + req.getMethod()); dumpRequest(req); } tryWait(req, true); intf = getNsIntf(req); if (req.getCharacterEncoding() == null) { req.setCharacterEncoding("UTF-8"); if (debug) { debugMsg("No charset specified in request; forced to UTF-8"); } } if (debug && dumpContent) { resp = new CharArrayWrappedResponse(resp, getLogger(), debug); } String methodName = req.getMethod(); MethodBase method = intf.getMethod(methodName); //resp.addHeader("DAV", intf.getDavHeader()); if (method == null) { logIt("No method for '" + methodName + "'"); // ================================================================ // Set the correct response // ================================================================ } else { method.doMethod(req, resp); } } catch (WebdavForbidden wdf) { sendError(intf, wdf, resp); } catch (Throwable t) { serverError = handleException(intf, t, resp, serverError); } finally { if (intf != null) { try { intf.close(); } catch (Throwable t) { serverError = handleException(intf, t, resp, serverError); } } try { tryWait(req, false); } catch (Throwable t) {} if (debug && dumpContent && (resp instanceof CharArrayWrappedResponse)) { /* instanceof check because we might get a subsequent exception before * we wrap the response */ CharArrayWrappedResponse wresp = (CharArrayWrappedResponse)resp; if (wresp.getUsedOutputStream()) { debugMsg("------------------------ response written to output stream -------------------"); } else { String str = wresp.toString(); debugMsg("------------------------ Dump of response -------------------"); debugMsg(str); debugMsg("---------------------- End dump of response -----------------"); byte[] bs = str.getBytes(); resp = (HttpServletResponse)wresp.getResponse(); debugMsg("contentLength=" + bs.length); resp.setContentLength(bs.length); resp.getOutputStream().write(bs); } } /* WebDAV is stateless - toss away the session */ try { HttpSession sess = req.getSession(false); if (sess != null) { sess.invalidate(); } } catch (Throwable t) {} } }
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java index 3d7772428..2ae69f840 100644 --- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java +++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java @@ -1,1027 +1,1027 @@ /* * ==================================================================== * Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.io.dav.http; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.text.ParseException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.zip.GZIPInputStream; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.TrustManager; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.BasicAuthenticationManager; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManagerExt; import org.tmatesoft.svn.core.auth.ISVNProxyManager; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVErrorHandler; import org.tmatesoft.svn.core.internal.util.ChunkedInputStream; import org.tmatesoft.svn.core.internal.util.FixedSizeInputStream; import org.tmatesoft.svn.core.internal.util.SVNSSLUtil; import org.tmatesoft.svn.core.internal.util.SVNSocketFactory; import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager; import org.tmatesoft.svn.core.internal.wc.IOExceptionWrapper; import org.tmatesoft.svn.core.internal.wc.SVNCancellableOutputStream; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * @version 1.3 * @author TMate Software Ltd. */ class HTTPConnection implements IHTTPConnection { private static final DefaultHandler DEFAULT_SAX_HANDLER = new DefaultHandler(); private static EntityResolver NO_ENTITY_RESOLVER = new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new ByteArrayInputStream(new byte[0])); } }; private static final int requestAttempts; private static final int DEFAULT_HTTP_TIMEOUT = 3600*1000; static { String attemptsString = System.getProperty("svnkit.http.requestAttempts", "1" ); int attempts = 1; try { attempts = Integer.parseInt(attemptsString); } catch (NumberFormatException nfe) { attempts = 1; } if (attempts <= 0) { attempts = 1; } requestAttempts = attempts; } private static SAXParserFactory ourSAXParserFactory; private byte[] myBuffer; private SAXParser mySAXParser; private SVNURL myHost; private OutputStream myOutputStream; private InputStream myInputStream; private Socket mySocket; private SVNRepository myRepository; private boolean myIsSecured; private boolean myIsProxied; private SVNAuthentication myLastValidAuth; private HTTPAuthentication myChallengeCredentials; private HTTPAuthentication myProxyAuthentication; private boolean myIsSpoolResponse; private TrustManager myTrustManager; private HTTPSSLKeyManager myKeyManager; private String myCharset; private boolean myIsSpoolAll; private File mySpoolDirectory; private long myNextRequestTimeout; private Collection<String> myCookies; private int myRequestCount; private HTTPStatus myLastStatus; public HTTPConnection(SVNRepository repository, String charset, File spoolDirectory, boolean spoolAll) throws SVNException { myRepository = repository; myCharset = charset; myHost = repository.getLocation().setPath("", false); myIsSecured = "https".equalsIgnoreCase(myHost.getProtocol()); myIsSpoolAll = spoolAll; mySpoolDirectory = spoolDirectory; myNextRequestTimeout = Long.MAX_VALUE; } public HTTPStatus getLastStatus() { return myLastStatus; } public SVNURL getHost() { return myHost; } private void connect(HTTPSSLKeyManager keyManager, TrustManager trustManager, ISVNProxyManager proxyManager) throws IOException, SVNException { SVNURL location = myRepository.getLocation(); if (mySocket == null || SVNSocketFactory.isSocketStale(mySocket)) { close(); String host = location.getHost(); int port = location.getPort(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); int connectTimeout = authManager != null ? authManager.getConnectTimeout(myRepository) : 0; int readTimeout = authManager != null ? authManager.getReadTimeout(myRepository) : DEFAULT_HTTP_TIMEOUT; if (readTimeout < 0) { readTimeout = DEFAULT_HTTP_TIMEOUT; } if (proxyManager != null && proxyManager.getProxyHost() != null) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, "Using proxy " + proxyManager.getProxyHost() + " (secured=" + myIsSecured + ")"); mySocket = SVNSocketFactory.createPlainSocket(proxyManager.getProxyHost(), proxyManager.getProxyPort(), connectTimeout, readTimeout, myRepository.getCanceller()); if (myProxyAuthentication == null) { myProxyAuthentication = new HTTPBasicAuthentication(proxyManager.getProxyUserName(), proxyManager.getProxyPassword(), myCharset); } myIsProxied = true; if (myIsSecured) { HTTPRequest connectRequest = new HTTPRequest(myCharset); connectRequest.setConnection(this); connectRequest.initCredentials(myProxyAuthentication, "CONNECT", host + ":" + port); connectRequest.setProxyAuthentication(myProxyAuthentication.authenticate()); connectRequest.setForceProxyAuth(true); connectRequest.dispatch("CONNECT", host + ":" + port, null, 0, 0, null); HTTPStatus status = connectRequest.getStatus(); if (status.getCode() == HttpURLConnection.HTTP_OK) { myInputStream = null; myOutputStream = null; mySocket = SVNSocketFactory.createSSLSocket(keyManager != null ? new KeyManager[] { keyManager } : new KeyManager[0], trustManager, host, port, mySocket, readTimeout); proxyManager.acknowledgeProxyContext(true, null); return; } SVNURL proxyURL = SVNURL.parseURIEncoded("http://" + proxyManager.getProxyHost() + ":" + proxyManager.getProxyPort()); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {"CONNECT", proxyURL}); proxyManager.acknowledgeProxyContext(false, err); SVNErrorManager.error(err, connectRequest.getErrorMessage(), SVNLogType.NETWORK); } } else { myIsProxied = false; myProxyAuthentication = null; mySocket = myIsSecured ? SVNSocketFactory.createSSLSocket(keyManager != null ? new KeyManager[] { keyManager } : new KeyManager[0], trustManager, host, port, connectTimeout, readTimeout, myRepository.getCanceller()) : SVNSocketFactory.createPlainSocket(host, port, connectTimeout, readTimeout, myRepository.getCanceller()); } } } public void readHeader(HTTPRequest request) throws IOException { InputStream is = myRepository.getDebugLog().createLogStream(SVNLogType.NETWORK, getInputStream()); try { // may throw EOF exception. HTTPStatus status = HTTPParser.parseStatus(is, myCharset); HTTPHeader header = HTTPHeader.parseHeader(is, myCharset); request.setStatus(status); request.setResponseHeader(header); } catch (ParseException e) { // in case of parse exception: // try to read remaining and log it. String line = HTTPParser.readLine(is, myCharset); while(line != null && line.length() > 0) { line = HTTPParser.readLine(is, myCharset); } throw new IOException(e.getMessage()); } finally { myRepository.getDebugLog().flushStream(is); } } public SVNErrorMessage readError(HTTPRequest request, String method, String path) { DAVErrorHandler errorHandler = new DAVErrorHandler(); try { readData(request, method, path, errorHandler); } catch (IOException e) { return null; } return errorHandler.getErrorMessage(); } public void sendData(byte[] body) throws IOException { try { getOutputStream().write(body, 0, body.length); getOutputStream().flush(); } finally { myRepository.getDebugLog().flushStream(getOutputStream()); } } public void sendData(InputStream source, long length) throws IOException { try { byte[] buffer = getBuffer(); while(length > 0) { int read = source.read(buffer, 0, (int) Math.min(buffer.length, length)); if (read > 0) { length -= read; getOutputStream().write(buffer, 0, read); } else if (read < 0) { break; } } getOutputStream().flush(); } finally { myRepository.getDebugLog().flushStream(getOutputStream()); } } public SVNAuthentication getLastValidCredentials() { return myLastValidAuth; } public void clearAuthenticationCache() { myCookies = null; myLastValidAuth = null; myTrustManager = null; myKeyManager = null; myChallengeCredentials = null; myProxyAuthentication = null; myRequestCount = 0; } public HTTPStatus request(String method, String path, HTTPHeader header, StringBuffer body, int ok1, int ok2, OutputStream dst, DefaultHandler handler) throws SVNException { return request(method, path, header, body, ok1, ok2, dst, handler, null); } public HTTPStatus request(String method, String path, HTTPHeader header, StringBuffer body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException { byte[] buffer = null; if (body != null) { try { buffer = body.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { buffer = body.toString().getBytes(); } } return request(method, path, header, buffer != null ? new ByteArrayInputStream(buffer) : null, ok1, ok2, dst, handler, context); } public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler) throws SVNException { return request(method, path, header, body, ok1, ok2, dst, handler, null); } public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException { myLastStatus = null; myRequestCount++; if ("".equals(path) || path == null) { path = "/"; } ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); // 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception. HTTPSSLKeyManager keyManager = myKeyManager == null && authManager != null ? createKeyManager() : myKeyManager; TrustManager trustManager = myTrustManager == null && authManager != null ? authManager.getTrustManager(myRepository.getLocation()) : myTrustManager; ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(myRepository.getLocation()) : null; String sslRealm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">"; SVNAuthentication httpAuth = myLastValidAuth; boolean isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false; if (httpAuth == null && isAuthForced) { httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null); myChallengeCredentials = new HTTPBasicAuthentication((SVNPasswordAuthentication)httpAuth, myCharset); } String realm = null; // 2. create request instance. HTTPRequest request = new HTTPRequest(myCharset); request.setConnection(this); request.setKeepAlive(true); request.setRequestBody(body); request.setResponseHandler(handler); request.setResponseStream(dst); SVNErrorMessage err = null; boolean ntlmAuthIsRequired = false; boolean ntlmProxyAuthIsRequired = false; boolean negoAuthIsRequired = false; int authAttempts = 0; while (true) { if (myNextRequestTimeout < 0 || System.currentTimeMillis() >= myNextRequestTimeout) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "Keep-Alive timeout detected"); close(); if (isClearCredentialsOnClose(myChallengeCredentials)) { httpAuth = null; } } int retryCount = 1; try { err = null; String httpAuthResponse = null; String proxyAuthResponse = null; while(retryCount >= 0) { connect(keyManager, trustManager, proxyManager); request.reset(); request.setProxied(myIsProxied); request.setSecured(myIsSecured); if (myProxyAuthentication != null && (ntlmProxyAuthIsRequired || !"NTLM".equals(myProxyAuthentication.getAuthenticationScheme()))) { if (proxyAuthResponse == null) { request.initCredentials(myProxyAuthentication, method, path); proxyAuthResponse = myProxyAuthentication.authenticate(); } request.setProxyAuthentication(proxyAuthResponse); } if (myChallengeCredentials != null && (ntlmAuthIsRequired || negoAuthIsRequired || ((!"NTLM".equals(myChallengeCredentials.getAuthenticationScheme())) && !"Negotiate".equals(myChallengeCredentials.getAuthenticationScheme())) && httpAuth != null)) { if (httpAuthResponse == null) { request.initCredentials(myChallengeCredentials, method, path); httpAuthResponse = myChallengeCredentials.authenticate(); } request.setAuthentication(httpAuthResponse); } if (myCookies != null && !myCookies.isEmpty()) { request.setCookies(myCookies); } try { request.dispatch(method, path, header, ok1, ok2, context); break; } catch (EOFException pe) { // retry, EOF always means closed connection. if (retryCount > 0) { close(); continue; } throw (IOException) new IOException(pe.getMessage()).initCause(pe); } finally { retryCount--; } } if (request.getResponseHeader().hasHeader(HTTPHeader.SET_COOKIE)) { myCookies = request.getResponseHeader().getHeaderValues(HTTPHeader.COOKIE); } myNextRequestTimeout = request.getNextRequestTimeout(); myLastStatus = request.getStatus(); } catch (SSLHandshakeException ssl) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, ssl); close(); if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) { SVNErrorManager.cancel(ssl.getCause().getMessage(), SVNLogType.NETWORK); } SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "SSL handshake failed: ''{0}''", new Object[] { ssl.getMessage() }, SVNErrorMessage.TYPE_ERROR, ssl); if (keyManager != null) { keyManager.acknowledgeAndClearAuthentication(sslErr); } err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl); continue; } catch (IOException e) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e); if (e instanceof SocketTimeoutException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "timed out waiting for server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof UnknownHostException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "unknown host", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof ConnectException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "connection refused by the server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof SVNCancellableOutputStream.IOCancelException) { SVNErrorManager.cancel(e.getMessage(), SVNLogType.NETWORK); } else if (e instanceof SSLException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, - e.getMessage()); + e); } else { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, - e.getMessage()); + e); } } catch (SVNException e) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e); // force connection close on SVNException // (could be thrown by user's auth manager methods). close(); throw e; } finally { finishResponse(request); } if (err != null) { if (proxyManager != null) { proxyManager.acknowledgeProxyContext(false, err); } close(); break; } if (proxyManager != null) { proxyManager.acknowledgeProxyContext(true, err); } if (keyManager != null) { myKeyManager = keyManager; myTrustManager = trustManager; keyManager.acknowledgeAndClearAuthentication(null); } if (myLastStatus.getCode() == HttpURLConnection.HTTP_FORBIDDEN) { if (httpAuth != null && authManager != null) { BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager); } myLastValidAuth = null; close(); err = request.getErrorMessage(); } else if (myIsProxied && myLastStatus.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) { Collection<String> proxyAuthHeaders = request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER); Collection<String> authTypes = null; if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) { DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager; authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation()); } try { myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset, authTypes, null, myRequestCount); } catch (SVNException svne) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, svne); err = svne.getErrorMessage(); break; } if (myProxyAuthentication instanceof HTTPNTLMAuthentication) { ntlmProxyAuthIsRequired = true; HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication)myProxyAuthentication; if (ntlmProxyAuth.isInType3State()) { continue; } } err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed"); if (proxyManager != null) { proxyManager.acknowledgeProxyContext(false, err); } close(); break; } else if (myLastStatus.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { authAttempts++;//how many times did we try? Collection<String> authHeaderValues = request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER); if (authHeaderValues == null || authHeaderValues.size() == 0) { err = request.getErrorMessage(); myLastStatus.setError(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, err.getMessageTemplate(), err.getRelatedObjects())); if ("LOCK".equalsIgnoreCase(method)) { myLastStatus.getError().setChildErrorMessage(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Probably you are trying to lock file in repository that only allows anonymous access")); } SVNErrorManager.error(myLastStatus.getError(), SVNLogType.NETWORK); return myLastStatus; } //we should work around a situation when a server //does not support Basic authentication while we're //forcing it, credentials should not be immediately //thrown away boolean skip = false; isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false; if (isAuthForced) { if (httpAuth != null && myChallengeCredentials != null && !HTTPAuthentication.isSchemeSupportedByServer(myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) { skip = true; } } Collection<String> authTypes = null; if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) { DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager; authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation()); } try { myChallengeCredentials = HTTPAuthentication.parseAuthParameters(authHeaderValues, myChallengeCredentials, myCharset, authTypes, authManager, myRequestCount); } catch (SVNException svne) { err = svne.getErrorMessage(); break; } myChallengeCredentials.setChallengeParameter("method", method); myChallengeCredentials.setChallengeParameter("uri", HTTPParser.getCanonicalPath(path, null).toString()); if (skip) { close(); continue; } HTTPNTLMAuthentication ntlmAuth = null; HTTPNegotiateAuthentication negoAuth = null; if (myChallengeCredentials instanceof HTTPNTLMAuthentication) { ntlmAuthIsRequired = true; ntlmAuth = (HTTPNTLMAuthentication)myChallengeCredentials; if (ntlmAuth.isInType3State()) { continue; } } else if (myChallengeCredentials instanceof HTTPDigestAuthentication) { // continue (retry once) if previous request was acceppted? if (myLastValidAuth != null) { myLastValidAuth = null; continue; } } else if (myChallengeCredentials instanceof HTTPNegotiateAuthentication) { negoAuthIsRequired = true; negoAuth = (HTTPNegotiateAuthentication)myChallengeCredentials; if (negoAuth.isStarted()) { continue; } } myLastValidAuth = null; if (ntlmAuth != null && ntlmAuth.isNative() && authAttempts == 1) { /* * if this is the first time we get HTTP_UNAUTHORIZED, NTLM is the target auth scheme * and JNA is available, we should try a native auth mechanism first without calling * auth providers. */ continue; } if (negoAuth != null && !negoAuth.needsLogin()) { continue; } if (authManager == null) { err = request.getErrorMessage(); break; } realm = myChallengeCredentials.getChallengeParameter("realm"); realm = realm == null ? "" : " " + realm; realm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">" + realm; if (httpAuth == null) { httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } else if (authAttempts >= requestAttempts) { BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager); httpAuth = authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } if (httpAuth == null) { err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, "HTTP authorization cancelled"); break; } if (httpAuth != null) { myChallengeCredentials.setCredentials((SVNPasswordAuthentication) httpAuth); } continue; } else if (myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_PERM || myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) { String newLocation = request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER); if (newLocation == null) { err = request.getErrorMessage(); break; } int hostIndex = newLocation.indexOf("://"); if (hostIndex > 0) { hostIndex += 3; hostIndex = newLocation.indexOf("/", hostIndex); } if (hostIndex > 0 && hostIndex < newLocation.length()) { String newPath = newLocation.substring(hostIndex); if (newPath.endsWith("/") && !newPath.endsWith("//") && !path.endsWith("/") && newPath.substring(0, newPath.length() - 1).equals(path)) { path += "//"; continue; } } err = request.getErrorMessage(); close(); } else if (request.getErrorMessage() != null) { err = request.getErrorMessage(); } else { ntlmProxyAuthIsRequired = false; ntlmAuthIsRequired = false; negoAuthIsRequired = false; } if (err != null) { break; } if (myIsProxied) { if (proxyManager != null) { proxyManager.acknowledgeProxyContext(true, null); } } if (httpAuth != null && realm != null && authManager != null) { BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth, myRepository.getLocation(), authManager); } if (trustManager != null && authManager != null) { authManager.acknowledgeTrustManager(trustManager); } if (httpAuth != null) { myLastValidAuth = httpAuth; } if (authManager instanceof ISVNAuthenticationManagerExt) { ((ISVNAuthenticationManagerExt)authManager).acknowledgeConnectionSuccessful(myRepository.getLocation()); } myLastStatus.setHeader(request.getResponseHeader()); return myLastStatus; } // force close on error that was not processed before. // these are errors that has no relation to http status (processing error or cancellation). close(); if (err != null && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY && err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) { SVNErrorManager.error(err, SVNLogType.NETWORK); } // err2 is another default context... myRepository.getDebugLog().logFine(SVNLogType.NETWORK, new Exception(err.getMessage())); SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {method, path}, err.getType(), err.getCause()); SVNErrorManager.error(err, err2, SVNLogType.NETWORK); return null; } private boolean isClearCredentialsOnClose(HTTPAuthentication auth) { return !(auth instanceof HTTPBasicAuthentication || auth instanceof HTTPDigestAuthentication || auth instanceof HTTPNegotiateAuthentication); } private HTTPSSLKeyManager createKeyManager() { if (!myIsSecured) { return null; } SVNURL location = myRepository.getLocation(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); String sslRealm = "<" + location.getProtocol() + "://" + location.getHost() + ":" + location.getPort() + ">"; return new HTTPSSLKeyManager(authManager, sslRealm, location); } public SVNErrorMessage readData(HTTPRequest request, OutputStream dst) throws IOException { InputStream stream = createInputStream(request.getResponseHeader(), getInputStream()); byte[] buffer = getBuffer(); boolean willCloseConnection = false; try { while (true) { int count = stream.read(buffer); if (count < 0) { break; } if (dst != null) { dst.write(buffer, 0, count); } } } catch (IOException e) { willCloseConnection = true; if (e instanceof IOExceptionWrapper) { IOExceptionWrapper wrappedException = (IOExceptionWrapper) e; return wrappedException.getOriginalException().getErrorMessage(); } if (e.getCause() instanceof SVNException) { return ((SVNException) e.getCause()).getErrorMessage(); } throw e; } finally { if (!willCloseConnection) { SVNFileUtil.closeFile(stream); } myRepository.getDebugLog().flushStream(stream); } return null; } public SVNErrorMessage readData(HTTPRequest request, String method, String path, DefaultHandler handler) throws IOException { InputStream is = null; SpoolFile tmpFile = null; SVNErrorMessage err = null; try { if (myIsSpoolResponse || myIsSpoolAll) { OutputStream dst = null; try { tmpFile = new SpoolFile(mySpoolDirectory); dst = tmpFile.openForWriting(); dst = new SVNCancellableOutputStream(dst, myRepository.getCanceller()); // this will exhaust http stream anyway. err = readData(request, dst); SVNFileUtil.closeFile(dst); dst = null; if (err != null) { return err; } // this stream always have to be closed. is = tmpFile.openForReading(); } finally { SVNFileUtil.closeFile(dst); } } else { is = createInputStream(request.getResponseHeader(), getInputStream()); } // this will not close is stream. err = readData(is, method, path, handler); } catch (IOException e) { throw e; } finally { if (myIsSpoolResponse || myIsSpoolAll) { // always close spooled stream. SVNFileUtil.closeFile(is); } else if (err == null && !hasToCloseConnection(request.getResponseHeader())) { // exhaust stream if connection is not about to be closed. SVNFileUtil.closeFile(is); } if (tmpFile != null) { try { tmpFile.delete(); } catch (SVNException e) { throw new IOException(e.getMessage()); } } myIsSpoolResponse = false; } return err; } private SVNErrorMessage readData(InputStream is, String method, String path, DefaultHandler handler) throws FactoryConfigurationError, UnsupportedEncodingException, IOException { try { if (mySAXParser == null) { mySAXParser = getSAXParserFactory().newSAXParser(); } XMLReader reader = new XMLReader(is); while (!reader.isClosed()) { org.xml.sax.XMLReader xmlReader = mySAXParser.getXMLReader(); xmlReader.setContentHandler(handler); xmlReader.setDTDHandler(handler); xmlReader.setErrorHandler(handler); xmlReader.setEntityResolver(NO_ENTITY_RESOLVER); xmlReader.parse(new InputSource(reader)); } } catch (SAXException e) { mySAXParser = null; if (e instanceof SAXParseException) { if (handler instanceof DAVErrorHandler) { // failed to read svn-specific error, return null. return null; } } else if (e.getException() instanceof SVNException) { return ((SVNException) e.getException()).getErrorMessage(); } else if (e.getCause() instanceof SVNException) { return ((SVNException) e.getCause()).getErrorMessage(); } return SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Processing {0} request response failed: {1} ({2}) ", new Object[] {method, e.getMessage(), path}); } catch (ParserConfigurationException e) { mySAXParser = null; return SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "XML parser configuration error while processing {0} request response: {1} ({2}) ", new Object[] {method, e.getMessage(), path}); } catch (EOFException e) { // skip it. } finally { if (mySAXParser != null) { // to avoid memory leaks when connection is cached. org.xml.sax.XMLReader xmlReader = null; try { xmlReader = mySAXParser.getXMLReader(); } catch (SAXException e) { } if (xmlReader != null) { xmlReader.setContentHandler(DEFAULT_SAX_HANDLER); xmlReader.setDTDHandler(DEFAULT_SAX_HANDLER); xmlReader.setErrorHandler(DEFAULT_SAX_HANDLER); xmlReader.setEntityResolver(NO_ENTITY_RESOLVER); } } myRepository.getDebugLog().flushStream(is); } return null; } public void skipData(HTTPRequest request) throws IOException { if (hasToCloseConnection(request.getResponseHeader())) { return; } InputStream is = createInputStream(request.getResponseHeader(), getInputStream()); while(is.skip(2048) > 0); } public void close() { if (isClearCredentialsOnClose(myChallengeCredentials)) { clearAuthenticationCache(); } if (mySocket != null) { if (myInputStream != null) { try { myInputStream.close(); } catch (IOException e) {} } if (myOutputStream != null) { try { myOutputStream.flush(); } catch (IOException e) {} } if (myOutputStream != null) { try { myOutputStream.close(); } catch (IOException e) {} } try { mySocket.close(); } catch (IOException e) {} mySocket = null; myOutputStream = null; myInputStream = null; } } private byte[] getBuffer() { if (myBuffer == null) { myBuffer = new byte[32*1024]; } return myBuffer; } private InputStream getInputStream() throws IOException { if (myInputStream == null) { if (mySocket == null) { return null; } // myInputStream = new CancellableSocketInputStream(new BufferedInputStream(mySocket.getInputStream(), 2048), myRepository.getCanceller()); myInputStream = new BufferedInputStream(mySocket.getInputStream(), 2048); } return myInputStream; } private OutputStream getOutputStream() throws IOException { SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "socket output stream requested..."); if (myOutputStream == null) { if (mySocket == null) { return null; } myOutputStream = new BufferedOutputStream(mySocket.getOutputStream(), 2048); myOutputStream = myRepository.getDebugLog().createLogStream(SVNLogType.NETWORK, myOutputStream); } return myOutputStream; } private void finishResponse(HTTPRequest request) { if (myOutputStream != null) { try { myOutputStream.flush(); } catch (IOException ex) { } } HTTPHeader header = request != null ? request.getResponseHeader() : null; if (hasToCloseConnection(header)) { close(); } } private static boolean hasToCloseConnection(HTTPHeader header) { if (header == null) { return true; } String connectionHeader = header.getFirstHeaderValue(HTTPHeader.CONNECTION_HEADER); String proxyHeader = header.getFirstHeaderValue(HTTPHeader.PROXY_CONNECTION_HEADER); if (connectionHeader != null && connectionHeader.toLowerCase().indexOf("close") >= 0) { return true; } else if (proxyHeader != null && proxyHeader.toLowerCase().indexOf("close") >= 0) { return true; } return false; } private InputStream createInputStream(HTTPHeader readHeader, InputStream is) throws IOException { if ("chunked".equalsIgnoreCase(readHeader.getFirstHeaderValue(HTTPHeader.TRANSFER_ENCODING_HEADER))) { is = new ChunkedInputStream(is, myCharset); } else if (readHeader.getFirstHeaderValue(HTTPHeader.CONTENT_LENGTH_HEADER) != null) { String lengthStr = readHeader.getFirstHeaderValue(HTTPHeader.CONTENT_LENGTH_HEADER); long length = 0; try { length = Long.parseLong(lengthStr); } catch (NumberFormatException nfe) { length = 0; } is = new FixedSizeInputStream(is, length); } else if (!hasToCloseConnection(readHeader)) { // no content length and no valid transfer-encoding! // consider as empty response. // but only when there is no "Connection: close" or "Proxy-Connection: close" header, // in that case just return "is". // skipData will not read that as it should also analyze "close" instruction. // return empty stream. // and force connection close? (not to read garbage on the next request). is = new FixedSizeInputStream(is, 0); // this will force connection to close. readHeader.setHeaderValue(HTTPHeader.CONNECTION_HEADER, "close"); } if ("gzip".equals(readHeader.getFirstHeaderValue(HTTPHeader.CONTENT_ENCODING_HEADER))) { is = new GZIPInputStream(is); } return myRepository.getDebugLog().createLogStream(SVNLogType.NETWORK, is); } private static synchronized SAXParserFactory getSAXParserFactory() throws FactoryConfigurationError { if (ourSAXParserFactory == null) { ourSAXParserFactory = createSAXParserFactory(); Map<String, Object> supportedFeatures = new HashMap<String, Object>(); try { ourSAXParserFactory.setFeature("http://xml.org/sax/features/namespaces", true); supportedFeatures.put("http://xml.org/sax/features/namespaces", Boolean.TRUE); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } try { ourSAXParserFactory.setFeature("http://xml.org/sax/features/validation", false); supportedFeatures.put("http://xml.org/sax/features/validation", Boolean.FALSE); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } try { ourSAXParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); supportedFeatures.put("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } if (supportedFeatures.size() < 3) { ourSAXParserFactory = createSAXParserFactory(); for (Iterator<String> names = supportedFeatures.keySet().iterator(); names.hasNext();) { String name = names.next(); try { ourSAXParserFactory.setFeature(name, supportedFeatures.get(name) == Boolean.TRUE); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } } } ourSAXParserFactory.setNamespaceAware(true); ourSAXParserFactory.setValidating(false); } return ourSAXParserFactory; } public static SAXParserFactory createSAXParserFactory() { String legacy = System.getProperty("svnkit.sax.useDefault"); if (legacy == null || !Boolean.valueOf(legacy).booleanValue()) { return SAXParserFactory.newInstance(); } // instantiate JVM parser. String[] parsers = {"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", // 1.5, 1.6 "org.apache.crimson.jaxp.SAXParserFactoryImpl", // 1.4 }; for (int i = 0; i < parsers.length; i++) { String className = parsers[i]; ClassLoader loader = HTTPConnection.class.getClassLoader(); try { Class<?> clazz = null; if (loader != null) { clazz = loader.loadClass(className); } else { clazz = Class.forName(className); } if (clazz != null) { Object factory = clazz.newInstance(); if (factory instanceof SAXParserFactory) { return (SAXParserFactory) factory; } } } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } } return SAXParserFactory.newInstance(); } public void setSpoolResponse(boolean spoolResponse) { myIsSpoolResponse = spoolResponse; } }
false
true
public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException { myLastStatus = null; myRequestCount++; if ("".equals(path) || path == null) { path = "/"; } ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); // 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception. HTTPSSLKeyManager keyManager = myKeyManager == null && authManager != null ? createKeyManager() : myKeyManager; TrustManager trustManager = myTrustManager == null && authManager != null ? authManager.getTrustManager(myRepository.getLocation()) : myTrustManager; ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(myRepository.getLocation()) : null; String sslRealm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">"; SVNAuthentication httpAuth = myLastValidAuth; boolean isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false; if (httpAuth == null && isAuthForced) { httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null); myChallengeCredentials = new HTTPBasicAuthentication((SVNPasswordAuthentication)httpAuth, myCharset); } String realm = null; // 2. create request instance. HTTPRequest request = new HTTPRequest(myCharset); request.setConnection(this); request.setKeepAlive(true); request.setRequestBody(body); request.setResponseHandler(handler); request.setResponseStream(dst); SVNErrorMessage err = null; boolean ntlmAuthIsRequired = false; boolean ntlmProxyAuthIsRequired = false; boolean negoAuthIsRequired = false; int authAttempts = 0; while (true) { if (myNextRequestTimeout < 0 || System.currentTimeMillis() >= myNextRequestTimeout) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "Keep-Alive timeout detected"); close(); if (isClearCredentialsOnClose(myChallengeCredentials)) { httpAuth = null; } } int retryCount = 1; try { err = null; String httpAuthResponse = null; String proxyAuthResponse = null; while(retryCount >= 0) { connect(keyManager, trustManager, proxyManager); request.reset(); request.setProxied(myIsProxied); request.setSecured(myIsSecured); if (myProxyAuthentication != null && (ntlmProxyAuthIsRequired || !"NTLM".equals(myProxyAuthentication.getAuthenticationScheme()))) { if (proxyAuthResponse == null) { request.initCredentials(myProxyAuthentication, method, path); proxyAuthResponse = myProxyAuthentication.authenticate(); } request.setProxyAuthentication(proxyAuthResponse); } if (myChallengeCredentials != null && (ntlmAuthIsRequired || negoAuthIsRequired || ((!"NTLM".equals(myChallengeCredentials.getAuthenticationScheme())) && !"Negotiate".equals(myChallengeCredentials.getAuthenticationScheme())) && httpAuth != null)) { if (httpAuthResponse == null) { request.initCredentials(myChallengeCredentials, method, path); httpAuthResponse = myChallengeCredentials.authenticate(); } request.setAuthentication(httpAuthResponse); } if (myCookies != null && !myCookies.isEmpty()) { request.setCookies(myCookies); } try { request.dispatch(method, path, header, ok1, ok2, context); break; } catch (EOFException pe) { // retry, EOF always means closed connection. if (retryCount > 0) { close(); continue; } throw (IOException) new IOException(pe.getMessage()).initCause(pe); } finally { retryCount--; } } if (request.getResponseHeader().hasHeader(HTTPHeader.SET_COOKIE)) { myCookies = request.getResponseHeader().getHeaderValues(HTTPHeader.COOKIE); } myNextRequestTimeout = request.getNextRequestTimeout(); myLastStatus = request.getStatus(); } catch (SSLHandshakeException ssl) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, ssl); close(); if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) { SVNErrorManager.cancel(ssl.getCause().getMessage(), SVNLogType.NETWORK); } SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "SSL handshake failed: ''{0}''", new Object[] { ssl.getMessage() }, SVNErrorMessage.TYPE_ERROR, ssl); if (keyManager != null) { keyManager.acknowledgeAndClearAuthentication(sslErr); } err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl); continue; } catch (IOException e) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e); if (e instanceof SocketTimeoutException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "timed out waiting for server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof UnknownHostException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "unknown host", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof ConnectException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "connection refused by the server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof SVNCancellableOutputStream.IOCancelException) { SVNErrorManager.cancel(e.getMessage(), SVNLogType.NETWORK); } else if (e instanceof SSLException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e.getMessage()); } else { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e.getMessage()); } } catch (SVNException e) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e); // force connection close on SVNException // (could be thrown by user's auth manager methods). close(); throw e; } finally { finishResponse(request); } if (err != null) { if (proxyManager != null) { proxyManager.acknowledgeProxyContext(false, err); } close(); break; } if (proxyManager != null) { proxyManager.acknowledgeProxyContext(true, err); } if (keyManager != null) { myKeyManager = keyManager; myTrustManager = trustManager; keyManager.acknowledgeAndClearAuthentication(null); } if (myLastStatus.getCode() == HttpURLConnection.HTTP_FORBIDDEN) { if (httpAuth != null && authManager != null) { BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager); } myLastValidAuth = null; close(); err = request.getErrorMessage(); } else if (myIsProxied && myLastStatus.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) { Collection<String> proxyAuthHeaders = request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER); Collection<String> authTypes = null; if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) { DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager; authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation()); } try { myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset, authTypes, null, myRequestCount); } catch (SVNException svne) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, svne); err = svne.getErrorMessage(); break; } if (myProxyAuthentication instanceof HTTPNTLMAuthentication) { ntlmProxyAuthIsRequired = true; HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication)myProxyAuthentication; if (ntlmProxyAuth.isInType3State()) { continue; } } err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed"); if (proxyManager != null) { proxyManager.acknowledgeProxyContext(false, err); } close(); break; } else if (myLastStatus.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { authAttempts++;//how many times did we try? Collection<String> authHeaderValues = request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER); if (authHeaderValues == null || authHeaderValues.size() == 0) { err = request.getErrorMessage(); myLastStatus.setError(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, err.getMessageTemplate(), err.getRelatedObjects())); if ("LOCK".equalsIgnoreCase(method)) { myLastStatus.getError().setChildErrorMessage(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Probably you are trying to lock file in repository that only allows anonymous access")); } SVNErrorManager.error(myLastStatus.getError(), SVNLogType.NETWORK); return myLastStatus; } //we should work around a situation when a server //does not support Basic authentication while we're //forcing it, credentials should not be immediately //thrown away boolean skip = false; isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false; if (isAuthForced) { if (httpAuth != null && myChallengeCredentials != null && !HTTPAuthentication.isSchemeSupportedByServer(myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) { skip = true; } } Collection<String> authTypes = null; if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) { DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager; authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation()); } try { myChallengeCredentials = HTTPAuthentication.parseAuthParameters(authHeaderValues, myChallengeCredentials, myCharset, authTypes, authManager, myRequestCount); } catch (SVNException svne) { err = svne.getErrorMessage(); break; } myChallengeCredentials.setChallengeParameter("method", method); myChallengeCredentials.setChallengeParameter("uri", HTTPParser.getCanonicalPath(path, null).toString()); if (skip) { close(); continue; } HTTPNTLMAuthentication ntlmAuth = null; HTTPNegotiateAuthentication negoAuth = null; if (myChallengeCredentials instanceof HTTPNTLMAuthentication) { ntlmAuthIsRequired = true; ntlmAuth = (HTTPNTLMAuthentication)myChallengeCredentials; if (ntlmAuth.isInType3State()) { continue; } } else if (myChallengeCredentials instanceof HTTPDigestAuthentication) { // continue (retry once) if previous request was acceppted? if (myLastValidAuth != null) { myLastValidAuth = null; continue; } } else if (myChallengeCredentials instanceof HTTPNegotiateAuthentication) { negoAuthIsRequired = true; negoAuth = (HTTPNegotiateAuthentication)myChallengeCredentials; if (negoAuth.isStarted()) { continue; } } myLastValidAuth = null; if (ntlmAuth != null && ntlmAuth.isNative() && authAttempts == 1) { /* * if this is the first time we get HTTP_UNAUTHORIZED, NTLM is the target auth scheme * and JNA is available, we should try a native auth mechanism first without calling * auth providers. */ continue; } if (negoAuth != null && !negoAuth.needsLogin()) { continue; } if (authManager == null) { err = request.getErrorMessage(); break; } realm = myChallengeCredentials.getChallengeParameter("realm"); realm = realm == null ? "" : " " + realm; realm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">" + realm; if (httpAuth == null) { httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } else if (authAttempts >= requestAttempts) { BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager); httpAuth = authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } if (httpAuth == null) { err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, "HTTP authorization cancelled"); break; } if (httpAuth != null) { myChallengeCredentials.setCredentials((SVNPasswordAuthentication) httpAuth); } continue; } else if (myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_PERM || myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) { String newLocation = request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER); if (newLocation == null) { err = request.getErrorMessage(); break; } int hostIndex = newLocation.indexOf("://"); if (hostIndex > 0) { hostIndex += 3; hostIndex = newLocation.indexOf("/", hostIndex); } if (hostIndex > 0 && hostIndex < newLocation.length()) { String newPath = newLocation.substring(hostIndex); if (newPath.endsWith("/") && !newPath.endsWith("//") && !path.endsWith("/") && newPath.substring(0, newPath.length() - 1).equals(path)) { path += "//"; continue; } } err = request.getErrorMessage(); close(); } else if (request.getErrorMessage() != null) { err = request.getErrorMessage(); } else { ntlmProxyAuthIsRequired = false; ntlmAuthIsRequired = false; negoAuthIsRequired = false; } if (err != null) { break; } if (myIsProxied) { if (proxyManager != null) { proxyManager.acknowledgeProxyContext(true, null); } } if (httpAuth != null && realm != null && authManager != null) { BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth, myRepository.getLocation(), authManager); } if (trustManager != null && authManager != null) { authManager.acknowledgeTrustManager(trustManager); } if (httpAuth != null) { myLastValidAuth = httpAuth; } if (authManager instanceof ISVNAuthenticationManagerExt) { ((ISVNAuthenticationManagerExt)authManager).acknowledgeConnectionSuccessful(myRepository.getLocation()); } myLastStatus.setHeader(request.getResponseHeader()); return myLastStatus; } // force close on error that was not processed before. // these are errors that has no relation to http status (processing error or cancellation). close(); if (err != null && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY && err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) { SVNErrorManager.error(err, SVNLogType.NETWORK); } // err2 is another default context... myRepository.getDebugLog().logFine(SVNLogType.NETWORK, new Exception(err.getMessage())); SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {method, path}, err.getType(), err.getCause()); SVNErrorManager.error(err, err2, SVNLogType.NETWORK); return null; }
public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException { myLastStatus = null; myRequestCount++; if ("".equals(path) || path == null) { path = "/"; } ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); // 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception. HTTPSSLKeyManager keyManager = myKeyManager == null && authManager != null ? createKeyManager() : myKeyManager; TrustManager trustManager = myTrustManager == null && authManager != null ? authManager.getTrustManager(myRepository.getLocation()) : myTrustManager; ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(myRepository.getLocation()) : null; String sslRealm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">"; SVNAuthentication httpAuth = myLastValidAuth; boolean isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false; if (httpAuth == null && isAuthForced) { httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null); myChallengeCredentials = new HTTPBasicAuthentication((SVNPasswordAuthentication)httpAuth, myCharset); } String realm = null; // 2. create request instance. HTTPRequest request = new HTTPRequest(myCharset); request.setConnection(this); request.setKeepAlive(true); request.setRequestBody(body); request.setResponseHandler(handler); request.setResponseStream(dst); SVNErrorMessage err = null; boolean ntlmAuthIsRequired = false; boolean ntlmProxyAuthIsRequired = false; boolean negoAuthIsRequired = false; int authAttempts = 0; while (true) { if (myNextRequestTimeout < 0 || System.currentTimeMillis() >= myNextRequestTimeout) { SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "Keep-Alive timeout detected"); close(); if (isClearCredentialsOnClose(myChallengeCredentials)) { httpAuth = null; } } int retryCount = 1; try { err = null; String httpAuthResponse = null; String proxyAuthResponse = null; while(retryCount >= 0) { connect(keyManager, trustManager, proxyManager); request.reset(); request.setProxied(myIsProxied); request.setSecured(myIsSecured); if (myProxyAuthentication != null && (ntlmProxyAuthIsRequired || !"NTLM".equals(myProxyAuthentication.getAuthenticationScheme()))) { if (proxyAuthResponse == null) { request.initCredentials(myProxyAuthentication, method, path); proxyAuthResponse = myProxyAuthentication.authenticate(); } request.setProxyAuthentication(proxyAuthResponse); } if (myChallengeCredentials != null && (ntlmAuthIsRequired || negoAuthIsRequired || ((!"NTLM".equals(myChallengeCredentials.getAuthenticationScheme())) && !"Negotiate".equals(myChallengeCredentials.getAuthenticationScheme())) && httpAuth != null)) { if (httpAuthResponse == null) { request.initCredentials(myChallengeCredentials, method, path); httpAuthResponse = myChallengeCredentials.authenticate(); } request.setAuthentication(httpAuthResponse); } if (myCookies != null && !myCookies.isEmpty()) { request.setCookies(myCookies); } try { request.dispatch(method, path, header, ok1, ok2, context); break; } catch (EOFException pe) { // retry, EOF always means closed connection. if (retryCount > 0) { close(); continue; } throw (IOException) new IOException(pe.getMessage()).initCause(pe); } finally { retryCount--; } } if (request.getResponseHeader().hasHeader(HTTPHeader.SET_COOKIE)) { myCookies = request.getResponseHeader().getHeaderValues(HTTPHeader.COOKIE); } myNextRequestTimeout = request.getNextRequestTimeout(); myLastStatus = request.getStatus(); } catch (SSLHandshakeException ssl) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, ssl); close(); if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) { SVNErrorManager.cancel(ssl.getCause().getMessage(), SVNLogType.NETWORK); } SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "SSL handshake failed: ''{0}''", new Object[] { ssl.getMessage() }, SVNErrorMessage.TYPE_ERROR, ssl); if (keyManager != null) { keyManager.acknowledgeAndClearAuthentication(sslErr); } err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl); continue; } catch (IOException e) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e); if (e instanceof SocketTimeoutException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "timed out waiting for server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof UnknownHostException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "unknown host", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof ConnectException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "connection refused by the server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof SVNCancellableOutputStream.IOCancelException) { SVNErrorManager.cancel(e.getMessage(), SVNLogType.NETWORK); } else if (e instanceof SSLException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e); } else { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e); } } catch (SVNException e) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e); // force connection close on SVNException // (could be thrown by user's auth manager methods). close(); throw e; } finally { finishResponse(request); } if (err != null) { if (proxyManager != null) { proxyManager.acknowledgeProxyContext(false, err); } close(); break; } if (proxyManager != null) { proxyManager.acknowledgeProxyContext(true, err); } if (keyManager != null) { myKeyManager = keyManager; myTrustManager = trustManager; keyManager.acknowledgeAndClearAuthentication(null); } if (myLastStatus.getCode() == HttpURLConnection.HTTP_FORBIDDEN) { if (httpAuth != null && authManager != null) { BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager); } myLastValidAuth = null; close(); err = request.getErrorMessage(); } else if (myIsProxied && myLastStatus.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) { Collection<String> proxyAuthHeaders = request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER); Collection<String> authTypes = null; if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) { DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager; authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation()); } try { myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset, authTypes, null, myRequestCount); } catch (SVNException svne) { myRepository.getDebugLog().logFine(SVNLogType.NETWORK, svne); err = svne.getErrorMessage(); break; } if (myProxyAuthentication instanceof HTTPNTLMAuthentication) { ntlmProxyAuthIsRequired = true; HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication)myProxyAuthentication; if (ntlmProxyAuth.isInType3State()) { continue; } } err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed"); if (proxyManager != null) { proxyManager.acknowledgeProxyContext(false, err); } close(); break; } else if (myLastStatus.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { authAttempts++;//how many times did we try? Collection<String> authHeaderValues = request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER); if (authHeaderValues == null || authHeaderValues.size() == 0) { err = request.getErrorMessage(); myLastStatus.setError(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, err.getMessageTemplate(), err.getRelatedObjects())); if ("LOCK".equalsIgnoreCase(method)) { myLastStatus.getError().setChildErrorMessage(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Probably you are trying to lock file in repository that only allows anonymous access")); } SVNErrorManager.error(myLastStatus.getError(), SVNLogType.NETWORK); return myLastStatus; } //we should work around a situation when a server //does not support Basic authentication while we're //forcing it, credentials should not be immediately //thrown away boolean skip = false; isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false; if (isAuthForced) { if (httpAuth != null && myChallengeCredentials != null && !HTTPAuthentication.isSchemeSupportedByServer(myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) { skip = true; } } Collection<String> authTypes = null; if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) { DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager; authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation()); } try { myChallengeCredentials = HTTPAuthentication.parseAuthParameters(authHeaderValues, myChallengeCredentials, myCharset, authTypes, authManager, myRequestCount); } catch (SVNException svne) { err = svne.getErrorMessage(); break; } myChallengeCredentials.setChallengeParameter("method", method); myChallengeCredentials.setChallengeParameter("uri", HTTPParser.getCanonicalPath(path, null).toString()); if (skip) { close(); continue; } HTTPNTLMAuthentication ntlmAuth = null; HTTPNegotiateAuthentication negoAuth = null; if (myChallengeCredentials instanceof HTTPNTLMAuthentication) { ntlmAuthIsRequired = true; ntlmAuth = (HTTPNTLMAuthentication)myChallengeCredentials; if (ntlmAuth.isInType3State()) { continue; } } else if (myChallengeCredentials instanceof HTTPDigestAuthentication) { // continue (retry once) if previous request was acceppted? if (myLastValidAuth != null) { myLastValidAuth = null; continue; } } else if (myChallengeCredentials instanceof HTTPNegotiateAuthentication) { negoAuthIsRequired = true; negoAuth = (HTTPNegotiateAuthentication)myChallengeCredentials; if (negoAuth.isStarted()) { continue; } } myLastValidAuth = null; if (ntlmAuth != null && ntlmAuth.isNative() && authAttempts == 1) { /* * if this is the first time we get HTTP_UNAUTHORIZED, NTLM is the target auth scheme * and JNA is available, we should try a native auth mechanism first without calling * auth providers. */ continue; } if (negoAuth != null && !negoAuth.needsLogin()) { continue; } if (authManager == null) { err = request.getErrorMessage(); break; } realm = myChallengeCredentials.getChallengeParameter("realm"); realm = realm == null ? "" : " " + realm; realm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">" + realm; if (httpAuth == null) { httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } else if (authAttempts >= requestAttempts) { BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager); httpAuth = authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } if (httpAuth == null) { err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, "HTTP authorization cancelled"); break; } if (httpAuth != null) { myChallengeCredentials.setCredentials((SVNPasswordAuthentication) httpAuth); } continue; } else if (myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_PERM || myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) { String newLocation = request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER); if (newLocation == null) { err = request.getErrorMessage(); break; } int hostIndex = newLocation.indexOf("://"); if (hostIndex > 0) { hostIndex += 3; hostIndex = newLocation.indexOf("/", hostIndex); } if (hostIndex > 0 && hostIndex < newLocation.length()) { String newPath = newLocation.substring(hostIndex); if (newPath.endsWith("/") && !newPath.endsWith("//") && !path.endsWith("/") && newPath.substring(0, newPath.length() - 1).equals(path)) { path += "//"; continue; } } err = request.getErrorMessage(); close(); } else if (request.getErrorMessage() != null) { err = request.getErrorMessage(); } else { ntlmProxyAuthIsRequired = false; ntlmAuthIsRequired = false; negoAuthIsRequired = false; } if (err != null) { break; } if (myIsProxied) { if (proxyManager != null) { proxyManager.acknowledgeProxyContext(true, null); } } if (httpAuth != null && realm != null && authManager != null) { BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth, myRepository.getLocation(), authManager); } if (trustManager != null && authManager != null) { authManager.acknowledgeTrustManager(trustManager); } if (httpAuth != null) { myLastValidAuth = httpAuth; } if (authManager instanceof ISVNAuthenticationManagerExt) { ((ISVNAuthenticationManagerExt)authManager).acknowledgeConnectionSuccessful(myRepository.getLocation()); } myLastStatus.setHeader(request.getResponseHeader()); return myLastStatus; } // force close on error that was not processed before. // these are errors that has no relation to http status (processing error or cancellation). close(); if (err != null && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY && err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) { SVNErrorManager.error(err, SVNLogType.NETWORK); } // err2 is another default context... myRepository.getDebugLog().logFine(SVNLogType.NETWORK, new Exception(err.getMessage())); SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {method, path}, err.getType(), err.getCause()); SVNErrorManager.error(err, err2, SVNLogType.NETWORK); return null; }
diff --git a/src/main/java/nz/co/searchwellington/feeds/CommentFeedService.java b/src/main/java/nz/co/searchwellington/feeds/CommentFeedService.java index 2741c166..0a8843d6 100644 --- a/src/main/java/nz/co/searchwellington/feeds/CommentFeedService.java +++ b/src/main/java/nz/co/searchwellington/feeds/CommentFeedService.java @@ -1,79 +1,79 @@ package nz.co.searchwellington.feeds; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import nz.co.searchwellington.feeds.rss.RssHttpFetcher; import nz.co.searchwellington.model.Comment; import nz.co.searchwellington.model.CommentFeed; import nz.co.searchwellington.utils.UrlFilters; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFeed; public class CommentFeedService { public final static Logger log = Logger.getLogger(CommentFeedService.class); private RssHttpFetcher rssHttpFetcher; public CommentFeedService(RssHttpFetcher rssHttpFetcher) { this.rssHttpFetcher = rssHttpFetcher; } public List<Comment> loadComments(CommentFeed commentFeed) { List<Comment> comments = new ArrayList<Comment>(); // TODO this stopped working around 14 june 2011 //if (commentFeed.getNewsitem() == null) { // log.warn("Comment feed has no associated newsitems; no point in loading comments: " + commentFeed.getUrl()); // return comments; //} + //log.info("Loading comments from comment feed for newsitem: " + commentFeed.getNewsitem().getName()); - log.info("Loading comments from comment feed for newsitem: " + commentFeed.getNewsitem().getName()); SyndFeed syndfeed = rssHttpFetcher.httpFetch(commentFeed.getUrl()); if (syndfeed != null) { log.debug("Comment feed is of type: " + syndfeed.getFeedType()); List entires = syndfeed.getEntries(); for (Iterator iter = entires.iterator(); iter.hasNext();) { SyndEntry item = (SyndEntry) iter.next(); Comment comment = new Comment(extractCommentBody(item)); comments.add(comment); } } else { log.warn("Comment feed was null after loading attempt."); } log.info("Loaded " + comments.size() + " comments."); return comments; } private String extractCommentBody(SyndEntry item) { String commentBody = item.getTitle(); if (item.getDescription() != null) { String description = item.getDescription().getValue(); if (description != null && !description.equals("")) { commentBody = stripHtmlFromCommentItem(description); } } List<SyndContent> contents = item.getContents(); for (SyndContent content : contents) { if (content.getType().equals("html")) { commentBody = stripHtmlFromCommentItem(content.getValue()); } } return commentBody; } private String stripHtmlFromCommentItem(String contentValue) { return UrlFilters.stripHtml(StringEscapeUtils.unescapeHtml(contentValue)); } }
false
true
public List<Comment> loadComments(CommentFeed commentFeed) { List<Comment> comments = new ArrayList<Comment>(); // TODO this stopped working around 14 june 2011 //if (commentFeed.getNewsitem() == null) { // log.warn("Comment feed has no associated newsitems; no point in loading comments: " + commentFeed.getUrl()); // return comments; //} log.info("Loading comments from comment feed for newsitem: " + commentFeed.getNewsitem().getName()); SyndFeed syndfeed = rssHttpFetcher.httpFetch(commentFeed.getUrl()); if (syndfeed != null) { log.debug("Comment feed is of type: " + syndfeed.getFeedType()); List entires = syndfeed.getEntries(); for (Iterator iter = entires.iterator(); iter.hasNext();) { SyndEntry item = (SyndEntry) iter.next(); Comment comment = new Comment(extractCommentBody(item)); comments.add(comment); } } else { log.warn("Comment feed was null after loading attempt."); } log.info("Loaded " + comments.size() + " comments."); return comments; }
public List<Comment> loadComments(CommentFeed commentFeed) { List<Comment> comments = new ArrayList<Comment>(); // TODO this stopped working around 14 june 2011 //if (commentFeed.getNewsitem() == null) { // log.warn("Comment feed has no associated newsitems; no point in loading comments: " + commentFeed.getUrl()); // return comments; //} //log.info("Loading comments from comment feed for newsitem: " + commentFeed.getNewsitem().getName()); SyndFeed syndfeed = rssHttpFetcher.httpFetch(commentFeed.getUrl()); if (syndfeed != null) { log.debug("Comment feed is of type: " + syndfeed.getFeedType()); List entires = syndfeed.getEntries(); for (Iterator iter = entires.iterator(); iter.hasNext();) { SyndEntry item = (SyndEntry) iter.next(); Comment comment = new Comment(extractCommentBody(item)); comments.add(comment); } } else { log.warn("Comment feed was null after loading attempt."); } log.info("Loaded " + comments.size() + " comments."); return comments; }
diff --git a/src/web/org/openmrs/web/taglib/FieldGenTag.java b/src/web/org/openmrs/web/taglib/FieldGenTag.java index 7c18e2d3..48d69da2 100644 --- a/src/web/org/openmrs/web/taglib/FieldGenTag.java +++ b/src/web/org/openmrs/web/taglib/FieldGenTag.java @@ -1,468 +1,468 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.taglib; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.api.context.Context; import org.openmrs.util.OpenmrsUtil; import org.openmrs.web.taglib.fieldgen.FieldGenHandler; import org.openmrs.web.taglib.fieldgen.FieldGenHandlerFactory; import org.openmrs.web.taglib.fieldgen.LocationHandler; public class FieldGenTag extends TagSupport { public static final long serialVersionUID = 21132L; private final Log log = LogFactory.getLog(getClass()); public static final String DEFAULT_INPUT_TEXT_LENGTH = "20"; public static final String DEFAULT_INPUT_INT_LENGTH = "8"; public static final String DEFAULT_INPUT_FLOAT_LENGTH = "12"; public static final String DEFAULT_INPUT_CHAR_LENGTH = "2"; private String type; private String formFieldName; private Object val; private String url; private String parameters = ""; private Map<String, Object> parameterMap = null; private Boolean allowUserDefault = Boolean.FALSE; // should not be reset each time private FieldGenHandlerFactory factory = null; //private String fieldLength; //private String forceInputType; //private String isNullable; //private String hasLabelBefore; //private String trueLabel; //private String falseLabel; //private String unknownLabel; //private String emptySelectMessage; //private String additionalArgs; //private Map<String,String> args; public PageContext getPageContext() { return this.pageContext; } @SuppressWarnings("unchecked") public int doStartTag() throws JspException { if (type == null) type = ""; if (formFieldName == null) formFieldName = ""; if (formFieldName.length() > 0) { FieldGenHandler handler = getHandlerByClassName(type); if (handler != null) { handler.setFieldGenTag(this); handler.run(); } else { String output = "Cannot handle type [" + type + "]. Please add a module to handle this type."; if (type.equals("char") || type.indexOf("java.lang.Character") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal; if (startVal.length() > 1) startVal = startVal.substring(0, 1); String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength") : null; fieldLength = (fieldLength == null) ? DEFAULT_INPUT_CHAR_LENGTH : fieldLength; output = "<input type=\"text\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"" + startVal + "\" size=\"" + fieldLength + "\" maxlength=\"1\" />"; } else if (type.equals("int") || type.indexOf("java.lang.Integer") >= 0 || type.equals("long") || type.indexOf("java.lang.Long") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal; String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength") : null; fieldLength = (fieldLength == null) ? DEFAULT_INPUT_INT_LENGTH : fieldLength; output = "<input type=\"text\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"" + startVal + "\" size=\"" + fieldLength + "\" />"; } else if (type.equals("float") || type.indexOf("java.lang.Float") >= 0 || type.equals("double") || type.indexOf("java.lang.Double") >= 0 || type.indexOf("java.lang.Number") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal; String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength") : null; fieldLength = (fieldLength == null) ? DEFAULT_INPUT_FLOAT_LENGTH : fieldLength; output = "<input type=\"text\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"" + startVal + "\" size=\"" + fieldLength + "\" />"; } else if (type.equals("boolean") || type.indexOf("java.lang.Boolean") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal.toLowerCase(); if ("false".equals(startVal) || "0".equals(startVal)) startVal = "f"; if ("true".equals(startVal) || "1".equals(startVal)) startVal = "t"; if ("unknown".equals(startVal) || "?".equals(startVal)) startVal = "u"; String forceInputType = this.parameterMap != null ? (String) this.parameterMap.get("forceInputType") : null; String isNullable = this.parameterMap != null ? (String) this.parameterMap.get("isNullable") : null; String trueLabel = this.parameterMap != null ? (String) this.parameterMap.get("trueLabel") : null; String falseLabel = this.parameterMap != null ? (String) this.parameterMap.get("falseLabel") : null; String unknownLabel = this.parameterMap != null ? (String) this.parameterMap.get("unknownLabel") : null; if (forceInputType == null) forceInputType = ""; if ("checkbox".equals(forceInputType)) { output = "<input type=\"checkbox\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; } else { if (isNullable == null) isNullable = ""; if (trueLabel == null) trueLabel = "true"; if (falseLabel == null) falseLabel = "false"; if (unknownLabel == null) unknownLabel = "unknown"; if ("false".equalsIgnoreCase(isNullable) || "f".equalsIgnoreCase(isNullable) || "0".equals(isNullable)) { output = "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_f\" value=\"f\"" + ("f".equals(startVal) ? " checked" : "") + "/> "; output += falseLabel; output += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; output += "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName - + "_t\" =\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; + + "_t\" value=\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; output += trueLabel; } else { output = "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_f\" value=\"f\"" + ("f".equals(startVal) ? " checked" : "") + "/> "; output += falseLabel; output += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; output += "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_t\" value=\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; output += trueLabel; output += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; output += "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_u\" value=\"u\"" + ("u".equals(startVal) ? " checked" : "") + "/> "; output += unknownLabel; } } } else if (type.indexOf("$") >= 0) { // this could be an enum - if so, let's display it String className = type; Class cls = null; try { cls = Class.forName(className); } catch (Throwable t) { cls = null; log.error("Could not instantiate class for this enum of class name [" + className + "] in FieldGenTag"); } if (cls != null) { if (cls.isEnum()) { Object[] enumConstants = cls.getEnumConstants(); if (enumConstants != null) { if (enumConstants.length > 0) { String startVal = ""; if (val != null) startVal = val.toString(); log.debug("val is " + val); log.debug("val.toString is " + startVal); if (startVal == null) startVal = ""; output = "<select name=\"" + formFieldName + "\" id=\"" + formFieldName + "\">"; for (int i = 0; i < enumConstants.length; i++) { output += "<option value=\"" + enumConstants[i].toString() + "\"" + (startVal.equals(enumConstants[i].toString()) ? " selected" : "") + ">"; output += enumConstants[i].toString(); output += "</option>"; } output += "</select> "; } } } } } // end checking different built-in types try { pageContext.getOut().write(output); } catch (IOException e) { log.error(e); } } } if (url == null) url = "default.field"; // all fieldGens are contained in the /WEB-INF/view/fieldGen/ folder and end with .field if (!url.endsWith("field")) url += ".field"; url = "/fieldGen/" + url; // add attrs to request so that the controller (and field jsp) can see/use them pageContext.getRequest().setAttribute("org.openmrs.fieldGen.type", type); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.formFieldName", formFieldName); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.parameters", OpenmrsUtil.parseParameterList(parameters)); HashMap<String, Object> hmParamMap = (HashMap<String, Object>) pageContext.getRequest().getAttribute( "org.openmrs.fieldGen.parameterMap"); if (hmParamMap == null) hmParamMap = new HashMap<String, Object>(); if (this.parameterMap != null) hmParamMap.putAll(this.parameterMap); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.parameterMap", hmParamMap); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.object", val); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.request", pageContext.getRequest()); try { pageContext.include(this.url); } catch (ServletException e) { log.error("ServletException while trying to include a file in FieldGenTag", e); } catch (IOException e) { log.error("IOException while trying to include a file in FieldGenTag", e); } /* log.debug("FieldGenTag has reqest of " + pageContext.getRequest().toString()); pageContext.getRequest().setAttribute("javax.servlet.include.servlet_path.fieldGen", url); FieldGenController fgc = new FieldGenController(); try { fgc.handleRequest((HttpServletRequest)pageContext.getRequest(), (HttpServletResponse)pageContext.getResponse()); } catch (ServletException e) { log.error("ServletException while attempting to pass control to FieldGenController in FieldGenTag"); } catch (IOException e) { log.error("IOException while attempting to pass control to FieldGenController in FieldGenTag"); } */ resetValues(); return SKIP_BODY; } private void resetValues() { this.type = null; this.formFieldName = null; this.val = null; this.url = null; this.parameters = null; this.parameterMap = null; } public String getType() { return type; } public void setType(String type) { if (type.startsWith("class ")) { this.type = type.substring("class ".length()); } else { this.type = type; } } /** * @return Returns the formFieldName. */ public String getFormFieldName() { return formFieldName; } /** * @param formFieldName The formFieldName to set. */ public void setFormFieldName(String formFieldName) { this.formFieldName = formFieldName; } /** * This is the initial value or the stored value for this tag. * * @return Returns the startVal. */ public Object getVal() { return val; } /** * @param startVal The startVal to set. */ public void setVal(Object startVal) { this.val = startVal; } public void setUrl(String url) { this.url = url; } /** * @return Returns the parameterMap. */ public Map<String, Object> getParameterMap() { return parameterMap; } /** * @param parameterMap The parameterMap to set. */ public void setParameterMap(Map<String, Object> parameterMap) { this.parameterMap = parameterMap; } /** * @return Returns the parameters. */ public String getParameters() { return parameters; } /** * @param parameters The parameters to set. */ public void setParameters(String parameters) { this.parameters = parameters; String delimiter = "\\|"; // pipe is a special char in regex, so need to escape it... /* if ( parameters.indexOf(delimiter) < 0 ) { delimiter = ";"; } */ String[] nvPairs = parameters.split(delimiter); try { for (String nvPair : nvPairs) { String[] nameValue = nvPair.split("="); String name = ""; if (nameValue.length > 0) name = nameValue[0]; String val = ""; if (nameValue.length > 1) val = nameValue[1]; if (this.parameterMap == null) this.parameterMap = new HashMap<String, Object>(); this.parameterMap.put(name, val); } } catch (ArrayIndexOutOfBoundsException ae) { log.error("Out of bounds while trying to parse " + parameters + " with delimiter " + delimiter); } } /** * @return the allowUserDefault */ public Boolean getAllowUserDefault() { return allowUserDefault; } /** * If this is set to true, the user's stored default value for this value will be used if the * {@link #getVal()} is null. <br/> * <br/> * Usage of this is up to the individual handlers. See {@link LocationHandler} for an example. <br/> * <br/> * An example of when the dev doesn't want a default value is if location is set to null by a * previous user and the current user is only editing. Therefore, the * FieldGenTag.java#setAllowUserDefault() should only be set to true if creating an object for * the first time) * * @param allowUserDefault the allowUserDefault to set */ public void setAllowUserDefault(Boolean allowUserDefault) { this.allowUserDefault = allowUserDefault; } public FieldGenHandler getHandlerByClassName(String className) { String handlerClassName = null; try { //Resource beanDefinition = new ClassPathResource("/web/WEB-INF/openmrs-servlet.xml"); //XmlBeanFactory beanFactory = new XmlBeanFactory( beanDefinition ); //factory = (FieldGenHandlerFactory)beanFactory.getBean("fieldGenHandlerFactory"); //ApplicationContext context = new FileSystemXmlApplicationContext("file:/**/WEB-INF/openmrs-servlet.xml"); //if ( context == null ) context = WebApplicationContextUtils.getWebApplicationContext(this.pageContext.getServletContext()); //if ( context == null ) context = new FileSystemXmlApplicationContext("file:/**/WEB-INF/openmrs-servlet.xml"); /* if ( context != null ) { if ( factory == null ) factory = (FieldGenHandlerFactory)Context.getBean("fieldGenHandlerFactory"); } else log.error("Could not get handle on BeanFactory from FieldGen module"); */ factory = FieldGenHandlerFactory.getSingletonInstance(); } catch (Exception e) { factory = null; e.printStackTrace(); } if (factory != null) { handlerClassName = factory.getHandlerByClassName(className); if (handlerClassName != null) { try { Class<?> cls = Context.loadClass(handlerClassName); Constructor<?> ct = cls.getConstructor(); FieldGenHandler handler = (FieldGenHandler) ct.newInstance(); return handler; } catch (Exception e) { log.error("Unable to handle type [" + className + "] with handler [" + handlerClassName + "]. " + e); return null; } } else { return null; } } else { return null; } } }
true
true
public int doStartTag() throws JspException { if (type == null) type = ""; if (formFieldName == null) formFieldName = ""; if (formFieldName.length() > 0) { FieldGenHandler handler = getHandlerByClassName(type); if (handler != null) { handler.setFieldGenTag(this); handler.run(); } else { String output = "Cannot handle type [" + type + "]. Please add a module to handle this type."; if (type.equals("char") || type.indexOf("java.lang.Character") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal; if (startVal.length() > 1) startVal = startVal.substring(0, 1); String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength") : null; fieldLength = (fieldLength == null) ? DEFAULT_INPUT_CHAR_LENGTH : fieldLength; output = "<input type=\"text\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"" + startVal + "\" size=\"" + fieldLength + "\" maxlength=\"1\" />"; } else if (type.equals("int") || type.indexOf("java.lang.Integer") >= 0 || type.equals("long") || type.indexOf("java.lang.Long") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal; String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength") : null; fieldLength = (fieldLength == null) ? DEFAULT_INPUT_INT_LENGTH : fieldLength; output = "<input type=\"text\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"" + startVal + "\" size=\"" + fieldLength + "\" />"; } else if (type.equals("float") || type.indexOf("java.lang.Float") >= 0 || type.equals("double") || type.indexOf("java.lang.Double") >= 0 || type.indexOf("java.lang.Number") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal; String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength") : null; fieldLength = (fieldLength == null) ? DEFAULT_INPUT_FLOAT_LENGTH : fieldLength; output = "<input type=\"text\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"" + startVal + "\" size=\"" + fieldLength + "\" />"; } else if (type.equals("boolean") || type.indexOf("java.lang.Boolean") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal.toLowerCase(); if ("false".equals(startVal) || "0".equals(startVal)) startVal = "f"; if ("true".equals(startVal) || "1".equals(startVal)) startVal = "t"; if ("unknown".equals(startVal) || "?".equals(startVal)) startVal = "u"; String forceInputType = this.parameterMap != null ? (String) this.parameterMap.get("forceInputType") : null; String isNullable = this.parameterMap != null ? (String) this.parameterMap.get("isNullable") : null; String trueLabel = this.parameterMap != null ? (String) this.parameterMap.get("trueLabel") : null; String falseLabel = this.parameterMap != null ? (String) this.parameterMap.get("falseLabel") : null; String unknownLabel = this.parameterMap != null ? (String) this.parameterMap.get("unknownLabel") : null; if (forceInputType == null) forceInputType = ""; if ("checkbox".equals(forceInputType)) { output = "<input type=\"checkbox\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; } else { if (isNullable == null) isNullable = ""; if (trueLabel == null) trueLabel = "true"; if (falseLabel == null) falseLabel = "false"; if (unknownLabel == null) unknownLabel = "unknown"; if ("false".equalsIgnoreCase(isNullable) || "f".equalsIgnoreCase(isNullable) || "0".equals(isNullable)) { output = "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_f\" value=\"f\"" + ("f".equals(startVal) ? " checked" : "") + "/> "; output += falseLabel; output += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; output += "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_t\" =\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; output += trueLabel; } else { output = "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_f\" value=\"f\"" + ("f".equals(startVal) ? " checked" : "") + "/> "; output += falseLabel; output += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; output += "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_t\" value=\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; output += trueLabel; output += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; output += "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_u\" value=\"u\"" + ("u".equals(startVal) ? " checked" : "") + "/> "; output += unknownLabel; } } } else if (type.indexOf("$") >= 0) { // this could be an enum - if so, let's display it String className = type; Class cls = null; try { cls = Class.forName(className); } catch (Throwable t) { cls = null; log.error("Could not instantiate class for this enum of class name [" + className + "] in FieldGenTag"); } if (cls != null) { if (cls.isEnum()) { Object[] enumConstants = cls.getEnumConstants(); if (enumConstants != null) { if (enumConstants.length > 0) { String startVal = ""; if (val != null) startVal = val.toString(); log.debug("val is " + val); log.debug("val.toString is " + startVal); if (startVal == null) startVal = ""; output = "<select name=\"" + formFieldName + "\" id=\"" + formFieldName + "\">"; for (int i = 0; i < enumConstants.length; i++) { output += "<option value=\"" + enumConstants[i].toString() + "\"" + (startVal.equals(enumConstants[i].toString()) ? " selected" : "") + ">"; output += enumConstants[i].toString(); output += "</option>"; } output += "</select> "; } } } } } // end checking different built-in types try { pageContext.getOut().write(output); } catch (IOException e) { log.error(e); } } } if (url == null) url = "default.field"; // all fieldGens are contained in the /WEB-INF/view/fieldGen/ folder and end with .field if (!url.endsWith("field")) url += ".field"; url = "/fieldGen/" + url; // add attrs to request so that the controller (and field jsp) can see/use them pageContext.getRequest().setAttribute("org.openmrs.fieldGen.type", type); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.formFieldName", formFieldName); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.parameters", OpenmrsUtil.parseParameterList(parameters)); HashMap<String, Object> hmParamMap = (HashMap<String, Object>) pageContext.getRequest().getAttribute( "org.openmrs.fieldGen.parameterMap"); if (hmParamMap == null) hmParamMap = new HashMap<String, Object>(); if (this.parameterMap != null) hmParamMap.putAll(this.parameterMap); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.parameterMap", hmParamMap); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.object", val); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.request", pageContext.getRequest()); try { pageContext.include(this.url); } catch (ServletException e) { log.error("ServletException while trying to include a file in FieldGenTag", e); } catch (IOException e) { log.error("IOException while trying to include a file in FieldGenTag", e); } /* log.debug("FieldGenTag has reqest of " + pageContext.getRequest().toString()); pageContext.getRequest().setAttribute("javax.servlet.include.servlet_path.fieldGen", url); FieldGenController fgc = new FieldGenController(); try { fgc.handleRequest((HttpServletRequest)pageContext.getRequest(), (HttpServletResponse)pageContext.getResponse()); } catch (ServletException e) { log.error("ServletException while attempting to pass control to FieldGenController in FieldGenTag"); } catch (IOException e) { log.error("IOException while attempting to pass control to FieldGenController in FieldGenTag"); } */ resetValues(); return SKIP_BODY; }
public int doStartTag() throws JspException { if (type == null) type = ""; if (formFieldName == null) formFieldName = ""; if (formFieldName.length() > 0) { FieldGenHandler handler = getHandlerByClassName(type); if (handler != null) { handler.setFieldGenTag(this); handler.run(); } else { String output = "Cannot handle type [" + type + "]. Please add a module to handle this type."; if (type.equals("char") || type.indexOf("java.lang.Character") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal; if (startVal.length() > 1) startVal = startVal.substring(0, 1); String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength") : null; fieldLength = (fieldLength == null) ? DEFAULT_INPUT_CHAR_LENGTH : fieldLength; output = "<input type=\"text\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"" + startVal + "\" size=\"" + fieldLength + "\" maxlength=\"1\" />"; } else if (type.equals("int") || type.indexOf("java.lang.Integer") >= 0 || type.equals("long") || type.indexOf("java.lang.Long") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal; String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength") : null; fieldLength = (fieldLength == null) ? DEFAULT_INPUT_INT_LENGTH : fieldLength; output = "<input type=\"text\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"" + startVal + "\" size=\"" + fieldLength + "\" />"; } else if (type.equals("float") || type.indexOf("java.lang.Float") >= 0 || type.equals("double") || type.indexOf("java.lang.Double") >= 0 || type.indexOf("java.lang.Number") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal; String fieldLength = this.parameterMap != null ? (String) this.parameterMap.get("fieldLength") : null; fieldLength = (fieldLength == null) ? DEFAULT_INPUT_FLOAT_LENGTH : fieldLength; output = "<input type=\"text\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"" + startVal + "\" size=\"" + fieldLength + "\" />"; } else if (type.equals("boolean") || type.indexOf("java.lang.Boolean") >= 0) { String startVal = ""; if (val != null) { startVal = val.toString(); } startVal = (startVal == null) ? "" : startVal.toLowerCase(); if ("false".equals(startVal) || "0".equals(startVal)) startVal = "f"; if ("true".equals(startVal) || "1".equals(startVal)) startVal = "t"; if ("unknown".equals(startVal) || "?".equals(startVal)) startVal = "u"; String forceInputType = this.parameterMap != null ? (String) this.parameterMap.get("forceInputType") : null; String isNullable = this.parameterMap != null ? (String) this.parameterMap.get("isNullable") : null; String trueLabel = this.parameterMap != null ? (String) this.parameterMap.get("trueLabel") : null; String falseLabel = this.parameterMap != null ? (String) this.parameterMap.get("falseLabel") : null; String unknownLabel = this.parameterMap != null ? (String) this.parameterMap.get("unknownLabel") : null; if (forceInputType == null) forceInputType = ""; if ("checkbox".equals(forceInputType)) { output = "<input type=\"checkbox\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "\" value=\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; } else { if (isNullable == null) isNullable = ""; if (trueLabel == null) trueLabel = "true"; if (falseLabel == null) falseLabel = "false"; if (unknownLabel == null) unknownLabel = "unknown"; if ("false".equalsIgnoreCase(isNullable) || "f".equalsIgnoreCase(isNullable) || "0".equals(isNullable)) { output = "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_f\" value=\"f\"" + ("f".equals(startVal) ? " checked" : "") + "/> "; output += falseLabel; output += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; output += "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_t\" value=\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; output += trueLabel; } else { output = "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_f\" value=\"f\"" + ("f".equals(startVal) ? " checked" : "") + "/> "; output += falseLabel; output += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; output += "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_t\" value=\"t\"" + ("t".equals(startVal) ? " checked" : "") + "/> "; output += trueLabel; output += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; output += "<input type=\"radio\" name=\"" + formFieldName + "\" id=\"" + formFieldName + "_u\" value=\"u\"" + ("u".equals(startVal) ? " checked" : "") + "/> "; output += unknownLabel; } } } else if (type.indexOf("$") >= 0) { // this could be an enum - if so, let's display it String className = type; Class cls = null; try { cls = Class.forName(className); } catch (Throwable t) { cls = null; log.error("Could not instantiate class for this enum of class name [" + className + "] in FieldGenTag"); } if (cls != null) { if (cls.isEnum()) { Object[] enumConstants = cls.getEnumConstants(); if (enumConstants != null) { if (enumConstants.length > 0) { String startVal = ""; if (val != null) startVal = val.toString(); log.debug("val is " + val); log.debug("val.toString is " + startVal); if (startVal == null) startVal = ""; output = "<select name=\"" + formFieldName + "\" id=\"" + formFieldName + "\">"; for (int i = 0; i < enumConstants.length; i++) { output += "<option value=\"" + enumConstants[i].toString() + "\"" + (startVal.equals(enumConstants[i].toString()) ? " selected" : "") + ">"; output += enumConstants[i].toString(); output += "</option>"; } output += "</select> "; } } } } } // end checking different built-in types try { pageContext.getOut().write(output); } catch (IOException e) { log.error(e); } } } if (url == null) url = "default.field"; // all fieldGens are contained in the /WEB-INF/view/fieldGen/ folder and end with .field if (!url.endsWith("field")) url += ".field"; url = "/fieldGen/" + url; // add attrs to request so that the controller (and field jsp) can see/use them pageContext.getRequest().setAttribute("org.openmrs.fieldGen.type", type); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.formFieldName", formFieldName); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.parameters", OpenmrsUtil.parseParameterList(parameters)); HashMap<String, Object> hmParamMap = (HashMap<String, Object>) pageContext.getRequest().getAttribute( "org.openmrs.fieldGen.parameterMap"); if (hmParamMap == null) hmParamMap = new HashMap<String, Object>(); if (this.parameterMap != null) hmParamMap.putAll(this.parameterMap); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.parameterMap", hmParamMap); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.object", val); pageContext.getRequest().setAttribute("org.openmrs.fieldGen.request", pageContext.getRequest()); try { pageContext.include(this.url); } catch (ServletException e) { log.error("ServletException while trying to include a file in FieldGenTag", e); } catch (IOException e) { log.error("IOException while trying to include a file in FieldGenTag", e); } /* log.debug("FieldGenTag has reqest of " + pageContext.getRequest().toString()); pageContext.getRequest().setAttribute("javax.servlet.include.servlet_path.fieldGen", url); FieldGenController fgc = new FieldGenController(); try { fgc.handleRequest((HttpServletRequest)pageContext.getRequest(), (HttpServletResponse)pageContext.getResponse()); } catch (ServletException e) { log.error("ServletException while attempting to pass control to FieldGenController in FieldGenTag"); } catch (IOException e) { log.error("IOException while attempting to pass control to FieldGenController in FieldGenTag"); } */ resetValues(); return SKIP_BODY; }
diff --git a/src/fr/iutvalence/java/mp/thelasttyper/client/data/Game.java b/src/fr/iutvalence/java/mp/thelasttyper/client/data/Game.java index d5480fa..aa841e2 100644 --- a/src/fr/iutvalence/java/mp/thelasttyper/client/data/Game.java +++ b/src/fr/iutvalence/java/mp/thelasttyper/client/data/Game.java @@ -1,154 +1,154 @@ package fr.iutvalence.java.mp.thelasttyper.client.data; /** * Class representing a game. For have rules read : readme.txt . * * @author culasb */ public class Game { /** * the default time for the game to check everything in millisecond. */ public final static int DEFAULT_CHECKTIME = 500; /** * the default level of a game */ public final static int DEFAULT_LEVEL = 1; /** * the default max level of a game */ public final static int DEFAULT_MAX_LEVEL = 5; /** * the default amount of words per level */ public final static int DEFAULT_WORDS_AMOUNT = 20; /** * Game's player */ private Player player; /** * The level */ private Level level; /** * Game instantiation : The level is initialized at the Default level(1) and * create to recover a list of words with the default level. More over a * player is initialize * * @param wm * the wordmanager used for the game */ // TODO (FIXED) the WM should be taken as parameter public Game(WordsManager wm) { this.level = new Level(DEFAULT_LEVEL, wm, DEFAULT_WORDS_AMOUNT); this.player = new Player("test"); // TODO changer ça avec un fichier // config plutot } /** * The running of the game */ public void play() { boolean isGameOn = true; // TODO (FIXED) inner comments should not use javadoc syntax // exception to do : OutofLivesException : when the player have 0 lives. // Will allow to end the game // TODO (think about it) isGameOn looks much more like a local variable // than a field while (isGameOn) { - while (level.play()) + while (this.level.play()) { try { Thread.sleep(DEFAULT_CHECKTIME); } catch (InterruptedException e) { e.printStackTrace(); } } if (!this.levelUp()) isGameOn = false; } this.endGame(); } // TODO (FIXED) this method is useless /** * return the current level of the current game * * // TODO (fix) fix return tag comment * * // TODO (FIXED) fix return tag comment * * @return the Level of the current game */ private Level getLevel() { return this.level; } /** * change the level of the current game * * @param level * the new level (int) */ private void setlevel(Level level) { this.level = level; } // LEVEL UP /** * Used when a new level is started * * @return return true if a new level can be played. if there is no more * level return false */ // TODO (FIXED) this method should return a boolean indicating if the next // level is // ready to be played or not (there is no more level). this chould avoid to // call endGame from this // method private boolean levelUp() { WordsManager wm = null; // TODO create a function to initialize this wordmanager // TODO complete with the future functions and classes if (this.level.getLevelNumber() == DEFAULT_MAX_LEVEL) return false; else { this.setlevel(new Level(this.level.getLevelNumber() + 1, wm, DEFAULT_WORDS_AMOUNT)); } return true; } /** * Give all conditions for the ending of this game. */ private void endGame() { // TODO determiner les conditions d'arret du jeu. } }
true
true
public void play() { boolean isGameOn = true; // TODO (FIXED) inner comments should not use javadoc syntax // exception to do : OutofLivesException : when the player have 0 lives. // Will allow to end the game // TODO (think about it) isGameOn looks much more like a local variable // than a field while (isGameOn) { while (level.play()) { try { Thread.sleep(DEFAULT_CHECKTIME); } catch (InterruptedException e) { e.printStackTrace(); } } if (!this.levelUp()) isGameOn = false; } this.endGame(); }
public void play() { boolean isGameOn = true; // TODO (FIXED) inner comments should not use javadoc syntax // exception to do : OutofLivesException : when the player have 0 lives. // Will allow to end the game // TODO (think about it) isGameOn looks much more like a local variable // than a field while (isGameOn) { while (this.level.play()) { try { Thread.sleep(DEFAULT_CHECKTIME); } catch (InterruptedException e) { e.printStackTrace(); } } if (!this.levelUp()) isGameOn = false; } this.endGame(); }
diff --git a/src/webapp/src/java/org/wyona/yanel/servlet/menu/TransitionMenuContentImpl.java b/src/webapp/src/java/org/wyona/yanel/servlet/menu/TransitionMenuContentImpl.java index 1994a697d..e812fb42a 100644 --- a/src/webapp/src/java/org/wyona/yanel/servlet/menu/TransitionMenuContentImpl.java +++ b/src/webapp/src/java/org/wyona/yanel/servlet/menu/TransitionMenuContentImpl.java @@ -1,132 +1,132 @@ /** * */ package org.wyona.yanel.servlet.menu; import org.apache.log4j.Logger; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.workflow.Transition; import org.wyona.yanel.core.workflow.Workflow; import org.wyona.yanel.core.workflow.WorkflowException; import org.wyona.yanel.core.workflow.WorkflowHelper; /** * Creates an html element wrapping the transition of a resource from a given state. * The element contains an appropriately formatted URL (i.e. GET request) as an * anchor if the transition is valid. */ public class TransitionMenuContentImpl implements ITransitionMenuContent { private static Logger log = Logger.getLogger(TransitionMenuContentImpl.class); private static final String RESOURCE_REVN_ARG = "yanel.resource.revision="; private static final String RESOURCE_TRANSITION_ARG = "yanel.resource.workflow.transition="; private static final String RESOURCE_TRANSITION_OUTPUT = "yanel.resource.workflow.transition.output"; private static final String STYLE_INACTIVE = "inactive"; private Resource resource; private String state; private String revision; private String isoMenuLang; /** * ctor. * @param resource the resource which the transitions are "from" * @param status status of the revision (draft, review, etc.) * @param revision revn the revision of the resource which the transitions are "from" * @param langCode desired language of the resulting menu */ public TransitionMenuContentImpl(final Resource resource, final String status, final String revision, final String langCode) { this.resource = resource; this.state = status; this.revision = revision; this.isoMenuLang = langCode.toLowerCase(); } /** * Returns an html <li> element containing either an html <a> element to * activate the desired action, or plain text if it is not allowed to take * the action. * based on the revision state. * @param t * @return */ public String getTransitionElement(final Transition t) { if(log.isDebugEnabled()) log.debug("Transition: " + t.getID()); try { Workflow workflow = WorkflowHelper.getWorkflow(this.resource); Transition[] stateSpecificTransitions = workflow.getLeavingTransitions(this.state); String label = t.getID() + " (WARNING: No label!)"; try { label = t.getDescription(this.resource.getRequestedLanguage()); } catch(Exception e) { log.error(e, e); } for (int i = 0; i < stateSpecificTransitions.length; i++) { if (transitionsMatch(stateSpecificTransitions[i], t) && isComplied(t, workflow)) { try { String url = getTransitionURL(t.getID()); log.warn("DEBUG: Active transition: " + label); return "<li>" + new AnchorElement(label, url).toString() + "</li>"; } catch (Exception e) { log.warn("Could not get transition URL!"); // TODO: Is this always the reason for an exception?! log.warn(e, e); } } } - log.warn("DEBUG: Inactive transition: " + label); + log.debug("Inactive transition: " + label); return "<li class='" + STYLE_INACTIVE + "'>" + label + "</li>"; } catch (Exception e) { log.error(e, e); return "<li class='" + STYLE_INACTIVE + "'>Exception: " + e.getMessage() + "</li>"; } } /** * Two transitions match if they have the same ID. * @param t1 Transition 1 * @param t2 Transition 2 * @return true if they match, else false */ private boolean transitionsMatch(final Transition t1, final Transition t2) { return t1.getID().equals(t2.getID()); } private String getTransitionURL(final String transitionId) throws Exception { String url = getResourceURL(); String submit = RESOURCE_TRANSITION_ARG + transitionId; URLBuilder builder = new URLBuilder(); builder.createURL(url, submit); builder.addParameter(RESOURCE_REVN_ARG, this.revision); builder.addParameter(RESOURCE_TRANSITION_OUTPUT, "xhtml"); return builder.getURL(); } private String getResourceURL() throws Exception { String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(this.resource.getPath()); String url = backToRealm + this.resource.getPath(); url = url.replaceAll("//", "/"); return url; } /** * Also see org/wyona/yanel/core/workflow/WorkflowHelper#canDoTransition() or #getWorkflowIntrospection() */ private boolean isComplied(Transition transition, Workflow workflow) throws Exception { org.wyona.yanel.core.workflow.Condition[] conditions = transition.getConditions(); for (int k = 0; k < conditions.length; k++) { if (!conditions[k].isComplied((org.wyona.yanel.core.api.attributes.WorkflowableV1) resource, workflow, revision)) { return false; } } return true; } }
true
true
public String getTransitionElement(final Transition t) { if(log.isDebugEnabled()) log.debug("Transition: " + t.getID()); try { Workflow workflow = WorkflowHelper.getWorkflow(this.resource); Transition[] stateSpecificTransitions = workflow.getLeavingTransitions(this.state); String label = t.getID() + " (WARNING: No label!)"; try { label = t.getDescription(this.resource.getRequestedLanguage()); } catch(Exception e) { log.error(e, e); } for (int i = 0; i < stateSpecificTransitions.length; i++) { if (transitionsMatch(stateSpecificTransitions[i], t) && isComplied(t, workflow)) { try { String url = getTransitionURL(t.getID()); log.warn("DEBUG: Active transition: " + label); return "<li>" + new AnchorElement(label, url).toString() + "</li>"; } catch (Exception e) { log.warn("Could not get transition URL!"); // TODO: Is this always the reason for an exception?! log.warn(e, e); } } } log.warn("DEBUG: Inactive transition: " + label); return "<li class='" + STYLE_INACTIVE + "'>" + label + "</li>"; } catch (Exception e) { log.error(e, e); return "<li class='" + STYLE_INACTIVE + "'>Exception: " + e.getMessage() + "</li>"; } }
public String getTransitionElement(final Transition t) { if(log.isDebugEnabled()) log.debug("Transition: " + t.getID()); try { Workflow workflow = WorkflowHelper.getWorkflow(this.resource); Transition[] stateSpecificTransitions = workflow.getLeavingTransitions(this.state); String label = t.getID() + " (WARNING: No label!)"; try { label = t.getDescription(this.resource.getRequestedLanguage()); } catch(Exception e) { log.error(e, e); } for (int i = 0; i < stateSpecificTransitions.length; i++) { if (transitionsMatch(stateSpecificTransitions[i], t) && isComplied(t, workflow)) { try { String url = getTransitionURL(t.getID()); log.warn("DEBUG: Active transition: " + label); return "<li>" + new AnchorElement(label, url).toString() + "</li>"; } catch (Exception e) { log.warn("Could not get transition URL!"); // TODO: Is this always the reason for an exception?! log.warn(e, e); } } } log.debug("Inactive transition: " + label); return "<li class='" + STYLE_INACTIVE + "'>" + label + "</li>"; } catch (Exception e) { log.error(e, e); return "<li class='" + STYLE_INACTIVE + "'>Exception: " + e.getMessage() + "</li>"; } }
diff --git a/src/me/chaseoes/tf2/commands/SpectateCommand.java b/src/me/chaseoes/tf2/commands/SpectateCommand.java index f5ce5c8..be949d0 100644 --- a/src/me/chaseoes/tf2/commands/SpectateCommand.java +++ b/src/me/chaseoes/tf2/commands/SpectateCommand.java @@ -1,100 +1,101 @@ package me.chaseoes.tf2.commands; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import me.chaseoes.tf2.*; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class SpectateCommand { private HashMap<String, SpectatePlayer> spectating = new HashMap<String, SpectatePlayer>(); static SpectateCommand instance = new SpectateCommand(); public static SpectateCommand getCommand() { return instance; } public void execSpectateCommand(CommandSender cs, String[] strings, Command cmnd) { CommandHelper h = new CommandHelper(cs, cmnd); Player player = (Player) cs; if (strings.length == 1) { if (isSpectating(player)) { stopSpectating(player); } else { player.sendMessage(ChatColor.YELLOW + "[TF2] You are not spectating a map currently."); } } else if (strings.length == 2) { String map = strings[1]; if (!TF2.getInstance().mapExists(map)) { cs.sendMessage(ChatColor.YELLOW + "[TF2] " + ChatColor.ITALIC + map + ChatColor.RESET + ChatColor.YELLOW + " is not a valid map name."); return; } Game game = GameUtilities.getUtilities().getGamePlayer((Player) cs).getGame(); if (game != null) { cs.sendMessage(ChatColor.YELLOW + "[TF2] You already in a game."); + return; } if (DataConfiguration.getData().getDataFile().getStringList("disabled-maps").contains(map)) { player.sendMessage(ChatColor.YELLOW + "[TF2] That map is disabled."); return; } if (!spectating.containsKey(cs.getName())) { spectating.put(cs.getName(), new SpectatePlayer(player)); } SpectatePlayer sc = spectating.get(cs.getName()); Game ngame = GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(map)); if (ngame.getStatus() == GameStatus.INGAME || ngame.getStatus() == GameStatus.STARTING) { sc.toggleSpectating(GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(map))); } else { player.sendMessage(ChatColor.YELLOW + "[TF2] This map is not ingame."); } } else { h.wrongArgs(); } } public boolean isSpectating(Player player) { if (spectating.containsKey(player.getName())) { return spectating.get(player.getName()).isSpectating; } return false; } public void stopSpectating(Player player) { if (isSpectating(player)) { SpectatePlayer sp = spectating.get(player.getName()); sp.toggleSpectating(GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(sp.gameSpectating))); } } public void stopSpectating(Game game) { for (SpectatePlayer sps : spectating.values()) { if (sps.isSpectating && sps.gameSpectating.equalsIgnoreCase(game.getMapName())) { sps.toggleSpectating(game); } } } public void playerLogout(Player player) { spectating.remove(player.getName()); } public Set<SpectatePlayer> getSpectators(Game game) { Set<SpectatePlayer> sps = new HashSet<SpectatePlayer>(); for (SpectatePlayer sp : spectating.values()) { if (sp.isSpectating && sp.gameSpectating.equalsIgnoreCase(game.getMapName())) { sps.add(sp); } } return sps; } }
true
true
public void execSpectateCommand(CommandSender cs, String[] strings, Command cmnd) { CommandHelper h = new CommandHelper(cs, cmnd); Player player = (Player) cs; if (strings.length == 1) { if (isSpectating(player)) { stopSpectating(player); } else { player.sendMessage(ChatColor.YELLOW + "[TF2] You are not spectating a map currently."); } } else if (strings.length == 2) { String map = strings[1]; if (!TF2.getInstance().mapExists(map)) { cs.sendMessage(ChatColor.YELLOW + "[TF2] " + ChatColor.ITALIC + map + ChatColor.RESET + ChatColor.YELLOW + " is not a valid map name."); return; } Game game = GameUtilities.getUtilities().getGamePlayer((Player) cs).getGame(); if (game != null) { cs.sendMessage(ChatColor.YELLOW + "[TF2] You already in a game."); } if (DataConfiguration.getData().getDataFile().getStringList("disabled-maps").contains(map)) { player.sendMessage(ChatColor.YELLOW + "[TF2] That map is disabled."); return; } if (!spectating.containsKey(cs.getName())) { spectating.put(cs.getName(), new SpectatePlayer(player)); } SpectatePlayer sc = spectating.get(cs.getName()); Game ngame = GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(map)); if (ngame.getStatus() == GameStatus.INGAME || ngame.getStatus() == GameStatus.STARTING) { sc.toggleSpectating(GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(map))); } else { player.sendMessage(ChatColor.YELLOW + "[TF2] This map is not ingame."); } } else { h.wrongArgs(); } }
public void execSpectateCommand(CommandSender cs, String[] strings, Command cmnd) { CommandHelper h = new CommandHelper(cs, cmnd); Player player = (Player) cs; if (strings.length == 1) { if (isSpectating(player)) { stopSpectating(player); } else { player.sendMessage(ChatColor.YELLOW + "[TF2] You are not spectating a map currently."); } } else if (strings.length == 2) { String map = strings[1]; if (!TF2.getInstance().mapExists(map)) { cs.sendMessage(ChatColor.YELLOW + "[TF2] " + ChatColor.ITALIC + map + ChatColor.RESET + ChatColor.YELLOW + " is not a valid map name."); return; } Game game = GameUtilities.getUtilities().getGamePlayer((Player) cs).getGame(); if (game != null) { cs.sendMessage(ChatColor.YELLOW + "[TF2] You already in a game."); return; } if (DataConfiguration.getData().getDataFile().getStringList("disabled-maps").contains(map)) { player.sendMessage(ChatColor.YELLOW + "[TF2] That map is disabled."); return; } if (!spectating.containsKey(cs.getName())) { spectating.put(cs.getName(), new SpectatePlayer(player)); } SpectatePlayer sc = spectating.get(cs.getName()); Game ngame = GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(map)); if (ngame.getStatus() == GameStatus.INGAME || ngame.getStatus() == GameStatus.STARTING) { sc.toggleSpectating(GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(map))); } else { player.sendMessage(ChatColor.YELLOW + "[TF2] This map is not ingame."); } } else { h.wrongArgs(); } }
diff --git a/src/org/apache/xalan/lib/sql/ColumnData.java b/src/org/apache/xalan/lib/sql/ColumnData.java index 3ddc926e..5d4fd1c5 100644 --- a/src/org/apache/xalan/lib/sql/ColumnData.java +++ b/src/org/apache/xalan/lib/sql/ColumnData.java @@ -1,350 +1,351 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xalan.lib.sql; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.Document; import org.w3c.dom.DOMException; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import org.apache.xalan.res.XSLTErrorResources; /** * Represents the col element text node, i.e., the column value. */ public class ColumnData extends StreamableNode implements Text { /** The column for which this is the data */ Column m_parent; /** Flag for debug mode */ private static final boolean DEBUG = false; /** * Constructor ColumnData * * * @param statement Owning document * @param parent Owning column */ public ColumnData(XStatement statement, Column parent) { super(statement); m_parent = parent; } /** * Return node type, Node.TEXT_NODE. * * @return Node.TEXT_NODE. */ public short getNodeType() { return Node.TEXT_NODE; } /** * splitText - not supported * * * @param offset Offset where to split text * * @return null * * @throws DOMException */ public Text splitText(int offset) throws DOMException { error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); return null; } /** * Return the value for this col element text node. I.e., return a String representation * of the data for this column in the current row. * * @return the data for this column * * @throws DOMException */ public String getData() throws DOMException { try { ResultSet rs = this.getXStatement().getResultSet(); int columnIndex = m_parent.m_columnIndex; if (DEBUG) System.out.println("In ColumnData.getData, columnIndex: " + columnIndex); if (columnIndex < m_parent.m_parent.m_childCount) { - return rs.getString(columnIndex + 1); + String s = rs.getString(columnIndex + 1); + return (null != s) ? s : ""; } else - return null; + return ""; } catch (SQLException sqle) { - return null; + return ""; } } /** * Return the value for this col element text node. I.e., return a String representation * of the data for this column in the current row. * Calls @link #getNodeValue() getNodeValue()}. * * @return the value for this column * * @throws DOMException */ public String getNodeValue() throws DOMException { return getData(); } /** * The number of 16-bit units that are available through * <code>data</code> and the <code>substringData</code> method below. * This may have the value zero, i.e., <code>CharacterData</code> nodes * may be empty. * * @return Number of characters in data */ public int getLength() { String s = getData(); return (null != s) ? s.length() : 0; } /** * substringData - Not supported. * * @param offset Starting offset of substring * @param count Number of characters isn substring * * @return null * * @throws DOMException */ public String substringData(int offset, int count) throws DOMException { error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); return null; } /** * Not supported. * * @param arg * * @throws DOMException */ public void appendData(String arg) throws DOMException { error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); } /** * Not supported. * * @param offset * @param arg * * @throws DOMException */ public void insertData(int offset, String arg) throws DOMException { error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); } /** * Not supported. * * @param offset * @param count * * @throws DOMException */ public void deleteData(int offset, int count) throws DOMException { error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); } /** * Not supported. * * @param offset * @param count * @param arg * * @throws DOMException */ public void replaceData(int offset, int count, String arg) throws DOMException { error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); } /** * Not supported. * * @param data * * @throws DOMException */ public void setData(String data) throws DOMException { // TODO: It would be cool to make this callable, to set // a value in the database. error(XSLTErrorResources.ER_FUNCTION_NOT_SUPPORTED); } /** * The owner of a col text node is the #Document (represented by XStatement). * * @return The owning document */ public Document getOwnerDocument() { return this.getXStatement(); } /** * Return node name, "#Text". * * @return "#Text". */ public String getNodeName() { return "#Text"; } /** * Return First child. This always returns null. * * @return null */ public Node getFirstChild() { if (DEBUG) System.out.println("In ColumnData.getNextSibling"); return null; } /** * Return next sibling. This always returns null. * * @return null */ public Node getNextSibling() { if (DEBUG) System.out.println("In ColumnData.getNextSibling"); return null; } /** * The parent node of the col text node is the col node. * * @return The parent node i.e the column node */ public Node getParentNode() { if (DEBUG) System.out.println("In ColumnData.getParentNode"); return m_parent; } /** * Tell if there are any children of the col node, * which is always false. * * @return false */ public boolean hasChildNodes() { if (DEBUG) System.out.println("In ColumnData.hasChildNodes"); return false; } }
false
true
public String getData() throws DOMException { try { ResultSet rs = this.getXStatement().getResultSet(); int columnIndex = m_parent.m_columnIndex; if (DEBUG) System.out.println("In ColumnData.getData, columnIndex: " + columnIndex); if (columnIndex < m_parent.m_parent.m_childCount) { return rs.getString(columnIndex + 1); } else return null; } catch (SQLException sqle) { return null; } }
public String getData() throws DOMException { try { ResultSet rs = this.getXStatement().getResultSet(); int columnIndex = m_parent.m_columnIndex; if (DEBUG) System.out.println("In ColumnData.getData, columnIndex: " + columnIndex); if (columnIndex < m_parent.m_parent.m_childCount) { String s = rs.getString(columnIndex + 1); return (null != s) ? s : ""; } else return ""; } catch (SQLException sqle) { return ""; } }
diff --git a/src/autosaveworld/threads/save/AutoSaveThread.java b/src/autosaveworld/threads/save/AutoSaveThread.java index fb66361..8599ba1 100644 --- a/src/autosaveworld/threads/save/AutoSaveThread.java +++ b/src/autosaveworld/threads/save/AutoSaveThread.java @@ -1,256 +1,256 @@ /** * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package autosaveworld.threads.save; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitScheduler; import autosaveworld.config.AutoSaveConfig; import autosaveworld.config.AutoSaveConfigMSG; import autosaveworld.core.AutoSaveWorld; public class AutoSaveThread extends Thread { private AutoSaveWorld plugin = null; private AutoSaveConfig config; private AutoSaveConfigMSG configmsg; public AutoSaveThread(AutoSaveWorld plugin, AutoSaveConfig config, AutoSaveConfigMSG configmsg) { this.plugin = plugin; this.config = config; this.configmsg = configmsg; } public void stopThread() { this.run = false; } public void startsave() { if (plugin.saveInProgress) { plugin.warn("Multiple concurrent saves attempted! Save interval is likely too short!"); return; } command = true; } // The code to run...weee private volatile boolean run = true; private boolean command = false; @Override public void run() { plugin.debug("AutoSaveThread Started"); Thread.currentThread().setName("AutoSaveWorld AutoSaveThread"); while (run) { // Prevent AutoSave from never sleeping // If interval is 0, sleep for 5 seconds and skip saving if(config.saveInterval == 0) { try {Thread.sleep(5000);} catch(InterruptedException e) {} continue; } //sleep for (int i = 0; i < config.saveInterval; i++) { if (!run || command) {break;} try {Thread.sleep(1000);} catch (InterruptedException e) {} } //save if (run && (config.saveEnabled||command)) { performSave(false); } } plugin.debug("Graceful quit of AutoSaveThread"); } public void performSave(boolean force) { if (config.saveIgnoreIfNoPlayers && plugin.getServer().getOnlinePlayers().length == 0 && !command && !force) { // No players online, don't bother saving. plugin.debug("Skipping save, no players online."); return; } command = false; if (plugin.backupInProgress) { plugin.warn("AutoBackup is in process. AutoSave cancelled"); return; } // Lock plugin.saveInProgress = true; plugin.broadcast(configmsg.messageSaveBroadcastPre, config.saveBroadcast); save(); plugin.broadcast(configmsg.messageSaveBroadcastPost, config.saveBroadcast); plugin.LastSave =new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(System.currentTimeMillis()); // Release plugin.saveInProgress = false; } private void save() { // Save the players plugin.debug("Saving players"); BukkitScheduler scheduler = plugin.getServer().getScheduler(); int taskid; if (run) { taskid = scheduler.scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { for (Player player : plugin.getServer().getOnlinePlayers()) { plugin.debug(String.format("Saving player: %s", player.getName())); player.saveData(); } } }); while (scheduler.isCurrentlyRunning(taskid) || scheduler.isQueued(taskid)) { try {Thread.sleep(100);} catch (InterruptedException e) {} } } plugin.debug("Saved Players"); // Save the worlds plugin.debug("Saving worlds"); for (final World world : plugin.getServer().getWorlds()) { if (run) { taskid = scheduler.scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { plugin.debug(String.format("Saving world: %s", world.getName())); saveWorld(world); } }); while (scheduler.isCurrentlyRunning(taskid) || scheduler.isQueued(taskid)) { try {Thread.sleep(100);} catch (InterruptedException e) {} } } } plugin.debug("Saved Worlds"); } private void saveWorld(World world) { //structures are saved only for main world so we use this workaround only for main world if (config.donotsavestructures && Bukkit.getWorlds().get(0).getName().equalsIgnoreCase(world.getName())) { saveWorldDoNoSaveStructureInfo(world); } else { saveWorldNormal(world); } } private void saveWorldNormal(World world) { world.save(); } private void saveWorldDoNoSaveStructureInfo(World world) { - //omg... + //save saveenabled state + boolean saveenabled = world.isAutoSave(); + //set saveenabled state + world.setAutoSave(true); + //now lets save everything besides structures try { - //save saveenabled state - boolean saveenabled = world.isAutoSave(); - //set saveenabled state - world.setAutoSave(true); //get worldserver and dataManager Field worldField = world.getClass().getDeclaredField("world"); worldField.setAccessible(true); Object worldserver = worldField.get(world); Field dataManagerField = worldserver.getClass().getSuperclass().getDeclaredField("dataManager"); dataManagerField.setAccessible(true); Object dataManager = dataManagerField.get(worldserver); //invoke check session Method checkSessionMethod = dataManager.getClass().getSuperclass().getDeclaredMethod("checkSession"); checkSessionMethod.setAccessible(true); checkSessionMethod.invoke(dataManager); //invoke saveWorldData Field worldDataField = worldserver.getClass().getSuperclass().getDeclaredField("worldData"); worldDataField.setAccessible(true); Object worldData = worldDataField.get(worldserver); Field serverField = worldserver.getClass().getDeclaredField("server"); serverField.setAccessible(true); Object server = serverField.get(worldserver); Method getPlayerListMethod = server.getClass().getDeclaredMethod("getPlayerList"); getPlayerListMethod.setAccessible(true); Object playerList = getPlayerListMethod.invoke(server); Method qMethod = playerList.getClass().getSuperclass().getDeclaredMethod("q"); qMethod.setAccessible(true); Object NBTTagCompound = qMethod.invoke(playerList); for (Method method : dataManager.getClass().getSuperclass().getDeclaredMethods()) { if (method.getName().equals("saveWorldData") && method.getParameterTypes().length == 2) { method.setAccessible(true); method.invoke(dataManager, worldData, NBTTagCompound); } } //invoke saveChunks Field chunkProviderField = worldserver.getClass().getSuperclass().getDeclaredField("chunkProvider"); chunkProviderField.setAccessible(true); Object chunkProvider = chunkProviderField.get(worldserver); for (Method method : chunkProvider.getClass().getDeclaredMethods()) { if (method.getName().equals("saveChunks") && method.getParameterTypes().length == 2) { method.setAccessible(true); method.invoke(chunkProvider, true, null); break; } } - //reset saveenabled state - world.setAutoSave(saveenabled); } catch (Exception e) { e.printStackTrace(); - //failed to workaround + //failed to save using reflections, save world normal plugin.debug("failed to workaround stucture saving, saving world using normal methods"); saveWorldNormal(world); } + //reset saveenabled state + world.setAutoSave(saveenabled); } }
false
true
private void saveWorldDoNoSaveStructureInfo(World world) { //omg... try { //save saveenabled state boolean saveenabled = world.isAutoSave(); //set saveenabled state world.setAutoSave(true); //get worldserver and dataManager Field worldField = world.getClass().getDeclaredField("world"); worldField.setAccessible(true); Object worldserver = worldField.get(world); Field dataManagerField = worldserver.getClass().getSuperclass().getDeclaredField("dataManager"); dataManagerField.setAccessible(true); Object dataManager = dataManagerField.get(worldserver); //invoke check session Method checkSessionMethod = dataManager.getClass().getSuperclass().getDeclaredMethod("checkSession"); checkSessionMethod.setAccessible(true); checkSessionMethod.invoke(dataManager); //invoke saveWorldData Field worldDataField = worldserver.getClass().getSuperclass().getDeclaredField("worldData"); worldDataField.setAccessible(true); Object worldData = worldDataField.get(worldserver); Field serverField = worldserver.getClass().getDeclaredField("server"); serverField.setAccessible(true); Object server = serverField.get(worldserver); Method getPlayerListMethod = server.getClass().getDeclaredMethod("getPlayerList"); getPlayerListMethod.setAccessible(true); Object playerList = getPlayerListMethod.invoke(server); Method qMethod = playerList.getClass().getSuperclass().getDeclaredMethod("q"); qMethod.setAccessible(true); Object NBTTagCompound = qMethod.invoke(playerList); for (Method method : dataManager.getClass().getSuperclass().getDeclaredMethods()) { if (method.getName().equals("saveWorldData") && method.getParameterTypes().length == 2) { method.setAccessible(true); method.invoke(dataManager, worldData, NBTTagCompound); } } //invoke saveChunks Field chunkProviderField = worldserver.getClass().getSuperclass().getDeclaredField("chunkProvider"); chunkProviderField.setAccessible(true); Object chunkProvider = chunkProviderField.get(worldserver); for (Method method : chunkProvider.getClass().getDeclaredMethods()) { if (method.getName().equals("saveChunks") && method.getParameterTypes().length == 2) { method.setAccessible(true); method.invoke(chunkProvider, true, null); break; } } //reset saveenabled state world.setAutoSave(saveenabled); } catch (Exception e) { e.printStackTrace(); //failed to workaround plugin.debug("failed to workaround stucture saving, saving world using normal methods"); saveWorldNormal(world); } }
private void saveWorldDoNoSaveStructureInfo(World world) { //save saveenabled state boolean saveenabled = world.isAutoSave(); //set saveenabled state world.setAutoSave(true); //now lets save everything besides structures try { //get worldserver and dataManager Field worldField = world.getClass().getDeclaredField("world"); worldField.setAccessible(true); Object worldserver = worldField.get(world); Field dataManagerField = worldserver.getClass().getSuperclass().getDeclaredField("dataManager"); dataManagerField.setAccessible(true); Object dataManager = dataManagerField.get(worldserver); //invoke check session Method checkSessionMethod = dataManager.getClass().getSuperclass().getDeclaredMethod("checkSession"); checkSessionMethod.setAccessible(true); checkSessionMethod.invoke(dataManager); //invoke saveWorldData Field worldDataField = worldserver.getClass().getSuperclass().getDeclaredField("worldData"); worldDataField.setAccessible(true); Object worldData = worldDataField.get(worldserver); Field serverField = worldserver.getClass().getDeclaredField("server"); serverField.setAccessible(true); Object server = serverField.get(worldserver); Method getPlayerListMethod = server.getClass().getDeclaredMethod("getPlayerList"); getPlayerListMethod.setAccessible(true); Object playerList = getPlayerListMethod.invoke(server); Method qMethod = playerList.getClass().getSuperclass().getDeclaredMethod("q"); qMethod.setAccessible(true); Object NBTTagCompound = qMethod.invoke(playerList); for (Method method : dataManager.getClass().getSuperclass().getDeclaredMethods()) { if (method.getName().equals("saveWorldData") && method.getParameterTypes().length == 2) { method.setAccessible(true); method.invoke(dataManager, worldData, NBTTagCompound); } } //invoke saveChunks Field chunkProviderField = worldserver.getClass().getSuperclass().getDeclaredField("chunkProvider"); chunkProviderField.setAccessible(true); Object chunkProvider = chunkProviderField.get(worldserver); for (Method method : chunkProvider.getClass().getDeclaredMethods()) { if (method.getName().equals("saveChunks") && method.getParameterTypes().length == 2) { method.setAccessible(true); method.invoke(chunkProvider, true, null); break; } } } catch (Exception e) { e.printStackTrace(); //failed to save using reflections, save world normal plugin.debug("failed to workaround stucture saving, saving world using normal methods"); saveWorldNormal(world); } //reset saveenabled state world.setAutoSave(saveenabled); }
diff --git a/java/src/game/ai/FitnessComparator.java b/java/src/game/ai/FitnessComparator.java index ee562aa..fb826df 100755 --- a/java/src/game/ai/FitnessComparator.java +++ b/java/src/game/ai/FitnessComparator.java @@ -1,18 +1,18 @@ package game.ai; import game.State; import java.util.Comparator; /** * Compares two states according to their scorer evaluation. * * @author Tillmann Rendel * @author Thomas Horstmeyer */ public class FitnessComparator implements Comparator<State> { public int compare(State a, State b) { - return Integer.compare(a.fitness, b.fitness); + return Integer.compare(b.fitness, a.fitness); } }
true
true
public int compare(State a, State b) { return Integer.compare(a.fitness, b.fitness); }
public int compare(State a, State b) { return Integer.compare(b.fitness, a.fitness); }
diff --git a/src/main/java/com/hacku/swearjar/server/ConvertServlet.java b/src/main/java/com/hacku/swearjar/server/ConvertServlet.java index 2ed39fd..4fd51f1 100644 --- a/src/main/java/com/hacku/swearjar/server/ConvertServlet.java +++ b/src/main/java/com/hacku/swearjar/server/ConvertServlet.java @@ -1,329 +1,330 @@ package com.hacku.swearjar.server; import com.google.gson.Gson; import com.hacku.swearjar.speechapi.SpeechResponse; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.impl.client.DefaultHttpClient; /** * Servlet implementation class ConvertServlet */ @WebServlet(description = "Converts incoming file to .flac format before sending to Google's ASR. Sends json response back to app.", urlPatterns = {"/convert"}) @MultipartConfig(maxFileSize = 1024 * 1024 * 32) //Accept files upto 32MB public class ConvertServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static void log(String filename, String output) { FileOutputStream eos = null; try { eos = new FileOutputStream("/tmp/" + filename); IOUtils.copy(IOUtils.toInputStream(output), eos); eos.flush(); eos.close(); } catch (FileNotFoundException ex) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ioe) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ioe); } finally { try { eos.close(); } catch (IOException ex) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex); } } } /** * Takes an audio file, transcodes it to flac, then performs speech * recognition. Gives a JSON response containing the recognised speech. * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String baseDir = "/tmp"; String baseFilename = "SwearJar_" + request.getSession().getCreationTime() //Timestamp + "_" + request.getSession().getId(); //Session ID String inputExt = ".3gp"; String outputExt = ".flac"; String inputFilename = baseDir + "/" + baseFilename + inputExt; String flacFilename = baseFilename + outputExt; //Read the wav file sent and store it in a .wav file Part part = request.getPart("Content"); InputStream inputStream = part.getInputStream(); FileOutputStream fos = new FileOutputStream(inputFilename); IOUtils.copy(inputStream, fos); fos.flush(); fos.close(); //encode the file as flac String[] outputFilenames = transcode(baseDir, baseFilename, inputExt, outputExt); String filenames = ""; for(int i=0; i<outputFilenames.length; i++) filenames = filenames.concat(outputFilenames[i] + "\n"); log("outputFilenames", filenames); //Do speech recogntion and return JSON SpeechResponse aggregateSpeech = getSpeechResponse(outputFilenames); response.getOutputStream().print(aggregateSpeech.toJson()); //IOUtils.copy(IOUtils.toInputStream(aggregateSpeech.toJson()), response.getOutputStream()); //Temporary files can be deleted now /*delete(inputFilename); for(String filename : outputFilenames) delete(filename);*/ } /** * Gets an aggregate SpeechResponse object based on the speech contained in * multiple flac files * * @param speechFiles * @return */ private static SpeechResponse getSpeechResponse(String[] speechFiles) { SpeechResponse aggregateSpeech = new SpeechResponse(); //Do speech recogntion and return JSON for (String filename : speechFiles) { //TODO create new threads here SpeechResponse speech = getSpeechResponse(filename); if (speech != null) { aggregateSpeech.concat(speech); } } return aggregateSpeech; } /** * Causes the calling thread to wait for a maximum of millis for the File at * filename to be created * * @param millis * @param filename * @deprecated */ private static File waitForFileCreation(String filename, int millis) { while (millis > 0) { try { File file = new File(filename); if (file.exists() && file.canRead()) { try { Thread.sleep(500); } catch (InterruptedException ex) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex); } return file; } Thread.sleep(1); millis--; } catch (InterruptedException ex) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex); } } return null; } /** * Deletes a file if it exists * * @param filename */ private static void delete(String filename) { try { new File(filename).delete(); } catch (NullPointerException ioe) { System.err.println("Error deleting: " + filename); } } /** * Transcodes input file to flac * * @param inputFile * @param outputFile * @return array of files created */ private static String[] transcode(String baseDir, String baseFilename, String inputExt, String outputExt) { Runtime rt = Runtime.getRuntime(); String output = ""; try { String str = "sox_splitter " + baseDir + " " + baseFilename + " " + inputExt + " " + outputExt; //"echo test &>> /tmp/output"; /*"ffmpeg -i " + //Location of vlc inputFile + " -ar 8000 -sample_fmt s16 "//Location of input + " " + outputFile;*/ /*"run \"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe\" -I --dummy-quiet " + //Location of vlc inputFile + //Location of input " --sout=\"#transcode{acodec=flac, channels=1 ab=16 samplerate=16000}" + ":std{access=file, mux=raw, dst=" + outputFile + //Location of output "}\" vlc://quit";*/ Process pr = rt.exec(str); int exitStatus = pr.waitFor(); output = IOUtils.toString(pr.getInputStream()); /*FileOutputStream fos = new FileOutputStream("/tmp/output"); IOUtils.copy(pr.getInputStream(), fos); fos.flush(); fos.close(); */ FileOutputStream eos = new FileOutputStream("/tmp/errors"); IOUtils.copy(pr.getErrorStream(), eos); eos.flush(); eos.close(); //output = IOUtils.toString(pr.getInputStream()); System.out.println(System.currentTimeMillis() + " VLC exit code: " + exitStatus); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { log("output", output); return output.split("\n"); } } /** * Takes the audio at the specified path and sends it off to Google via HTTP * POST. Packages the JSON response from Google into a SpeechResponse * object. * * @param speechFilename path to the audio file * @return SpeechResponse containing recognised speech, null if error occurs */ private static SpeechResponse getSpeechResponse(String speechFilename) { FileLock lock = null; String except = ""; try { log("file", speechFilename); except = except.concat("1"); File file = waitForFileCreation(speechFilename, 1000); // Read speech file //File file = new File(speechFilename); except = except.concat("2"); FileInputStream inputStream = new FileInputStream(file); //Wait for file to become available //FileChannel channel = inputStream.getChannel(); //lock = channel.lock(0, Long.MAX_VALUE, true);//channel.lock(); except = except.concat("3"); ByteArrayInputStream data = new ByteArrayInputStream( IOUtils.toByteArray(inputStream)); // Set up the POST request except = except.concat("4"); HttpPost postRequest = getPost(data); // Do the request to google except = except.concat("5"); HttpClient client = new DefaultHttpClient(); except = except.concat("6"); HttpResponse response = client.execute(postRequest); except = except.concat("7"); - log("response", packageResponse(response).toJson()); + SpeechResponse packagedResponse = packageResponse(response); + log("response", packagedResponse.toJson()); //return the JSON stream except = except.concat("8"); - return packageResponse(response); + return packagedResponse; } catch (FileNotFoundException ex) { ex.printStackTrace(); log("exceptionFNF", ex.getMessage()); } catch (IOException ioe) { ioe.printStackTrace(); log("exceptionIOE", ioe.getMessage()); } catch (Exception ex) { ex.printStackTrace(); log("exception", ex.toString()); } finally { log("except", except); /*try { lock.release(); } catch (IOException ex) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (NullPointerException npe) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, npe); }*/ } return null; } /** * Sets up the post request = * * @param data audio file * @return HttpPost object with parameters initialised to audio file */ private static HttpPost getPost(ByteArrayInputStream data) { HttpPost postRequest = new HttpPost( "https://www.google.com/speech-api/v1/recognize" + "?xjerr=1&pfilter=0&client=chromium&lang=en-US&maxresults=1"); // Specify Content and Content-Type parameters for POST request MultipartEntity entity = new MultipartEntity(); entity.addPart("Content", new InputStreamBody(data, "Content")); postRequest.setHeader("Content-Type", "audio/x-flac; rate=16000"); postRequest.setEntity(entity); return postRequest; } /** * Uses GSON library to put the returned JSON into a SpeechResponse object * * @param response containing JSON to be packaged * @return SpeechResponse containing recognised speech * @throws IOException */ private static SpeechResponse packageResponse(HttpResponse response) throws IOException { Gson gson = new Gson(); InputStreamReader isr = new InputStreamReader(response.getEntity().getContent()); SpeechResponse speechResponse = gson.fromJson(isr, SpeechResponse.class); return speechResponse; } }
false
true
private static SpeechResponse getSpeechResponse(String speechFilename) { FileLock lock = null; String except = ""; try { log("file", speechFilename); except = except.concat("1"); File file = waitForFileCreation(speechFilename, 1000); // Read speech file //File file = new File(speechFilename); except = except.concat("2"); FileInputStream inputStream = new FileInputStream(file); //Wait for file to become available //FileChannel channel = inputStream.getChannel(); //lock = channel.lock(0, Long.MAX_VALUE, true);//channel.lock(); except = except.concat("3"); ByteArrayInputStream data = new ByteArrayInputStream( IOUtils.toByteArray(inputStream)); // Set up the POST request except = except.concat("4"); HttpPost postRequest = getPost(data); // Do the request to google except = except.concat("5"); HttpClient client = new DefaultHttpClient(); except = except.concat("6"); HttpResponse response = client.execute(postRequest); except = except.concat("7"); log("response", packageResponse(response).toJson()); //return the JSON stream except = except.concat("8"); return packageResponse(response); } catch (FileNotFoundException ex) { ex.printStackTrace(); log("exceptionFNF", ex.getMessage()); } catch (IOException ioe) { ioe.printStackTrace(); log("exceptionIOE", ioe.getMessage()); } catch (Exception ex) { ex.printStackTrace(); log("exception", ex.toString()); } finally { log("except", except); /*try { lock.release(); } catch (IOException ex) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (NullPointerException npe) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, npe); }*/ }
private static SpeechResponse getSpeechResponse(String speechFilename) { FileLock lock = null; String except = ""; try { log("file", speechFilename); except = except.concat("1"); File file = waitForFileCreation(speechFilename, 1000); // Read speech file //File file = new File(speechFilename); except = except.concat("2"); FileInputStream inputStream = new FileInputStream(file); //Wait for file to become available //FileChannel channel = inputStream.getChannel(); //lock = channel.lock(0, Long.MAX_VALUE, true);//channel.lock(); except = except.concat("3"); ByteArrayInputStream data = new ByteArrayInputStream( IOUtils.toByteArray(inputStream)); // Set up the POST request except = except.concat("4"); HttpPost postRequest = getPost(data); // Do the request to google except = except.concat("5"); HttpClient client = new DefaultHttpClient(); except = except.concat("6"); HttpResponse response = client.execute(postRequest); except = except.concat("7"); SpeechResponse packagedResponse = packageResponse(response); log("response", packagedResponse.toJson()); //return the JSON stream except = except.concat("8"); return packagedResponse; } catch (FileNotFoundException ex) { ex.printStackTrace(); log("exceptionFNF", ex.getMessage()); } catch (IOException ioe) { ioe.printStackTrace(); log("exceptionIOE", ioe.getMessage()); } catch (Exception ex) { ex.printStackTrace(); log("exception", ex.toString()); } finally { log("except", except); /*try { lock.release(); } catch (IOException ex) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (NullPointerException npe) { Logger.getLogger(ConvertServlet.class.getName()).log(Level.SEVERE, null, npe); }*/ }
diff --git a/gdx/src/com/badlogic/gdx/math/Polygon.java b/gdx/src/com/badlogic/gdx/math/Polygon.java index dfd7db729..2051acdad 100644 --- a/gdx/src/com/badlogic/gdx/math/Polygon.java +++ b/gdx/src/com/badlogic/gdx/math/Polygon.java @@ -1,205 +1,206 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.math; public class Polygon { private final float[] vertices; private float x, y; private float originX, originY; private float rotation; private float scaleX = 1, scaleY = 1; private boolean dirty; private Rectangle bounds = new Rectangle(); public Polygon (float[] vertices) { if (vertices.length < 6) throw new IllegalArgumentException("polygons must contain at least 3 points."); this.vertices = vertices; } public float[] getVertices () { if (!dirty) return vertices; float[] vertices = this.vertices; final int numFloats = vertices.length; final float translateX = x + originX; final float translateY = y + originY; final float cos = MathUtils.cosDeg(rotation); final float sin = MathUtils.sinDeg(rotation); float x, y; for (int i = 0; i < numFloats; i += 2) { x = vertices[i]; y = vertices[i + 1]; // move vertices to local coordinates x -= translateX; y -= translateY; // scale if needed if (scaleX != 1 || scaleY != 1) { x *= scaleX; y *= scaleY; } // rotate if needed if (rotation != 0) { + float oldX = x; x = cos * x - sin * y; - y = sin * x + cos * y; + y = sin * oldX + cos * y; } // move vertices back to world coordinates x += translateX; y += translateY; vertices[i] = x; vertices[i + 1] = y; } dirty = false; return vertices; } public void setOrigin (float originX, float originY) { this.originX = originX; this.originY = originY; dirty = true; } public void setPosition (float x, float y) { this.x = x; this.y = y; dirty = true; } public void translate (float x, float y) { this.x += x; this.y += y; dirty = true; } public void setRotation (float degrees) { this.rotation = degrees; dirty = true; } public void rotate (float degrees) { rotation += degrees; dirty = true; } public void setScale (float scaleX, float scaleY) { this.scaleX = scaleX; this.scaleY = scaleY; dirty = true; } public void scale (float amount) { this.scaleX += amount; this.scaleY += amount; dirty = true; } public float area () { float area = 0; float[] vertices = getVertices(); final int numFloats = vertices.length; int x1, y1, x2, y2; for (int i = 0; i < numFloats; i += 2) { x1 = i; y1 = i + 1; x2 = (i + 2) % numFloats; y2 = (i + 3) % numFloats; area += vertices[x1] * vertices[y2]; area -= vertices[x2] * vertices[y1]; } area *= 0.5f; return area; } public Rectangle getBoundingRectangle () { float[] vertices = getVertices(); float minX = vertices[0]; float minY = vertices[1]; float maxX = vertices[0]; float maxY = vertices[1]; final int numFloats = vertices.length; for (int i = 2; i < numFloats; i += 2) { minX = minX > vertices[i] ? vertices[i] : minX; minY = minY > vertices[i + 1] ? vertices[i + 1] : minY; maxX = maxX < vertices[i] ? vertices[i] : maxX; maxY = maxY < vertices[i + 1] ? vertices[i + 1] : maxY; } bounds.x = minX; bounds.y = minY; bounds.width = maxX - minX; bounds.height = maxY - minY; return bounds; } public boolean contains (float x, float y) { final float[] vertices = getVertices(); final int numFloats = vertices.length; int intersects = 0; for (int i = 0; i < numFloats; i += 2) { float x1 = vertices[i]; float y1 = vertices[i + 1]; float x2 = vertices[(i + 2) % numFloats]; float y2 = vertices[(i + 3) % numFloats]; if (((y1 <= y && y < y2) || (y2 <= y && y < y1)) && x < ((x2 - x1) / (y2 - y1) * (y - y1) + x1)) intersects++; } return (intersects & 1) == 1; } public float getX () { return x; } public float getY () { return y; } public float getOriginX () { return originX; } public float getOriginY () { return originY; } public float getRotation () { return rotation; } public float getScaleX () { return scaleX; } public float getScaleY () { return scaleY; } }
false
true
public float[] getVertices () { if (!dirty) return vertices; float[] vertices = this.vertices; final int numFloats = vertices.length; final float translateX = x + originX; final float translateY = y + originY; final float cos = MathUtils.cosDeg(rotation); final float sin = MathUtils.sinDeg(rotation); float x, y; for (int i = 0; i < numFloats; i += 2) { x = vertices[i]; y = vertices[i + 1]; // move vertices to local coordinates x -= translateX; y -= translateY; // scale if needed if (scaleX != 1 || scaleY != 1) { x *= scaleX; y *= scaleY; } // rotate if needed if (rotation != 0) { x = cos * x - sin * y; y = sin * x + cos * y; } // move vertices back to world coordinates x += translateX; y += translateY; vertices[i] = x; vertices[i + 1] = y; } dirty = false; return vertices; }
public float[] getVertices () { if (!dirty) return vertices; float[] vertices = this.vertices; final int numFloats = vertices.length; final float translateX = x + originX; final float translateY = y + originY; final float cos = MathUtils.cosDeg(rotation); final float sin = MathUtils.sinDeg(rotation); float x, y; for (int i = 0; i < numFloats; i += 2) { x = vertices[i]; y = vertices[i + 1]; // move vertices to local coordinates x -= translateX; y -= translateY; // scale if needed if (scaleX != 1 || scaleY != 1) { x *= scaleX; y *= scaleY; } // rotate if needed if (rotation != 0) { float oldX = x; x = cos * x - sin * y; y = sin * oldX + cos * y; } // move vertices back to world coordinates x += translateX; y += translateY; vertices[i] = x; vertices[i + 1] = y; } dirty = false; return vertices; }
diff --git a/OpERP/src/main/java/devopsdistilled/operp/server/ServerApp.java b/OpERP/src/main/java/devopsdistilled/operp/server/ServerApp.java index f6c626f4..19a4db02 100644 --- a/OpERP/src/main/java/devopsdistilled/operp/server/ServerApp.java +++ b/OpERP/src/main/java/devopsdistilled/operp/server/ServerApp.java @@ -1,47 +1,48 @@ package devopsdistilled.operp.server; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.Properties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import devopsdistilled.operp.server.context.AppContext; public class ServerApp { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext( AppContext.class); Properties hibernateProperties = new Properties(); URL hibernatePropertiesFileUrl = ServerApp.class.getClassLoader() .getResource("server/hibernate.properties"); File hibernatePropertiesFile = new File( hibernatePropertiesFileUrl.getFile()); try { InputStream in = new FileInputStream(hibernatePropertiesFile); hibernateProperties.load(in); String hbm2dllKey = "hibernate.hbm2ddl.auto"; String hbm2ddlValue = hibernateProperties.getProperty(hbm2dllKey); if (hbm2ddlValue.equalsIgnoreCase("create")) hibernateProperties.setProperty(hbm2dllKey, "update"); in.close(); OutputStream out = new FileOutputStream(hibernatePropertiesFile); hibernateProperties.store(out, null); } catch (IOException e) { System.err.println("hibernate.properties file not found!"); + e.printStackTrace(); } System.out.println(context); } }
true
true
public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext( AppContext.class); Properties hibernateProperties = new Properties(); URL hibernatePropertiesFileUrl = ServerApp.class.getClassLoader() .getResource("server/hibernate.properties"); File hibernatePropertiesFile = new File( hibernatePropertiesFileUrl.getFile()); try { InputStream in = new FileInputStream(hibernatePropertiesFile); hibernateProperties.load(in); String hbm2dllKey = "hibernate.hbm2ddl.auto"; String hbm2ddlValue = hibernateProperties.getProperty(hbm2dllKey); if (hbm2ddlValue.equalsIgnoreCase("create")) hibernateProperties.setProperty(hbm2dllKey, "update"); in.close(); OutputStream out = new FileOutputStream(hibernatePropertiesFile); hibernateProperties.store(out, null); } catch (IOException e) { System.err.println("hibernate.properties file not found!"); } System.out.println(context); }
public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext( AppContext.class); Properties hibernateProperties = new Properties(); URL hibernatePropertiesFileUrl = ServerApp.class.getClassLoader() .getResource("server/hibernate.properties"); File hibernatePropertiesFile = new File( hibernatePropertiesFileUrl.getFile()); try { InputStream in = new FileInputStream(hibernatePropertiesFile); hibernateProperties.load(in); String hbm2dllKey = "hibernate.hbm2ddl.auto"; String hbm2ddlValue = hibernateProperties.getProperty(hbm2dllKey); if (hbm2ddlValue.equalsIgnoreCase("create")) hibernateProperties.setProperty(hbm2dllKey, "update"); in.close(); OutputStream out = new FileOutputStream(hibernatePropertiesFile); hibernateProperties.store(out, null); } catch (IOException e) { System.err.println("hibernate.properties file not found!"); e.printStackTrace(); } System.out.println(context); }
diff --git a/hbl/src/main/java/com/inadco/hbl/model/NumericMeasure.java b/hbl/src/main/java/com/inadco/hbl/model/NumericMeasure.java index d05506e..006d633 100644 --- a/hbl/src/main/java/com/inadco/hbl/model/NumericMeasure.java +++ b/hbl/src/main/java/com/inadco/hbl/model/NumericMeasure.java @@ -1,65 +1,65 @@ /* * * Copyright © 2010, 2011 Inadco, Inc. 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. * * */ package com.inadco.hbl.model; import com.inadco.hbl.api.Measure; /** * Simple double-measure support * * @author dmitriy * */ public class NumericMeasure implements Measure { protected String name; public NumericMeasure(String name) { super(); this.name = name; } @Override public String getName() { return name; } @Override public Object compiler2Fact(Object value) { if (value == null) return null; /* * translate all numeric types to Double. */ else if (value instanceof Double) return (Double) value; else if (value instanceof Long) return ((Long) value).doubleValue(); else if (value instanceof Integer) return ((Integer) value).doubleValue(); else if (value instanceof Short) return ((Short) value).doubleValue(); else if (value instanceof Byte) return ((Byte) value).doubleValue(); else - throw new RuntimeException(String.format("Unknown measure instance type: %s", value.getClass().getName())); + throw new RuntimeException(String.format("Unknown measure '%s' instance type: %s", name, value.getClass().getName())); } }
true
true
public Object compiler2Fact(Object value) { if (value == null) return null; /* * translate all numeric types to Double. */ else if (value instanceof Double) return (Double) value; else if (value instanceof Long) return ((Long) value).doubleValue(); else if (value instanceof Integer) return ((Integer) value).doubleValue(); else if (value instanceof Short) return ((Short) value).doubleValue(); else if (value instanceof Byte) return ((Byte) value).doubleValue(); else throw new RuntimeException(String.format("Unknown measure instance type: %s", value.getClass().getName())); }
public Object compiler2Fact(Object value) { if (value == null) return null; /* * translate all numeric types to Double. */ else if (value instanceof Double) return (Double) value; else if (value instanceof Long) return ((Long) value).doubleValue(); else if (value instanceof Integer) return ((Integer) value).doubleValue(); else if (value instanceof Short) return ((Short) value).doubleValue(); else if (value instanceof Byte) return ((Byte) value).doubleValue(); else throw new RuntimeException(String.format("Unknown measure '%s' instance type: %s", name, value.getClass().getName())); }
diff --git a/test/models/PermissionTest.java b/test/models/PermissionTest.java index 3b2bf2cf..4dc2f343 100644 --- a/test/models/PermissionTest.java +++ b/test/models/PermissionTest.java @@ -1,26 +1,26 @@ package models; import models.enumeration.PermissionOperation; import models.enumeration.PermissionResource; import org.junit.Test; import static org.fest.assertions.Assertions.assertThat; public class PermissionTest extends ModelTest<Permission> { @Test public void permissionCheck() throws Exception { // Given // When // Then - assertThat(Permission.permissionCheck(2l, 1l, PermissionResource.PROJECT.resource(), PermissionOperation.WRITE.operation())).isEqualTo(true); - assertThat(Permission.permissionCheck(2l, 2l, PermissionResource.PROJECT.resource(), PermissionOperation.WRITE.operation())).isEqualTo(false); + assertThat(Permission.permissionCheck(2l, 1l, PermissionResource.PROJECT, PermissionOperation.WRITE)).isEqualTo(true); + assertThat(Permission.permissionCheck(2l, 2l, PermissionResource.PROJECT, PermissionOperation.WRITE)).isEqualTo(false); } @Test public void findPermissionsByRole() throws Exception { // Given // When // Then assertThat(Permission.findPermissionsByRole(1l).size()).isEqualTo(11); } }
true
true
public void permissionCheck() throws Exception { // Given // When // Then assertThat(Permission.permissionCheck(2l, 1l, PermissionResource.PROJECT.resource(), PermissionOperation.WRITE.operation())).isEqualTo(true); assertThat(Permission.permissionCheck(2l, 2l, PermissionResource.PROJECT.resource(), PermissionOperation.WRITE.operation())).isEqualTo(false); }
public void permissionCheck() throws Exception { // Given // When // Then assertThat(Permission.permissionCheck(2l, 1l, PermissionResource.PROJECT, PermissionOperation.WRITE)).isEqualTo(true); assertThat(Permission.permissionCheck(2l, 2l, PermissionResource.PROJECT, PermissionOperation.WRITE)).isEqualTo(false); }
diff --git a/src/jLanSend/MainWindow.java b/src/jLanSend/MainWindow.java index 079b105..eec3b50 100644 --- a/src/jLanSend/MainWindow.java +++ b/src/jLanSend/MainWindow.java @@ -1,311 +1,311 @@ /** * */ package jLanSend; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.Observable; import java.util.Observer; import java.util.Vector; import javax.print.attribute.standard.NumberUp; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; /** * @author Moritz Bellach * */ public class MainWindow extends JFrame implements Observer { /** * */ private static final long serialVersionUID = 1L; private JTabbedPane tabGroup; private JPanel recvTab, sendTab, settingsTab, sendBtnGrp, sendOpList, receiveOpList; private JTextField nick; JSpinner port; private JCheckBox startTray, startAutodetection, startReceiver; private JButton fchooser, sendbtn, downloaddir, savesettings, restoresettings, defaultsettings; private JComboBox hostchooser; private ComboBoxModel cbm; private SpinnerModel sm; private File f; private Vector<String> rHosts; /** * @throws HeadlessException */ public MainWindow() throws HeadlessException { super("JLanSend"); JLanSend.getJLanSend().addObserver(this); setLayout(new BorderLayout()); tabGroup = new JTabbedPane(); recvTab = new JPanel(new BorderLayout()); sendTab = new JPanel(new BorderLayout()); settingsTab = new JPanel(new GridLayout(0, 2)); sendBtnGrp = new JPanel(); sendTab.add(sendBtnGrp, BorderLayout.NORTH); fchooser = new JButton("choose file"); fchooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { JFileChooser jfs = new JFileChooser(); if(JFileChooser.APPROVE_OPTION == jfs.showOpenDialog(rootPane)) { f = jfs.getSelectedFile(); fchooser.setText(f.getName()); } } }); sendbtn = new JButton("send"); sendbtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { //SendOp op = new SendOp(f, (String) hostchooser.getSelectedItem(), 9999); //TransferDisplay disp = new TransferDisplay(op.getFName(), op.rHostName, op); //sendOpList.add(disp); //sendOpList.revalidate(); - JLanSend.getJLanSend().addSendOp(new SendOp(f, (String) hostchooser.getSelectedItem(), 9999)); + JLanSend.getJLanSend().addSendOp(new SendOp(f, (String) hostchooser.getSelectedItem(), JLanSend.getJLanSend().getPort())); } }); cbm = new DefaultComboBoxModel(); rHosts = new Vector<String>(); hostchooser = new JComboBox(rHosts); hostchooser.setEditable(true); sendBtnGrp.add(new JLabel("Send")); sendBtnGrp.add(fchooser); sendBtnGrp.add(new JLabel("to")); sendBtnGrp.add(hostchooser); sendBtnGrp.add(sendbtn); sendOpList = new JPanel(new GridLayout(0, 1)); sendTab.add(new JScrollPane(sendOpList), BorderLayout.CENTER); receiveOpList = new JPanel(new GridLayout(0, 1)); recvTab.add(new JScrollPane(receiveOpList), BorderLayout.CENTER); //port = new JTextField(String.valueOf(JLanSend.getJLanSend().getPort())); sm = new SpinnerNumberModel(JLanSend.getJLanSend().getPort(), 1025, 65535, 1); port = new JSpinner(sm); downloaddir = new JButton(JLanSend.getJLanSend().getDownloaddir()); downloaddir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser jfc = new JFileChooser(JLanSend.getJLanSend().getDownloaddir()); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if(JFileChooser.APPROVE_OPTION == jfc.showOpenDialog(rootPane)){ downloaddir.setText(jfc.getSelectedFile().getAbsolutePath()); } } }); nick = new JTextField(JLanSend.getJLanSend().getNick()); startReceiver = new JCheckBox(); startReceiver.setSelected(JLanSend.getJLanSend().isStartReceiver()); startAutodetection = new JCheckBox(); startAutodetection.setSelected(JLanSend.getJLanSend().isStartAutodetection()); startTray = new JCheckBox(); startTray.setSelected(JLanSend.getJLanSend().isStartTray()); savesettings = new JButton("save"); savesettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JLanSend.getJLanSend().setNick(nick.getText()); JLanSend.getJLanSend().setDownloaddir(downloaddir.getText()); JLanSend.getJLanSend().setPort(((SpinnerNumberModel) sm).getNumber().intValue()); JLanSend.getJLanSend().setStartAutodetection(startAutodetection.isSelected()); JLanSend.getJLanSend().setStartReceiver(startReceiver.isSelected()); JLanSend.getJLanSend().setStartTray(startTray.isSelected()); JLanSend.getJLanSend().writeSettings(); } }); restoresettings = new JButton("restore"); restoresettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { nick.setText(JLanSend.getJLanSend().getNick()); downloaddir.setText(JLanSend.getJLanSend().getDownloaddir()); sm.setValue(new NumberUp(JLanSend.getJLanSend().getPort())); startAutodetection.setSelected(JLanSend.getJLanSend().isStartAutodetection()); startReceiver.setSelected(JLanSend.getJLanSend().isStartReceiver()); startTray.setSelected(JLanSend.getJLanSend().isStartTray()); } }); defaultsettings = new JButton("factory settings"); defaultsettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO add factory settings reset } }); settingsTab.add(new JLabel("Nick")); settingsTab.add(nick); settingsTab.add(new JLabel("Download Directory")); settingsTab.add(downloaddir); settingsTab.add(new JLabel("Port")); settingsTab.add(port); settingsTab.add(new JLabel("start receiving files on launch")); settingsTab.add(startReceiver); settingsTab.add(new JLabel("create tray icon on launch")); settingsTab.add(startTray); settingsTab.add(new JLabel("start detecting other JLanSends on launch")); settingsTab.add(startAutodetection); settingsTab.add(restoresettings); settingsTab.add(savesettings); settingsTab.add(defaultsettings); tabGroup.addTab("Send", sendTab); tabGroup.addTab("Receive", recvTab); tabGroup.addTab("Settings", settingsTab); add(tabGroup); pack(); if(JLanSend.getJLanSend().isStartTray()){ setDefaultCloseOperation(HIDE_ON_CLOSE); } else{ setDefaultCloseOperation(EXIT_ON_CLOSE); } setVisible(true); } /** * hides the main window */ public void pubhide(){ setVisible(false); } /** * unhides the main window */ public void pubunhide(){ setVisible(true); } /** * toggles the visibility of the main window */ public void toggleVisibility(){ if(isVisible()){ pubhide(); } else{ pubunhide(); } } public synchronized void changeRHost(boolean add, String rHost){ if(add){ if(!rHosts.contains(rHost)){ rHosts.add(rHost); } } else { String toRemove = ""; for(String savedHost : rHosts){ if(savedHost.endsWith(rHost)){ toRemove = savedHost; break; } } if(!toRemove.equals("")){ rHosts.remove(toRemove); } hostchooser.revalidate(); } } @Override public void update(Observable src, Object msg) { if(src instanceof JLanSend) { if(msg instanceof ReceiveOp) { ((ReceiveOp) msg).addObserver(this); receiveOpList.add(new TransferDisplay(((ReceiveOp) msg).getFName(), ((ReceiveOp) msg).getRNick() + "@" + ((ReceiveOp) msg).getRHostName(), (ReceiveOp) msg) ); } else if(msg instanceof SendOp) { ((SendOp) msg).addObserver(this); sendOpList.add(new TransferDisplay(((SendOp) msg).getFName(), ((SendOp) msg).getRNick() + "@" + ((SendOp) msg).getRHostName(), (SendOp) msg) ); sendOpList.revalidate(); } else { System.out.println("oO"); } } else { switch ((ObsMsg) msg) { /*case RECVPROGRESS: // TODO get progress break; case RECVDONE: // TODO show its done break; case SENDPROGRESS: // TODO get progress break; case SENDDONE: // TODO show its done break;*/ case REMOVEME: // TODO remove from gui ??? src.deleteObserver(this); /*case NEWRHOSTS: hostchooser.removeAllItems(); rHosts = JLanSend.getJLanSend().getRHosts(); for (String rHost : rHosts) { hostchooser.addItem(rHost); } */ default: break; } } } }
true
true
public MainWindow() throws HeadlessException { super("JLanSend"); JLanSend.getJLanSend().addObserver(this); setLayout(new BorderLayout()); tabGroup = new JTabbedPane(); recvTab = new JPanel(new BorderLayout()); sendTab = new JPanel(new BorderLayout()); settingsTab = new JPanel(new GridLayout(0, 2)); sendBtnGrp = new JPanel(); sendTab.add(sendBtnGrp, BorderLayout.NORTH); fchooser = new JButton("choose file"); fchooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { JFileChooser jfs = new JFileChooser(); if(JFileChooser.APPROVE_OPTION == jfs.showOpenDialog(rootPane)) { f = jfs.getSelectedFile(); fchooser.setText(f.getName()); } } }); sendbtn = new JButton("send"); sendbtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { //SendOp op = new SendOp(f, (String) hostchooser.getSelectedItem(), 9999); //TransferDisplay disp = new TransferDisplay(op.getFName(), op.rHostName, op); //sendOpList.add(disp); //sendOpList.revalidate(); JLanSend.getJLanSend().addSendOp(new SendOp(f, (String) hostchooser.getSelectedItem(), 9999)); } }); cbm = new DefaultComboBoxModel(); rHosts = new Vector<String>(); hostchooser = new JComboBox(rHosts); hostchooser.setEditable(true); sendBtnGrp.add(new JLabel("Send")); sendBtnGrp.add(fchooser); sendBtnGrp.add(new JLabel("to")); sendBtnGrp.add(hostchooser); sendBtnGrp.add(sendbtn); sendOpList = new JPanel(new GridLayout(0, 1)); sendTab.add(new JScrollPane(sendOpList), BorderLayout.CENTER); receiveOpList = new JPanel(new GridLayout(0, 1)); recvTab.add(new JScrollPane(receiveOpList), BorderLayout.CENTER); //port = new JTextField(String.valueOf(JLanSend.getJLanSend().getPort())); sm = new SpinnerNumberModel(JLanSend.getJLanSend().getPort(), 1025, 65535, 1); port = new JSpinner(sm); downloaddir = new JButton(JLanSend.getJLanSend().getDownloaddir()); downloaddir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser jfc = new JFileChooser(JLanSend.getJLanSend().getDownloaddir()); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if(JFileChooser.APPROVE_OPTION == jfc.showOpenDialog(rootPane)){ downloaddir.setText(jfc.getSelectedFile().getAbsolutePath()); } } }); nick = new JTextField(JLanSend.getJLanSend().getNick()); startReceiver = new JCheckBox(); startReceiver.setSelected(JLanSend.getJLanSend().isStartReceiver()); startAutodetection = new JCheckBox(); startAutodetection.setSelected(JLanSend.getJLanSend().isStartAutodetection()); startTray = new JCheckBox(); startTray.setSelected(JLanSend.getJLanSend().isStartTray()); savesettings = new JButton("save"); savesettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JLanSend.getJLanSend().setNick(nick.getText()); JLanSend.getJLanSend().setDownloaddir(downloaddir.getText()); JLanSend.getJLanSend().setPort(((SpinnerNumberModel) sm).getNumber().intValue()); JLanSend.getJLanSend().setStartAutodetection(startAutodetection.isSelected()); JLanSend.getJLanSend().setStartReceiver(startReceiver.isSelected()); JLanSend.getJLanSend().setStartTray(startTray.isSelected()); JLanSend.getJLanSend().writeSettings(); } }); restoresettings = new JButton("restore"); restoresettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { nick.setText(JLanSend.getJLanSend().getNick()); downloaddir.setText(JLanSend.getJLanSend().getDownloaddir()); sm.setValue(new NumberUp(JLanSend.getJLanSend().getPort())); startAutodetection.setSelected(JLanSend.getJLanSend().isStartAutodetection()); startReceiver.setSelected(JLanSend.getJLanSend().isStartReceiver()); startTray.setSelected(JLanSend.getJLanSend().isStartTray()); } }); defaultsettings = new JButton("factory settings"); defaultsettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO add factory settings reset } }); settingsTab.add(new JLabel("Nick")); settingsTab.add(nick); settingsTab.add(new JLabel("Download Directory")); settingsTab.add(downloaddir); settingsTab.add(new JLabel("Port")); settingsTab.add(port); settingsTab.add(new JLabel("start receiving files on launch")); settingsTab.add(startReceiver); settingsTab.add(new JLabel("create tray icon on launch")); settingsTab.add(startTray); settingsTab.add(new JLabel("start detecting other JLanSends on launch")); settingsTab.add(startAutodetection); settingsTab.add(restoresettings); settingsTab.add(savesettings); settingsTab.add(defaultsettings); tabGroup.addTab("Send", sendTab); tabGroup.addTab("Receive", recvTab); tabGroup.addTab("Settings", settingsTab); add(tabGroup); pack(); if(JLanSend.getJLanSend().isStartTray()){ setDefaultCloseOperation(HIDE_ON_CLOSE); } else{ setDefaultCloseOperation(EXIT_ON_CLOSE); } setVisible(true); }
public MainWindow() throws HeadlessException { super("JLanSend"); JLanSend.getJLanSend().addObserver(this); setLayout(new BorderLayout()); tabGroup = new JTabbedPane(); recvTab = new JPanel(new BorderLayout()); sendTab = new JPanel(new BorderLayout()); settingsTab = new JPanel(new GridLayout(0, 2)); sendBtnGrp = new JPanel(); sendTab.add(sendBtnGrp, BorderLayout.NORTH); fchooser = new JButton("choose file"); fchooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { JFileChooser jfs = new JFileChooser(); if(JFileChooser.APPROVE_OPTION == jfs.showOpenDialog(rootPane)) { f = jfs.getSelectedFile(); fchooser.setText(f.getName()); } } }); sendbtn = new JButton("send"); sendbtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { //SendOp op = new SendOp(f, (String) hostchooser.getSelectedItem(), 9999); //TransferDisplay disp = new TransferDisplay(op.getFName(), op.rHostName, op); //sendOpList.add(disp); //sendOpList.revalidate(); JLanSend.getJLanSend().addSendOp(new SendOp(f, (String) hostchooser.getSelectedItem(), JLanSend.getJLanSend().getPort())); } }); cbm = new DefaultComboBoxModel(); rHosts = new Vector<String>(); hostchooser = new JComboBox(rHosts); hostchooser.setEditable(true); sendBtnGrp.add(new JLabel("Send")); sendBtnGrp.add(fchooser); sendBtnGrp.add(new JLabel("to")); sendBtnGrp.add(hostchooser); sendBtnGrp.add(sendbtn); sendOpList = new JPanel(new GridLayout(0, 1)); sendTab.add(new JScrollPane(sendOpList), BorderLayout.CENTER); receiveOpList = new JPanel(new GridLayout(0, 1)); recvTab.add(new JScrollPane(receiveOpList), BorderLayout.CENTER); //port = new JTextField(String.valueOf(JLanSend.getJLanSend().getPort())); sm = new SpinnerNumberModel(JLanSend.getJLanSend().getPort(), 1025, 65535, 1); port = new JSpinner(sm); downloaddir = new JButton(JLanSend.getJLanSend().getDownloaddir()); downloaddir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser jfc = new JFileChooser(JLanSend.getJLanSend().getDownloaddir()); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if(JFileChooser.APPROVE_OPTION == jfc.showOpenDialog(rootPane)){ downloaddir.setText(jfc.getSelectedFile().getAbsolutePath()); } } }); nick = new JTextField(JLanSend.getJLanSend().getNick()); startReceiver = new JCheckBox(); startReceiver.setSelected(JLanSend.getJLanSend().isStartReceiver()); startAutodetection = new JCheckBox(); startAutodetection.setSelected(JLanSend.getJLanSend().isStartAutodetection()); startTray = new JCheckBox(); startTray.setSelected(JLanSend.getJLanSend().isStartTray()); savesettings = new JButton("save"); savesettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JLanSend.getJLanSend().setNick(nick.getText()); JLanSend.getJLanSend().setDownloaddir(downloaddir.getText()); JLanSend.getJLanSend().setPort(((SpinnerNumberModel) sm).getNumber().intValue()); JLanSend.getJLanSend().setStartAutodetection(startAutodetection.isSelected()); JLanSend.getJLanSend().setStartReceiver(startReceiver.isSelected()); JLanSend.getJLanSend().setStartTray(startTray.isSelected()); JLanSend.getJLanSend().writeSettings(); } }); restoresettings = new JButton("restore"); restoresettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { nick.setText(JLanSend.getJLanSend().getNick()); downloaddir.setText(JLanSend.getJLanSend().getDownloaddir()); sm.setValue(new NumberUp(JLanSend.getJLanSend().getPort())); startAutodetection.setSelected(JLanSend.getJLanSend().isStartAutodetection()); startReceiver.setSelected(JLanSend.getJLanSend().isStartReceiver()); startTray.setSelected(JLanSend.getJLanSend().isStartTray()); } }); defaultsettings = new JButton("factory settings"); defaultsettings.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO add factory settings reset } }); settingsTab.add(new JLabel("Nick")); settingsTab.add(nick); settingsTab.add(new JLabel("Download Directory")); settingsTab.add(downloaddir); settingsTab.add(new JLabel("Port")); settingsTab.add(port); settingsTab.add(new JLabel("start receiving files on launch")); settingsTab.add(startReceiver); settingsTab.add(new JLabel("create tray icon on launch")); settingsTab.add(startTray); settingsTab.add(new JLabel("start detecting other JLanSends on launch")); settingsTab.add(startAutodetection); settingsTab.add(restoresettings); settingsTab.add(savesettings); settingsTab.add(defaultsettings); tabGroup.addTab("Send", sendTab); tabGroup.addTab("Receive", recvTab); tabGroup.addTab("Settings", settingsTab); add(tabGroup); pack(); if(JLanSend.getJLanSend().isStartTray()){ setDefaultCloseOperation(HIDE_ON_CLOSE); } else{ setDefaultCloseOperation(EXIT_ON_CLOSE); } setVisible(true); }
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNAdminArea14.java b/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNAdminArea14.java index 5496ba540..0f2112809 100644 --- a/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNAdminArea14.java +++ b/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNAdminArea14.java @@ -1,1796 +1,1798 @@ /* * ==================================================================== * Copyright (c) 2004-2007 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.wc.admin; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.internal.io.fs.FSFile; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNFormatUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNTimeUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileListUtil; import org.tmatesoft.svn.core.internal.wc.SVNFileType; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.SVNProperties; import org.tmatesoft.svn.util.SVNDebugLog; /** * @version 1.1.1 * @author TMate Software Ltd. */ public class SVNAdminArea14 extends SVNAdminArea { public static final String[] ourCachableProperties = new String[] { SVNProperty.SPECIAL, SVNProperty.EXTERNALS, SVNProperty.NEEDS_LOCK }; public static final int WC_FORMAT = 8; private static final String ATTRIBUTE_COPIED = "copied"; private static final String ATTRIBUTE_DELETED = "deleted"; private static final String ATTRIBUTE_ABSENT = "absent"; private static final String ATTRIBUTE_INCOMPLETE = "incomplete"; private static final String THIS_DIR = ""; private File myLockFile; private File myEntriesFile; public SVNAdminArea14(File dir) { super(dir); myLockFile = new File(getAdminDirectory(), "lock"); myEntriesFile = new File(getAdminDirectory(), "entries"); } public static String[] getCachableProperties() { return ourCachableProperties; } public void saveWCProperties(boolean close) throws SVNException { Map wcPropsCache = getWCPropertiesStorage(false); if (wcPropsCache == null) { return; } boolean hasAnyProps = false; File dstFile = getAdminFile("all-wcprops"); File tmpFile = getAdminFile("tmp/all-wcprops"); for(Iterator entries = wcPropsCache.keySet().iterator(); entries.hasNext();) { String name = (String)entries.next(); SVNVersionedProperties props = (SVNVersionedProperties)wcPropsCache.get(name); if (!props.isEmpty()) { hasAnyProps = true; break; } } if (hasAnyProps) { OutputStream target = null; try { target = SVNFileUtil.openFileForWriting(tmpFile); SVNVersionedProperties props = (SVNVersionedProperties)wcPropsCache.get(getThisDirName()); if (props != null && !props.isEmpty()) { SVNProperties.setProperties(props.asMap(), target, SVNProperties.SVN_HASH_TERMINATOR); } else { SVNProperties.setProperties(Collections.EMPTY_MAP, target, SVNProperties.SVN_HASH_TERMINATOR); } for(Iterator entries = wcPropsCache.keySet().iterator(); entries.hasNext();) { String name = (String)entries.next(); if (getThisDirName().equals(name)) { continue; } props = (SVNVersionedProperties)wcPropsCache.get(name); if (!props.isEmpty()) { target.write(name.getBytes("UTF-8")); target.write('\n'); SVNProperties.setProperties(props.asMap(), target, SVNProperties.SVN_HASH_TERMINATOR); } } } catch (IOException ioe) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, ioe.getLocalizedMessage()); SVNErrorManager.error(err, ioe); } finally { SVNFileUtil.closeFile(target); } SVNFileUtil.rename(tmpFile, dstFile); SVNFileUtil.setReadonly(dstFile, true); } else { SVNFileUtil.deleteFile(dstFile); } if (close) { closeWCProperties(); } } public SVNVersionedProperties getBaseProperties(String name) throws SVNException { Map basePropsCache = getBasePropertiesStorage(true); SVNVersionedProperties props = (SVNVersionedProperties)basePropsCache.get(name); if (props != null) { return props; } Map baseProps = null; try { baseProps = readBaseProperties(name); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage().wrap("Failed to load properties from disk"); SVNErrorManager.error(err); } props = new SVNProperties13(baseProps); basePropsCache.put(name, props); return props; } public SVNVersionedProperties getRevertProperties(String name) throws SVNException { Map revertPropsCache = getRevertPropertiesStorage(true); SVNVersionedProperties props = (SVNVersionedProperties)revertPropsCache.get(name); if (props != null) { return props; } Map revertProps = null; try { revertProps = readRevertProperties(name); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage().wrap("Failed to load properties from disk"); SVNErrorManager.error(err); } props = new SVNProperties13(revertProps); revertPropsCache.put(name, props); return props; } public SVNVersionedProperties getProperties(String name) throws SVNException { Map propsCache = getPropertiesStorage(true); SVNVersionedProperties props = (SVNVersionedProperties)propsCache.get(name); if (props != null) { return props; } final String entryName = name; props = new SVNProperties14(null, this, name){ protected Map loadProperties() throws SVNException { Map props = getPropertiesMap(); if (props == null) { try { props = readProperties(entryName); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage().wrap("Failed to load properties from disk"); SVNErrorManager.error(err); } props = props != null ? props : new HashMap(); setPropertiesMap(props); } return props; } }; propsCache.put(name, props); return props; } public SVNVersionedProperties getWCProperties(String entryName) throws SVNException { SVNEntry entry = getEntry(entryName, false); if (entry == null) { return null; } Map wcPropsCache = getWCPropertiesStorage(true); SVNVersionedProperties props = (SVNVersionedProperties)wcPropsCache.get(entryName); if (props != null) { return props; } if (wcPropsCache.isEmpty()) { wcPropsCache = readAllWCProperties(); } props = (SVNVersionedProperties)wcPropsCache.get(entryName); if (props == null) { props = new SVNProperties13(new HashMap()); wcPropsCache.put(entryName, props); } return props; } private Map readAllWCProperties() throws SVNException { Map wcPropsCache = getWCPropertiesStorage(true); wcPropsCache.clear(); File propertiesFile = getAdminFile("all-wcprops"); if (!propertiesFile.exists()) { return wcPropsCache; } FSFile wcpropsFile = null; try { wcpropsFile = new FSFile(propertiesFile); Map wcProps = wcpropsFile.readProperties(false); SVNVersionedProperties entryWCProps = new SVNProperties13(wcProps); wcPropsCache.put(getThisDirName(), entryWCProps); String name = null; StringBuffer buffer = new StringBuffer(); while(true) { try { name = wcpropsFile.readLine(buffer); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.STREAM_UNEXPECTED_EOF && buffer.length() > 0) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Missing end of line in wcprops file for ''{0}''", getRoot()); SVNErrorManager.error(err, e); } break; } wcProps = wcpropsFile.readProperties(false); entryWCProps = new SVNProperties13(wcProps); wcPropsCache.put(name, entryWCProps); buffer.delete(0, buffer.length()); } } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage().wrap("Failed to load properties from disk"); SVNErrorManager.error(err); } finally { wcpropsFile.close(); } return wcPropsCache; } private Map readBaseProperties(String name) throws SVNException { File propertiesFile = getBasePropertiesFile(name, false); SVNProperties props = new SVNProperties(propertiesFile, null); return props.asMap(); } private Map readRevertProperties(String name) throws SVNException { File propertiesFile = getRevertPropertiesFile(name, false); SVNProperties props = new SVNProperties(propertiesFile, null); return props.asMap(); } private Map readProperties(String name) throws SVNException { if (hasPropModifications(name)) { File propertiesFile = getPropertiesFile(name, false); SVNProperties props = new SVNProperties(propertiesFile, null); return props.asMap(); } Map basePropsCache = getBasePropertiesStorage(true); if (basePropsCache != null ) { SVNVersionedProperties baseProps = (SVNVersionedProperties) basePropsCache.get(name); if (baseProps != null) { return baseProps.asMap(); } } if (hasProperties(name)) { return readBaseProperties(name); } return new HashMap(); } public void saveVersionedProperties(SVNLog log, boolean close) throws SVNException { Map command = new HashMap(); Set processedEntries = new HashSet(); Map propsCache = getPropertiesStorage(false); if (propsCache != null && !propsCache.isEmpty()) { for(Iterator entries = propsCache.keySet().iterator(); entries.hasNext();) { String name = (String)entries.next(); SVNVersionedProperties props = (SVNVersionedProperties)propsCache.get(name); if (props.isModified()) { SVNVersionedProperties baseProps = getBaseProperties(name); SVNVersionedProperties propsDiff = baseProps.compareTo(props); String[] cachableProps = SVNAdminArea14.getCachableProperties(); command.put(SVNProperty.CACHABLE_PROPS, asString(cachableProps, " ")); Map propsMap = props.loadProperties(); LinkedList presentProps = new LinkedList(); for (int i = 0; i < cachableProps.length; i++) { if (propsMap.containsKey(cachableProps[i])) { presentProps.addLast(cachableProps[i]); } } if (presentProps.size() > 0) { String presentPropsString = asString((String[])presentProps.toArray(new String[presentProps.size()]), " "); command.put(SVNProperty.PRESENT_PROPS, presentPropsString); } else { command.put(SVNProperty.PRESENT_PROPS, ""); } command.put(SVNProperty.HAS_PROPS, SVNProperty.toString(!props.isEmpty())); boolean hasPropModifications = !propsDiff.isEmpty(); command.put(SVNProperty.HAS_PROP_MODS, SVNProperty.toString(hasPropModifications)); command.put(SVNLog.NAME_ATTR, name); log.addCommand(SVNLog.MODIFY_ENTRY, command, false); processedEntries.add(name); command.clear(); String dstPath = getThisDirName().equals(name) ? "dir-props" : "props/" + name + ".svn-work"; dstPath = getAdminDirectory().getName() + "/" + dstPath; if (hasPropModifications) { String tmpPath = "tmp/"; tmpPath += getThisDirName().equals(name) ? "dir-props" : "props/" + name + ".svn-work"; File tmpFile = getAdminFile(tmpPath); String srcPath = getAdminDirectory().getName() + "/" + tmpPath; SVNProperties tmpProps = new SVNProperties(tmpFile, srcPath); tmpProps.setProperties(props.asMap()); command.put(SVNLog.NAME_ATTR, srcPath); command.put(SVNLog.DEST_ATTR, dstPath); log.addCommand(SVNLog.MOVE, command, false); command.clear(); command.put(SVNLog.NAME_ATTR, dstPath); log.addCommand(SVNLog.READONLY, command, false); } else { command.put(SVNLog.NAME_ATTR, dstPath); log.addCommand(SVNLog.DELETE, command, false); } command.clear(); props.setModified(false); } } } Map basePropsCache = getBasePropertiesStorage(false); if (basePropsCache != null && !basePropsCache.isEmpty()) { for(Iterator entries = basePropsCache.keySet().iterator(); entries.hasNext();) { String name = (String)entries.next(); SVNVersionedProperties baseProps = (SVNVersionedProperties)basePropsCache.get(name); if (baseProps.isModified()) { String dstPath = getThisDirName().equals(name) ? "dir-prop-base" : "prop-base/" + name + ".svn-base"; dstPath = getAdminDirectory().getName() + "/" + dstPath; boolean isEntryProcessed = processedEntries.contains(name); if (!isEntryProcessed) { SVNVersionedProperties props = getProperties(name); String[] cachableProps = SVNAdminArea14.getCachableProperties(); command.put(SVNProperty.CACHABLE_PROPS, asString(cachableProps, " ")); Map propsMap = props.loadProperties(); LinkedList presentProps = new LinkedList(); for (int i = 0; i < cachableProps.length; i++) { if (propsMap.containsKey(cachableProps[i])) { presentProps.addLast(cachableProps[i]); } } if (presentProps.size() > 0) { String presentPropsString = asString((String[])presentProps.toArray(new String[presentProps.size()]), " "); command.put(SVNProperty.PRESENT_PROPS, presentPropsString); } else { command.put(SVNProperty.PRESENT_PROPS, ""); } command.put(SVNProperty.HAS_PROPS, SVNProperty.toString(!props.isEmpty())); SVNVersionedProperties propsDiff = baseProps.compareTo(props); boolean hasPropModifications = !propsDiff.isEmpty(); command.put(SVNProperty.HAS_PROP_MODS, SVNProperty.toString(hasPropModifications)); command.put(SVNLog.NAME_ATTR, name); log.addCommand(SVNLog.MODIFY_ENTRY, command, false); command.clear(); if (!hasPropModifications) { String workingPropsPath = getThisDirName().equals(name) ? "dir-props" : "props/" + name + ".svn-work"; workingPropsPath = getAdminDirectory().getName() + "/" + workingPropsPath; command.put(SVNLog.NAME_ATTR, workingPropsPath); log.addCommand(SVNLog.DELETE, command, false); command.clear(); } } if (baseProps.isEmpty()) { command.put(SVNLog.NAME_ATTR, dstPath); log.addCommand(SVNLog.DELETE, command, false); } else { String tmpPath = "tmp/"; tmpPath += getThisDirName().equals(name) ? "dir-prop-base" : "prop-base/" + name + ".svn-base"; File tmpFile = getAdminFile(tmpPath); String srcPath = getAdminDirectory().getName() + "/" + tmpPath; SVNProperties tmpProps = new SVNProperties(tmpFile, srcPath); tmpProps.setProperties(baseProps.asMap()); command.put(SVNLog.NAME_ATTR, srcPath); command.put(SVNLog.DEST_ATTR, dstPath); log.addCommand(SVNLog.MOVE, command, false); command.clear(); command.put(SVNLog.NAME_ATTR, dstPath); log.addCommand(SVNLog.READONLY, command, false); } baseProps.setModified(false); } } } if (close) { closeVersionedProperties(); } } public void saveEntries(boolean close) throws SVNException { if (myEntries != null) { if (!isLocked()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "No write-lock in ''{0}''", getRoot()); SVNErrorManager.error(err); } SVNEntry rootEntry = (SVNEntry) myEntries.get(getThisDirName()); if (rootEntry == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_NOT_FOUND, "No default entry in directory ''{0}''", getRoot()); SVNErrorManager.error(err); } String reposURL = rootEntry.getRepositoryRoot(); String url = rootEntry.getURL(); if (reposURL != null && !SVNPathUtil.isAncestor(reposURL, url)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNKNOWN, "Entry ''{0}'' has inconsistent repository root and url", getThisDirName()); SVNErrorManager.error(err); } File tmpFile = new File(getAdminDirectory(), "tmp/entries"); Writer os = null; try { os = new OutputStreamWriter(SVNFileUtil.openFileForWriting(tmpFile), "UTF-8"); writeEntries(os); } catch (IOException e) { SVNFileUtil.closeFile(os); SVNFileUtil.deleteFile(tmpFile); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot wrtie entries file ''{0}'': {1}", new Object[] {myEntriesFile, e.getLocalizedMessage()}); SVNErrorManager.error(err, e); } finally { SVNFileUtil.closeFile(os); } SVNFileUtil.rename(tmpFile, myEntriesFile); SVNFileUtil.setReadonly(myEntriesFile, true); if (close) { closeEntries(); } } } protected Map fetchEntries() throws SVNException { if (!myEntriesFile.exists()) { return null; } Map entries = new HashMap(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(SVNFileUtil.openFileForReading(myEntriesFile), "UTF-8")); //skip format line reader.readLine(); int entryNumber = 1; while(true){ try { SVNEntry entry = readEntry(reader, entryNumber); if (entry == null) { break; } entries.put(entry.getName(), entry); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage().wrap("Error at entry {0} in entries file for ''{1}'':", new Object[]{new Integer(entryNumber), getRoot()}); SVNErrorManager.error(err); } ++entryNumber; } } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read entries file ''{0}'': {1}", new Object[] {myEntriesFile, e.getMessage()}); SVNErrorManager.error(err, e); } finally { SVNFileUtil.closeFile(reader); } SVNEntry defaultEntry = (SVNEntry)entries.get(getThisDirName()); if (defaultEntry == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_NOT_FOUND, "Missing default entry"); SVNErrorManager.error(err); } Map defaultEntryAttrs = defaultEntry.asMap(); if (defaultEntryAttrs.get(SVNProperty.REVISION) == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_REVISION, "Default entry has no revision number"); SVNErrorManager.error(err); } if (defaultEntryAttrs.get(SVNProperty.URL) == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "Default entry is missing URL"); SVNErrorManager.error(err); } for (Iterator entriesIter = entries.keySet().iterator(); entriesIter.hasNext();) { String name = (String)entriesIter.next(); SVNEntry entry = (SVNEntry)entries.get(name); if (getThisDirName().equals(name)) { continue; } Map entryAttributes = entry.asMap(); SVNNodeKind kind = SVNNodeKind.parseKind((String)entryAttributes.get(SVNProperty.KIND)); if (kind == SVNNodeKind.FILE) { if (entryAttributes.get(SVNProperty.REVISION) == null || Long.parseLong((String) entryAttributes.get(SVNProperty.REVISION), 10) < 0) { entryAttributes.put(SVNProperty.REVISION, defaultEntryAttrs.get(SVNProperty.REVISION)); } if (entryAttributes.get(SVNProperty.URL) == null) { String rootURL = (String)defaultEntryAttrs.get(SVNProperty.URL); String url = SVNPathUtil.append(rootURL, SVNEncodingUtil.uriEncode(name)); entryAttributes.put(SVNProperty.URL, url); } if (entryAttributes.get(SVNProperty.REPOS) == null) { entryAttributes.put(SVNProperty.REPOS, defaultEntryAttrs.get(SVNProperty.REPOS)); } if (entryAttributes.get(SVNProperty.UUID) == null) { String schedule = (String)entryAttributes.get(SVNProperty.SCHEDULE); if (!(SVNProperty.SCHEDULE_ADD.equals(schedule) || SVNProperty.SCHEDULE_REPLACE.equals(schedule))) { entryAttributes.put(SVNProperty.UUID, defaultEntryAttrs.get(SVNProperty.UUID)); } } if (entryAttributes.get(SVNProperty.CACHABLE_PROPS) == null) { entryAttributes.put(SVNProperty.CACHABLE_PROPS, defaultEntryAttrs.get(SVNProperty.CACHABLE_PROPS)); } } } return entries; } private SVNEntry readEntry(BufferedReader reader, int entryNumber) throws IOException, SVNException { String line = reader.readLine(); if (line == null && entryNumber > 1) { return null; } String name = parseString(line); name = name != null ? name : getThisDirName(); Map entryAttrs = new HashMap(); entryAttrs.put(SVNProperty.NAME, name); SVNEntry entry = new SVNEntry(entryAttrs, this, name); line = reader.readLine(); String kind = parseValue(line); if (kind != null) { SVNNodeKind parsedKind = SVNNodeKind.parseKind(kind); if (parsedKind != SVNNodeKind.UNKNOWN && parsedKind != SVNNodeKind.NONE) { entryAttrs.put(SVNProperty.KIND, kind); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Entry ''{0}'' has invalid node kind", name); SVNErrorManager.error(err); } } else { entryAttrs.put(SVNProperty.KIND, SVNNodeKind.NONE.toString()); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String revision = parseValue(line); if (revision != null) { entryAttrs.put(SVNProperty.REVISION, revision); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String url = parseString(line); if (url != null) { entryAttrs.put(SVNProperty.URL, url); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String reposRoot = parseString(line); if (reposRoot != null && url != null && !SVNPathUtil.isAncestor(reposRoot, url)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Entry for ''{0}'' has invalid repository root", name); SVNErrorManager.error(err); } else if (reposRoot != null) { entryAttrs.put(SVNProperty.REPOS, reposRoot); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String schedule = parseValue(line); if (schedule != null) { if (SVNProperty.SCHEDULE_ADD.equals(schedule) || SVNProperty.SCHEDULE_DELETE.equals(schedule) || SVNProperty.SCHEDULE_REPLACE.equals(schedule)) { entryAttrs.put(SVNProperty.SCHEDULE, schedule); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_ATTRIBUTE_INVALID, "Entry ''{0}'' has invalid ''{1}'' value", new Object[]{name, SVNProperty.SCHEDULE}); SVNErrorManager.error(err); } } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String timestamp = parseValue(line); if (timestamp != null) { entryAttrs.put(SVNProperty.TEXT_TIME, timestamp); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String checksum = parseString(line); if (checksum != null) { entryAttrs.put(SVNProperty.CHECKSUM, checksum); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String committedDate = parseValue(line); if (committedDate != null) { entryAttrs.put(SVNProperty.COMMITTED_DATE, committedDate); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String committedRevision = parseValue(line); if (committedRevision != null) { entryAttrs.put(SVNProperty.COMMITTED_REVISION, committedRevision); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String committedAuthor = parseString(line); if (committedAuthor != null) { entryAttrs.put(SVNProperty.LAST_AUTHOR, committedAuthor); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean hasProps = parseBoolean(line, SVNProperty.HAS_PROPS); if (hasProps) { entryAttrs.put(SVNProperty.HAS_PROPS, SVNProperty.toString(hasProps)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean hasPropMods = parseBoolean(line, SVNProperty.HAS_PROP_MODS); if (hasPropMods) { entryAttrs.put(SVNProperty.HAS_PROP_MODS, SVNProperty.toString(hasPropMods)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String cachablePropsStr = parseValue(line); if (cachablePropsStr != null) { String[] cachableProps = fromString(cachablePropsStr, " "); entryAttrs.put(SVNProperty.CACHABLE_PROPS, cachableProps); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String presentPropsStr = parseValue(line); if (presentPropsStr != null) { String[] presentProps = fromString(presentPropsStr, " "); entryAttrs.put(SVNProperty.PRESENT_PROPS, presentProps); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String prejFile = parseString(line); if (prejFile != null) { entryAttrs.put(SVNProperty.PROP_REJECT_FILE, prejFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String conflictOldFile = parseString(line); if (conflictOldFile != null) { entryAttrs.put(SVNProperty.CONFLICT_OLD, conflictOldFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String conflictNewFile = parseString(line); if (conflictNewFile != null) { entryAttrs.put(SVNProperty.CONFLICT_NEW, conflictNewFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String conflictWorkFile = parseString(line); if (conflictWorkFile != null) { entryAttrs.put(SVNProperty.CONFLICT_WRK, conflictWorkFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isCopied = parseBoolean(line, ATTRIBUTE_COPIED); if (isCopied) { entryAttrs.put(SVNProperty.COPIED, SVNProperty.toString(isCopied)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String copyfromURL = parseString(line); if (copyfromURL != null) { entryAttrs.put(SVNProperty.COPYFROM_URL, copyfromURL); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String copyfromRevision = parseValue(line); if (copyfromRevision != null) { entryAttrs.put(SVNProperty.COPYFROM_REVISION, copyfromRevision); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isDeleted = parseBoolean(line, ATTRIBUTE_DELETED); if (isDeleted) { entryAttrs.put(SVNProperty.DELETED, SVNProperty.toString(isDeleted)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isAbsent = parseBoolean(line, ATTRIBUTE_ABSENT); if (isAbsent) { entryAttrs.put(SVNProperty.ABSENT, SVNProperty.toString(isAbsent)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isIncomplete = parseBoolean(line, ATTRIBUTE_INCOMPLETE); if (isIncomplete) { entryAttrs.put(SVNProperty.INCOMPLETE, SVNProperty.toString(isIncomplete)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String uuid = parseString(line); if (uuid != null) { entryAttrs.put(SVNProperty.UUID, uuid); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockToken = parseString(line); if (lockToken != null) { entryAttrs.put(SVNProperty.LOCK_TOKEN, lockToken); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockOwner = parseString(line); if (lockOwner != null) { entryAttrs.put(SVNProperty.LOCK_OWNER, lockOwner); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockComment = parseString(line); if (lockComment != null) { entryAttrs.put(SVNProperty.LOCK_COMMENT, lockComment); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockCreationDate = parseValue(line); if (lockCreationDate != null) { entryAttrs.put(SVNProperty.LOCK_CREATION_DATE, lockCreationDate); } do { line = reader.readLine(); if (line == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Missing entry terminator"); SVNErrorManager.error(err); - } else if (line.length() == 1 && line.charAt(0) != '\f') { + } else if (line.length() == 1 && line.charAt(0) != '\f') { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Invalid entry terminator"); SVNErrorManager.error(err); + } else if (line.length() == 1 && line.charAt(0) == '\f') { + break; } } while (line != null); return entry; } private boolean isEntryFinished(String line) { return line != null && line.length() > 0 && line.charAt(0) == '\f'; } private boolean parseBoolean(String line, String field) throws SVNException { line = parseValue(line); if (line != null) { if (!line.equals(field)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Invalid value for field ''{0}''", field); SVNErrorManager.error(err); } return true; } return false; } private String parseString(String line) throws SVNException { if (line == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Unexpected end of entry"); SVNErrorManager.error(err); } else if ("".equals(line)) { return null; } int fromIndex = 0; int ind = -1; StringBuffer buffer = null; String escapedString = null; while ((ind = line.indexOf('\\', fromIndex)) != -1) { if (line.length() < ind + 4 || line.charAt(ind + 1) != 'x' || !SVNEncodingUtil.isHexDigit(line.charAt(ind + 2)) || !SVNEncodingUtil.isHexDigit(line.charAt(ind + 3))) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Invalid escape sequence"); SVNErrorManager.error(err); } if (buffer == null) { buffer = new StringBuffer(); } escapedString = line.substring(ind + 2, ind + 4); int escapedByte = Integer.parseInt(escapedString, 16); if (ind > fromIndex) { buffer.append(line.substring(fromIndex, ind)); buffer.append((char)(escapedByte & 0xFF)); } else { buffer.append((char)(escapedByte & 0xFF)); } fromIndex = ind + 4; } if (buffer != null) { if (fromIndex < line.length()) { buffer.append(line.substring(fromIndex)); } return buffer.toString(); } return line; } private String parseValue(String line) throws SVNException { if (line == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Unexpected end of entry"); SVNErrorManager.error(err); } else if ("".equals(line)) { return null; } return line; } public String getThisDirName() { return THIS_DIR; } protected void writeEntries(Writer writer) throws IOException { SVNEntry rootEntry = (SVNEntry)myEntries.get(getThisDirName()); writer.write(getFormatVersion() + "\n"); writeEntry(writer, getThisDirName(), rootEntry.asMap(), null); List names = new ArrayList(myEntries.keySet()); Collections.sort(names); for (Iterator entries = names.iterator(); entries.hasNext();) { String name = (String)entries.next(); SVNEntry entry = (SVNEntry)myEntries.get(name); if (getThisDirName().equals(name)) { continue; } Map entryAttributes = entry.asMap(); Map defaultEntryAttrs = rootEntry.asMap(); SVNNodeKind kind = SVNNodeKind.parseKind((String)entryAttributes.get(SVNProperty.KIND)); if (kind == SVNNodeKind.FILE) { if (entryAttributes.get(SVNProperty.REVISION) == null || Long.parseLong((String) entryAttributes.get(SVNProperty.REVISION), 10) < 0) { entryAttributes.put(SVNProperty.REVISION, defaultEntryAttrs.get(SVNProperty.REVISION)); } if (entryAttributes.get(SVNProperty.URL) == null) { String rootURL = (String)defaultEntryAttrs.get(SVNProperty.URL); String url = SVNPathUtil.append(rootURL, SVNEncodingUtil.uriEncode(name)); entryAttributes.put(SVNProperty.URL, url); } if (entryAttributes.get(SVNProperty.REPOS) == null) { entryAttributes.put(SVNProperty.REPOS, defaultEntryAttrs.get(SVNProperty.REPOS)); } if (entryAttributes.get(SVNProperty.UUID) == null) { String schedule = (String)entryAttributes.get(SVNProperty.SCHEDULE); if (!(SVNProperty.SCHEDULE_ADD.equals(schedule) || SVNProperty.SCHEDULE_REPLACE.equals(schedule))) { entryAttributes.put(SVNProperty.UUID, defaultEntryAttrs.get(SVNProperty.UUID)); } } if (entryAttributes.get(SVNProperty.CACHABLE_PROPS) == null) { entryAttributes.put(SVNProperty.CACHABLE_PROPS, defaultEntryAttrs.get(SVNProperty.CACHABLE_PROPS)); } } writeEntry(writer, name, entryAttributes, rootEntry.asMap()); } } private void writeEntry(Writer writer, String name, Map entry, Map rootEntry) throws IOException { boolean isThisDir = getThisDirName().equals(name); boolean isSubDir = !isThisDir && SVNProperty.KIND_DIR.equals(entry.get(SVNProperty.KIND)); int emptyFields = 0; if (!writeString(writer, name, emptyFields)) { ++emptyFields; } String kind = (String)entry.get(SVNProperty.KIND); if (writeValue(writer, kind, emptyFields)){ emptyFields = 0; } else { ++emptyFields; } String revision = null; if (isThisDir){ revision = (String)entry.get(SVNProperty.REVISION); } else if (!isSubDir){ revision = (String)entry.get(SVNProperty.REVISION); if (revision != null && revision.equals(rootEntry.get(SVNProperty.REVISION))) { revision = null; } } if (writeRevision(writer, revision, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String url = null; if (isThisDir) { url = (String)entry.get(SVNProperty.URL); } else if (!isSubDir) { url = (String)entry.get(SVNProperty.URL); String expectedURL = SVNPathUtil.append((String)rootEntry.get(SVNProperty.URL), name); if (url != null && url.equals(expectedURL)) { url = null; } } if (writeString(writer, url, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String root = null; if (isThisDir) { root = (String)entry.get(SVNProperty.REPOS); } else if (!isSubDir) { String thisDirRoot = (String)rootEntry.get(SVNProperty.REPOS); root = (String)entry.get(SVNProperty.REPOS); if (root != null && root.equals(thisDirRoot)) { root = null; } } if (writeString(writer, root, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String schedule = (String)entry.get(SVNProperty.SCHEDULE); if (schedule != null && (!SVNProperty.SCHEDULE_ADD.equals(schedule) && !SVNProperty.SCHEDULE_DELETE.equals(schedule) && !SVNProperty.SCHEDULE_REPLACE.equals(schedule))) { schedule = null; } if (writeValue(writer, schedule, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String textTime = (String)entry.get(SVNProperty.TEXT_TIME); if (writeValue(writer, textTime, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String checksum = (String)entry.get(SVNProperty.CHECKSUM); if (writeValue(writer, checksum, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String committedDate = (String)entry.get(SVNProperty.COMMITTED_DATE); if (writeValue(writer, committedDate, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String committedRevision = (String)entry.get(SVNProperty.COMMITTED_REVISION); if (writeRevision(writer, committedRevision, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String committedAuthor = (String)entry.get(SVNProperty.LAST_AUTHOR); if (writeString(writer, committedAuthor, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String hasProps = (String)entry.get(SVNProperty.HAS_PROPS); if (SVNProperty.booleanValue(hasProps)) { writeValue(writer, SVNProperty.HAS_PROPS, emptyFields); emptyFields = 0; } else { ++emptyFields; } String hasPropMods = (String)entry.get(SVNProperty.HAS_PROP_MODS); if (SVNProperty.booleanValue(hasPropMods)) { writeValue(writer, SVNProperty.HAS_PROP_MODS, emptyFields); emptyFields = 0; } else { ++emptyFields; } String cachableProps = asString((String[])entry.get(SVNProperty.CACHABLE_PROPS), " "); if (!isThisDir) { String thisDirCachableProps = asString((String[])rootEntry.get(SVNProperty.CACHABLE_PROPS), " "); if (thisDirCachableProps != null && cachableProps != null && thisDirCachableProps.equals(cachableProps)) { cachableProps = null; } } if (writeValue(writer, cachableProps, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String presentProps = asString((String[])entry.get(SVNProperty.PRESENT_PROPS), " "); if (writeValue(writer, presentProps, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String propRejectFile = (String)entry.get(SVNProperty.PROP_REJECT_FILE); if (writeString(writer, propRejectFile, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String conflictOldFile = (String)entry.get(SVNProperty.CONFLICT_OLD); if (writeString(writer, conflictOldFile, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String conflictNewFile = (String)entry.get(SVNProperty.CONFLICT_NEW); if (writeString(writer, conflictNewFile, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String conflictWrkFile = (String)entry.get(SVNProperty.CONFLICT_WRK); if (writeString(writer, conflictWrkFile, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String copiedAttr = (String)entry.get(SVNProperty.COPIED); if (SVNProperty.booleanValue(copiedAttr)) { writeValue(writer, ATTRIBUTE_COPIED, emptyFields); emptyFields = 0; } else { ++emptyFields; } String copyfromURL = (String)entry.get(SVNProperty.COPYFROM_URL); if (writeString(writer, copyfromURL, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String copyfromRevision = (String)entry.get(SVNProperty.COPYFROM_REVISION); if (writeRevision(writer, copyfromRevision, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String deletedAttr = (String)entry.get(SVNProperty.DELETED); if (SVNProperty.booleanValue(deletedAttr)) { writeValue(writer, ATTRIBUTE_DELETED, emptyFields); emptyFields = 0; } else { ++emptyFields; } String absentAttr = (String)entry.get(SVNProperty.ABSENT); if (SVNProperty.booleanValue(absentAttr)) { writeValue(writer, ATTRIBUTE_ABSENT, emptyFields); emptyFields = 0; } else { ++emptyFields; } String incompleteAttr = (String)entry.get(SVNProperty.INCOMPLETE); if (SVNProperty.booleanValue(incompleteAttr)) { writeValue(writer, ATTRIBUTE_INCOMPLETE, emptyFields); emptyFields = 0; } else { ++emptyFields; } String uuid = (String)entry.get(SVNProperty.UUID); if (!isThisDir) { String thisDirUUID = (String)rootEntry.get(SVNProperty.UUID); if (thisDirUUID != null && uuid != null && thisDirUUID.equals(uuid)) { uuid = null; } } if (writeValue(writer, uuid, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String lockToken = (String)entry.get(SVNProperty.LOCK_TOKEN); if (writeString(writer, lockToken, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String lockOwner = (String)entry.get(SVNProperty.LOCK_OWNER); if (writeString(writer, lockOwner, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String lockComment = (String)entry.get(SVNProperty.LOCK_COMMENT); if (writeString(writer, lockComment, emptyFields)) { emptyFields = 0; } else { ++emptyFields; } String lockCreationDate = (String)entry.get(SVNProperty.LOCK_CREATION_DATE); writeValue(writer, lockCreationDate, emptyFields); writer.write("\f\n"); writer.flush(); } private boolean writeString(Writer writer, String str, int emptyFields) throws IOException { if (str != null && str.length() > 0) { for (int i = 0; i < emptyFields; i++) { writer.write('\n'); } for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (SVNEncodingUtil.isASCIIControlChar(ch) || ch == '\\') { writer.write("\\x"); writer.write(SVNFormatUtil.getHexNumberFromByte((byte)ch)); } else { writer.write(ch); } } writer.write('\n'); return true; } return false; } private boolean writeValue(Writer writer, String val, int emptyFields) throws IOException { if (val != null && val.length() > 0) { for (int i = 0; i < emptyFields; i++) { writer.write('\n'); } writer.write(val); writer.write('\n'); return true; } return false; } private boolean writeRevision(Writer writer, String rev, int emptyFields) throws IOException { if (rev != null && rev.length() > 0 && Long.parseLong(rev) >= 0) { for (int i = 0; i < emptyFields; i++) { writer.write('\n'); } writer.write(rev); writer.write('\n'); return true; } return false; } public boolean hasPropModifications(String name) throws SVNException { SVNEntry entry = getEntry(name, true); if (entry != null) { Map entryAttrs = entry.asMap(); return SVNProperty.booleanValue((String)entryAttrs.get(SVNProperty.HAS_PROP_MODS)); } return false; } public boolean hasProperties(String name) throws SVNException { SVNEntry entry = getEntry(name, true); if (entry != null) { Map entryAttrs = entry.asMap(); return SVNProperty.booleanValue((String)entryAttrs.get(SVNProperty.HAS_PROPS)); } return false; } public boolean lock() throws SVNException { return lock(false); } public boolean lock(boolean stealLock) throws SVNException { if (!isVersioned()) { return false; } if (stealLock && myLockFile.isFile()) { setLocked(true); return true; } boolean created = false; try { created = myLockFile.createNewFile(); } catch (IOException e) { SVNErrorCode code = e.getMessage().indexOf("denied") >= 0 ? SVNErrorCode.WC_LOCKED : SVNErrorCode.WC_NOT_LOCKED; SVNErrorMessage err = SVNErrorMessage.create(code, "Cannot lock working copy ''{0}'': {1}", new Object[] {getRoot(), e.getLocalizedMessage()}); SVNErrorManager.error(err, e); } if (created) { setLocked(true); return created; } if (myLockFile.isFile()) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_LOCKED, "Working copy ''{0}'' locked; try performing ''cleanup''", getRoot()); SVNErrorManager.error(err); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Cannot lock working copy ''{0}''", getRoot()); SVNErrorManager.error(err); } return false; } private void createFormatFile(File formatFile, boolean createMyself) throws SVNException { OutputStream os = null; try { formatFile = createMyself ? getAdminFile("format") : formatFile; os = SVNFileUtil.openFileForWriting(formatFile); os.write(String.valueOf(WC_FORMAT).getBytes("UTF-8")); os.write('\n'); } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getLocalizedMessage()); SVNErrorManager.error(err, e); } finally { SVNFileUtil.closeFile(os); } } public SVNAdminArea createVersionedDirectory(File dir, String url, String rootURL, String uuid, long revNumber, boolean createMyself) throws SVNException { dir = createMyself ? getRoot() : dir; dir.mkdirs(); File adminDir = createMyself ? getAdminDirectory() : new File(dir, SVNFileUtil.getAdminDirectoryName()); adminDir.mkdir(); SVNFileUtil.setHidden(adminDir, true); // lock dir. File lockFile = createMyself ? myLockFile : new File(adminDir, "lock"); SVNFileUtil.createEmptyFile(lockFile); File[] tmp = { createMyself ? getAdminFile("tmp") : new File(adminDir, "tmp"), createMyself ? getAdminFile("tmp" + File.separatorChar + "props") : new File(adminDir, "tmp" + File.separatorChar + "props"), createMyself ? getAdminFile("tmp" + File.separatorChar + "prop-base") : new File(adminDir, "tmp" + File.separatorChar + "prop-base"), createMyself ? getAdminFile("tmp" + File.separatorChar + "text-base") : new File(adminDir, "tmp" + File.separatorChar + "text-base"), createMyself ? getAdminFile("props") : new File(adminDir, "props"), createMyself ? getAdminFile("prop-base") : new File(adminDir, "prop-base"), createMyself ? getAdminFile("text-base") : new File(adminDir, "text-base") }; for (int i = 0; i < tmp.length; i++) { tmp[i].mkdir(); } // for backward compatibility createFormatFile(createMyself ? null : new File(adminDir, "format"), createMyself); SVNAdminArea adminArea = createMyself ? this : new SVNAdminArea14(dir); adminArea.setLocked(true); SVNEntry rootEntry = adminArea.getEntry(adminArea.getThisDirName(), true); if (rootEntry == null) { rootEntry = adminArea.addEntry(adminArea.getThisDirName()); } if (url != null) { rootEntry.setURL(url); } rootEntry.setRepositoryRoot(rootURL); rootEntry.setRevision(revNumber); rootEntry.setKind(SVNNodeKind.DIR); if (uuid != null) { rootEntry.setUUID(uuid); } if (revNumber > 0) { rootEntry.setIncomplete(true); } rootEntry.setCachableProperties(ourCachableProperties); try { adminArea.saveEntries(false); } catch (SVNException svne) { SVNErrorMessage err = svne.getErrorMessage().wrap("Error writing entries file for ''{0}''", dir); SVNErrorManager.error(err, svne); } // unlock dir. SVNFileUtil.deleteFile(lockFile); return adminArea; } public SVNAdminArea upgradeFormat(SVNAdminArea adminArea) throws SVNException { File logFile = adminArea.getAdminFile("log"); SVNFileType type = SVNFileType.getType(logFile); if (type == SVNFileType.FILE) { SVNDebugLog.getDefaultLog().info("Upgrade failed: found a log file at '" + logFile + "'"); return adminArea; } SVNLog log = getLog(); Map command = new HashMap(); command.put(SVNLog.FORMAT_ATTR, String.valueOf(getFormatVersion())); log.addCommand(SVNLog.UPGRADE_FORMAT, command, false); command.clear(); setWCAccess(adminArea.getWCAccess()); Iterator entries = adminArea.entries(true); myEntries = new HashMap(); Map basePropsCache = getBasePropertiesStorage(true); Map propsCache = getPropertiesStorage(true); for (; entries.hasNext();) { SVNEntry entry = (SVNEntry) entries.next(); SVNEntry newEntry = new SVNEntry(new HashMap(entry.asMap()), this, entry.getName()); myEntries.put(entry.getName(), newEntry); if (entry.getKind() != SVNNodeKind.FILE && !adminArea.getThisDirName().equals(entry.getName())) { continue; } SVNVersionedProperties srcBaseProps = adminArea.getBaseProperties(entry.getName()); Map basePropsHolder = srcBaseProps.asMap(); SVNVersionedProperties dstBaseProps = new SVNProperties13(basePropsHolder); basePropsCache.put(entry.getName(), dstBaseProps); dstBaseProps.setModified(true); SVNVersionedProperties srcProps = adminArea.getProperties(entry.getName()); SVNVersionedProperties dstProps = new SVNProperties14(srcProps.asMap(), this, entry.getName()){ protected Map loadProperties() throws SVNException { return getPropertiesMap(); } }; propsCache.put(entry.getName(), dstProps); dstProps.setModified(true); command.put(SVNLog.NAME_ATTR, entry.getName()); command.put(SVNProperty.shortPropertyName(SVNProperty.PROP_TIME), SVNTimeUtil.formatDate(new Date(0), true)); log.addCommand(SVNLog.MODIFY_ENTRY, command, false); command.clear(); SVNVersionedProperties wcProps = adminArea.getWCProperties(entry.getName()); log.logChangedWCProperties(entry.getName(), wcProps.asMap()); } saveVersionedProperties(log, true); log.save(); SVNFileUtil.deleteFile(getAdminFile("README.txt")); SVNFileUtil.deleteFile(getAdminFile("empty-file")); SVNFileUtil.deleteAll(getAdminFile("wcprops"), true); SVNFileUtil.deleteAll(getAdminFile("tmp/wcprops"), true); SVNFileUtil.deleteAll(getAdminFile("dir-wcprops"), true); runLogs(); return this; } public void postUpgradeFormat(int format) throws SVNException { if (format == WC_FORMAT) { createFormatFile(null, true); return; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNKNOWN, "Unexpected format number:\n" + " expected: {0,number,integer}\n" + " actual: {1,number,integer}", new Object[]{new Integer(WC_FORMAT), new Integer(format)}); SVNErrorManager.error(err); } public void postCommit(String fileName, long revisionNumber, boolean implicit, SVNErrorCode errorCode) throws SVNException { SVNEntry entry = getEntry(fileName, true); if (entry == null || (!getThisDirName().equals(fileName) && entry.getKind() != SVNNodeKind.FILE)) { SVNErrorMessage err = SVNErrorMessage.create(errorCode, "Log command for directory ''{0}'' is mislocated", getRoot()); SVNErrorManager.error(err); } if (!implicit && entry.isScheduledForDeletion()) { if (getThisDirName().equals(fileName)) { entry.setRevision(revisionNumber); entry.setKind(SVNNodeKind.DIR); File killMe = getAdminFile("KILLME"); if (killMe.getParentFile().isDirectory()) { try { killMe.createNewFile(); } catch (IOException e) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot create file ''{0}'': {1}", new Object[] {killMe, e.getLocalizedMessage()}); SVNErrorManager.error(err, e); } } } else { removeFromRevisionControl(fileName, false, false); SVNEntry parentEntry = getEntry(getThisDirName(), true); if (revisionNumber > parentEntry.getRevision()) { SVNEntry fileEntry = addEntry(fileName); fileEntry.setKind(SVNNodeKind.FILE); fileEntry.setDeleted(true); fileEntry.setRevision(revisionNumber); } } return; } if (!implicit && entry.isScheduledForReplacement() && getThisDirName().equals(fileName)) { for (Iterator ents = entries(true); ents.hasNext();) { SVNEntry currentEntry = (SVNEntry) ents.next(); if (!currentEntry.isScheduledForDeletion()) { continue; } if (currentEntry.getKind() == SVNNodeKind.FILE || currentEntry.getKind() == SVNNodeKind.DIR) { removeFromRevisionControl(currentEntry.getName(), false, false); } } } long textTime = 0; if (!implicit && !getThisDirName().equals(fileName)) { File tmpFile = getBaseFile(fileName, true); SVNFileType fileType = SVNFileType.getType(tmpFile); if (fileType == SVNFileType.FILE || fileType == SVNFileType.SYMLINK) { boolean modified = false; File workingFile = getFile(fileName); long tmpTimestamp = tmpFile.lastModified(); long wkTimestamp = workingFile.lastModified(); if (tmpTimestamp != wkTimestamp) { // check if wc file is not modified File tmpFile2 = SVNFileUtil.createUniqueFile(tmpFile.getParentFile(), fileName, ".tmp"); try { String tmpFile2Path = SVNFileUtil.getBasePath(tmpFile2); SVNTranslator.translate(this, fileName, fileName, tmpFile2Path, false); modified = !SVNFileUtil.compareFiles(tmpFile, tmpFile2, null); } catch (SVNException svne) { SVNErrorMessage err = SVNErrorMessage.create(errorCode, "Error comparing ''{0}'' and ''{1}''", new Object[] {workingFile, tmpFile}); SVNErrorManager.error(err, svne); } finally { tmpFile2.delete(); } } textTime = modified ? tmpTimestamp : wkTimestamp; } } if (!implicit && entry.isScheduledForReplacement()) { SVNFileUtil.deleteFile(getBasePropertiesFile(fileName, false)); } boolean setReadWrite = false; boolean setNotExecutable = false; SVNVersionedProperties baseProps = getBaseProperties(fileName); SVNVersionedProperties wcProps = getProperties(fileName); //TODO: to work properly we must create a tmp working props file //instead of tmp base props one File tmpPropsFile = getPropertiesFile(fileName, true); File wcPropsFile = getPropertiesFile(fileName, false); File basePropertiesFile = getBasePropertiesFile(fileName, false); SVNFileType tmpPropsType = SVNFileType.getType(tmpPropsFile); // tmp may be missing when there were no prop change at all! if (tmpPropsType == SVNFileType.FILE) { if (!getThisDirName().equals(fileName)) { SVNVersionedProperties propDiff = baseProps.compareTo(wcProps); setReadWrite = propDiff != null && propDiff.containsProperty(SVNProperty.NEEDS_LOCK) && propDiff.getPropertyValue(SVNProperty.NEEDS_LOCK) == null; setNotExecutable = propDiff != null && propDiff.containsProperty(SVNProperty.EXECUTABLE) && propDiff.getPropertyValue(SVNProperty.EXECUTABLE) == null; } try { if (!tmpPropsFile.exists() || tmpPropsFile.length() <= 4) { SVNFileUtil.deleteFile(basePropertiesFile); } else { SVNFileUtil.copyFile(tmpPropsFile, basePropertiesFile, true); SVNFileUtil.setReadonly(basePropertiesFile, true); } } finally { SVNFileUtil.deleteFile(tmpPropsFile); } } if (!getThisDirName().equals(fileName) && !implicit) { File tmpFile = getBaseFile(fileName, true); File baseFile = getBaseFile(fileName, false); File wcFile = getFile(fileName); File tmpFile2 = null; try { tmpFile2 = SVNFileUtil.createUniqueFile(tmpFile.getParentFile(), fileName, ".tmp"); boolean overwritten = false; SVNFileType fileType = SVNFileType.getType(tmpFile); boolean special = getProperties(fileName).getPropertyValue(SVNProperty.SPECIAL) != null; if (SVNFileUtil.isWindows || !special) { if (fileType == SVNFileType.FILE) { SVNTranslator.translate(this, fileName, SVNFileUtil.getBasePath(tmpFile), SVNFileUtil.getBasePath(tmpFile2), true); } else { SVNTranslator.translate(this, fileName, fileName, SVNFileUtil.getBasePath(tmpFile2), true); } if (!SVNFileUtil.compareFiles(tmpFile2, wcFile, null)) { SVNFileUtil.copyFile(tmpFile2, wcFile, true); overwritten = true; } } boolean needsReadonly = getProperties(fileName).getPropertyValue(SVNProperty.NEEDS_LOCK) != null && entry.getLockToken() == null; boolean needsExecutable = getProperties(fileName).getPropertyValue(SVNProperty.EXECUTABLE) != null; if (needsReadonly) { SVNFileUtil.setReadonly(wcFile, true); overwritten = true; } if (needsExecutable) { SVNFileUtil.setExecutable(wcFile, true); overwritten = true; } if (fileType == SVNFileType.FILE) { SVNFileUtil.rename(tmpFile, baseFile); } if (setReadWrite) { SVNFileUtil.setReadonly(wcFile, false); overwritten = true; } if (setNotExecutable) { SVNFileUtil.setExecutable(wcFile, false); overwritten = true; } if (overwritten) { textTime = wcFile.lastModified(); } } catch (SVNException svne) { SVNErrorMessage err = SVNErrorMessage.create(errorCode, "Error replacing text-base of ''{0}''", fileName); SVNErrorManager.error(err, svne); } finally { tmpFile2.delete(); tmpFile.delete(); } } // update entry Map entryAttrs = new HashMap(); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.REVISION), SVNProperty.toString(revisionNumber)); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.KIND), getThisDirName().equals(fileName) ? SVNProperty.KIND_DIR : SVNProperty.KIND_FILE); if (!implicit) { entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.SCHEDULE), null); } entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.COPIED), SVNProperty.toString(false)); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.DELETED), SVNProperty.toString(false)); if (textTime != 0 && !implicit) { entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.TEXT_TIME), SVNTimeUtil.formatDate(new Date(textTime))); } entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.CONFLICT_NEW), null); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.CONFLICT_OLD), null); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.CONFLICT_WRK), null); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.PROP_REJECT_FILE), null); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.COPYFROM_REVISION), null); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.COPYFROM_URL), null); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.HAS_PROP_MODS), SVNProperty.toString(false)); try { modifyEntry(fileName, entryAttrs, false, true); } catch (SVNException svne) { SVNErrorMessage err = SVNErrorMessage.create(errorCode, "Error modifying entry of ''{0}''", fileName); SVNErrorManager.error(err, svne); } SVNFileUtil.deleteFile(wcPropsFile); if (!getThisDirName().equals(fileName)) { return; } // update entry in parent. File dirFile = getRoot(); if (getWCAccess().isWCRoot(getRoot())) { return; } boolean unassociated = false; SVNAdminArea parentArea = null; try { parentArea = getWCAccess().retrieve(dirFile.getParentFile()); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { parentArea = getWCAccess().open(dirFile.getParentFile(), true, false, 0); unassociated = true; } throw svne; } SVNEntry entryInParent = parentArea.getEntry(dirFile.getName(), false); if (entryInParent != null) { entryAttrs.clear(); if (!implicit) { entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.SCHEDULE), null); } entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.COPIED), SVNProperty.toString(false)); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.COPYFROM_REVISION), null); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.COPYFROM_URL), null); entryAttrs.put(SVNProperty.shortPropertyName(SVNProperty.DELETED), SVNProperty.toString(false)); try { parentArea.modifyEntry(entryInParent.getName(), entryAttrs, true, true); } catch (SVNException svne) { SVNErrorMessage err = SVNErrorMessage.create(errorCode, "Error modifying entry of ''{0}''", fileName); SVNErrorManager.error(err, svne); } } parentArea.saveEntries(false); if (unassociated) { getWCAccess().closeAdminArea(dirFile.getParentFile()); } } public boolean unlock() throws SVNException { if (!myLockFile.exists()) { return true; } // only if there are not locks or killme files. boolean killMe = getAdminFile("KILLME").exists(); if (killMe) { return false; } File[] logs = SVNFileListUtil.listFiles(getAdminDirectory()); for (int i = 0; logs != null && i < logs.length; i++) { File log = logs[i]; if ("log".equals(log.getName()) || log.getName().startsWith("log.")) { return false; } } boolean deleted = myLockFile.delete(); if (!deleted) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_LOCKED, "Failed to unlock working copy ''{0}''", getRoot()); SVNErrorManager.error(err); } return deleted; } public boolean isVersioned() { if (getAdminDirectory().isDirectory() && myEntriesFile.canRead()) { try { if (getEntry("", false) != null) { return true; } } catch (SVNException e) { // } } return false; } public boolean isLocked() throws SVNException { if (!myWasLocked) { return false; } SVNFileType type = SVNFileType.getType(myLockFile); if (type == SVNFileType.FILE) { return true; } else if (type == SVNFileType.NONE) { return false; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_LOCKED, "Lock file ''{0}'' is not a regular file", myLockFile); SVNErrorManager.error(err); return false; } protected int getFormatVersion() { return WC_FORMAT; } protected boolean isEntryPropertyApplicable(String name) { return true; } }
false
true
private SVNEntry readEntry(BufferedReader reader, int entryNumber) throws IOException, SVNException { String line = reader.readLine(); if (line == null && entryNumber > 1) { return null; } String name = parseString(line); name = name != null ? name : getThisDirName(); Map entryAttrs = new HashMap(); entryAttrs.put(SVNProperty.NAME, name); SVNEntry entry = new SVNEntry(entryAttrs, this, name); line = reader.readLine(); String kind = parseValue(line); if (kind != null) { SVNNodeKind parsedKind = SVNNodeKind.parseKind(kind); if (parsedKind != SVNNodeKind.UNKNOWN && parsedKind != SVNNodeKind.NONE) { entryAttrs.put(SVNProperty.KIND, kind); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Entry ''{0}'' has invalid node kind", name); SVNErrorManager.error(err); } } else { entryAttrs.put(SVNProperty.KIND, SVNNodeKind.NONE.toString()); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String revision = parseValue(line); if (revision != null) { entryAttrs.put(SVNProperty.REVISION, revision); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String url = parseString(line); if (url != null) { entryAttrs.put(SVNProperty.URL, url); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String reposRoot = parseString(line); if (reposRoot != null && url != null && !SVNPathUtil.isAncestor(reposRoot, url)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Entry for ''{0}'' has invalid repository root", name); SVNErrorManager.error(err); } else if (reposRoot != null) { entryAttrs.put(SVNProperty.REPOS, reposRoot); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String schedule = parseValue(line); if (schedule != null) { if (SVNProperty.SCHEDULE_ADD.equals(schedule) || SVNProperty.SCHEDULE_DELETE.equals(schedule) || SVNProperty.SCHEDULE_REPLACE.equals(schedule)) { entryAttrs.put(SVNProperty.SCHEDULE, schedule); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_ATTRIBUTE_INVALID, "Entry ''{0}'' has invalid ''{1}'' value", new Object[]{name, SVNProperty.SCHEDULE}); SVNErrorManager.error(err); } } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String timestamp = parseValue(line); if (timestamp != null) { entryAttrs.put(SVNProperty.TEXT_TIME, timestamp); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String checksum = parseString(line); if (checksum != null) { entryAttrs.put(SVNProperty.CHECKSUM, checksum); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String committedDate = parseValue(line); if (committedDate != null) { entryAttrs.put(SVNProperty.COMMITTED_DATE, committedDate); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String committedRevision = parseValue(line); if (committedRevision != null) { entryAttrs.put(SVNProperty.COMMITTED_REVISION, committedRevision); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String committedAuthor = parseString(line); if (committedAuthor != null) { entryAttrs.put(SVNProperty.LAST_AUTHOR, committedAuthor); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean hasProps = parseBoolean(line, SVNProperty.HAS_PROPS); if (hasProps) { entryAttrs.put(SVNProperty.HAS_PROPS, SVNProperty.toString(hasProps)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean hasPropMods = parseBoolean(line, SVNProperty.HAS_PROP_MODS); if (hasPropMods) { entryAttrs.put(SVNProperty.HAS_PROP_MODS, SVNProperty.toString(hasPropMods)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String cachablePropsStr = parseValue(line); if (cachablePropsStr != null) { String[] cachableProps = fromString(cachablePropsStr, " "); entryAttrs.put(SVNProperty.CACHABLE_PROPS, cachableProps); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String presentPropsStr = parseValue(line); if (presentPropsStr != null) { String[] presentProps = fromString(presentPropsStr, " "); entryAttrs.put(SVNProperty.PRESENT_PROPS, presentProps); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String prejFile = parseString(line); if (prejFile != null) { entryAttrs.put(SVNProperty.PROP_REJECT_FILE, prejFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String conflictOldFile = parseString(line); if (conflictOldFile != null) { entryAttrs.put(SVNProperty.CONFLICT_OLD, conflictOldFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String conflictNewFile = parseString(line); if (conflictNewFile != null) { entryAttrs.put(SVNProperty.CONFLICT_NEW, conflictNewFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String conflictWorkFile = parseString(line); if (conflictWorkFile != null) { entryAttrs.put(SVNProperty.CONFLICT_WRK, conflictWorkFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isCopied = parseBoolean(line, ATTRIBUTE_COPIED); if (isCopied) { entryAttrs.put(SVNProperty.COPIED, SVNProperty.toString(isCopied)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String copyfromURL = parseString(line); if (copyfromURL != null) { entryAttrs.put(SVNProperty.COPYFROM_URL, copyfromURL); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String copyfromRevision = parseValue(line); if (copyfromRevision != null) { entryAttrs.put(SVNProperty.COPYFROM_REVISION, copyfromRevision); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isDeleted = parseBoolean(line, ATTRIBUTE_DELETED); if (isDeleted) { entryAttrs.put(SVNProperty.DELETED, SVNProperty.toString(isDeleted)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isAbsent = parseBoolean(line, ATTRIBUTE_ABSENT); if (isAbsent) { entryAttrs.put(SVNProperty.ABSENT, SVNProperty.toString(isAbsent)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isIncomplete = parseBoolean(line, ATTRIBUTE_INCOMPLETE); if (isIncomplete) { entryAttrs.put(SVNProperty.INCOMPLETE, SVNProperty.toString(isIncomplete)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String uuid = parseString(line); if (uuid != null) { entryAttrs.put(SVNProperty.UUID, uuid); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockToken = parseString(line); if (lockToken != null) { entryAttrs.put(SVNProperty.LOCK_TOKEN, lockToken); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockOwner = parseString(line); if (lockOwner != null) { entryAttrs.put(SVNProperty.LOCK_OWNER, lockOwner); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockComment = parseString(line); if (lockComment != null) { entryAttrs.put(SVNProperty.LOCK_COMMENT, lockComment); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockCreationDate = parseValue(line); if (lockCreationDate != null) { entryAttrs.put(SVNProperty.LOCK_CREATION_DATE, lockCreationDate); } do { line = reader.readLine(); if (line == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Missing entry terminator"); SVNErrorManager.error(err); } else if (line.length() == 1 && line.charAt(0) != '\f') { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Invalid entry terminator"); SVNErrorManager.error(err); } } while (line != null); return entry; }
private SVNEntry readEntry(BufferedReader reader, int entryNumber) throws IOException, SVNException { String line = reader.readLine(); if (line == null && entryNumber > 1) { return null; } String name = parseString(line); name = name != null ? name : getThisDirName(); Map entryAttrs = new HashMap(); entryAttrs.put(SVNProperty.NAME, name); SVNEntry entry = new SVNEntry(entryAttrs, this, name); line = reader.readLine(); String kind = parseValue(line); if (kind != null) { SVNNodeKind parsedKind = SVNNodeKind.parseKind(kind); if (parsedKind != SVNNodeKind.UNKNOWN && parsedKind != SVNNodeKind.NONE) { entryAttrs.put(SVNProperty.KIND, kind); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Entry ''{0}'' has invalid node kind", name); SVNErrorManager.error(err); } } else { entryAttrs.put(SVNProperty.KIND, SVNNodeKind.NONE.toString()); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String revision = parseValue(line); if (revision != null) { entryAttrs.put(SVNProperty.REVISION, revision); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String url = parseString(line); if (url != null) { entryAttrs.put(SVNProperty.URL, url); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String reposRoot = parseString(line); if (reposRoot != null && url != null && !SVNPathUtil.isAncestor(reposRoot, url)) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Entry for ''{0}'' has invalid repository root", name); SVNErrorManager.error(err); } else if (reposRoot != null) { entryAttrs.put(SVNProperty.REPOS, reposRoot); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String schedule = parseValue(line); if (schedule != null) { if (SVNProperty.SCHEDULE_ADD.equals(schedule) || SVNProperty.SCHEDULE_DELETE.equals(schedule) || SVNProperty.SCHEDULE_REPLACE.equals(schedule)) { entryAttrs.put(SVNProperty.SCHEDULE, schedule); } else { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_ATTRIBUTE_INVALID, "Entry ''{0}'' has invalid ''{1}'' value", new Object[]{name, SVNProperty.SCHEDULE}); SVNErrorManager.error(err); } } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String timestamp = parseValue(line); if (timestamp != null) { entryAttrs.put(SVNProperty.TEXT_TIME, timestamp); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String checksum = parseString(line); if (checksum != null) { entryAttrs.put(SVNProperty.CHECKSUM, checksum); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String committedDate = parseValue(line); if (committedDate != null) { entryAttrs.put(SVNProperty.COMMITTED_DATE, committedDate); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String committedRevision = parseValue(line); if (committedRevision != null) { entryAttrs.put(SVNProperty.COMMITTED_REVISION, committedRevision); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String committedAuthor = parseString(line); if (committedAuthor != null) { entryAttrs.put(SVNProperty.LAST_AUTHOR, committedAuthor); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean hasProps = parseBoolean(line, SVNProperty.HAS_PROPS); if (hasProps) { entryAttrs.put(SVNProperty.HAS_PROPS, SVNProperty.toString(hasProps)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean hasPropMods = parseBoolean(line, SVNProperty.HAS_PROP_MODS); if (hasPropMods) { entryAttrs.put(SVNProperty.HAS_PROP_MODS, SVNProperty.toString(hasPropMods)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String cachablePropsStr = parseValue(line); if (cachablePropsStr != null) { String[] cachableProps = fromString(cachablePropsStr, " "); entryAttrs.put(SVNProperty.CACHABLE_PROPS, cachableProps); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String presentPropsStr = parseValue(line); if (presentPropsStr != null) { String[] presentProps = fromString(presentPropsStr, " "); entryAttrs.put(SVNProperty.PRESENT_PROPS, presentProps); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String prejFile = parseString(line); if (prejFile != null) { entryAttrs.put(SVNProperty.PROP_REJECT_FILE, prejFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String conflictOldFile = parseString(line); if (conflictOldFile != null) { entryAttrs.put(SVNProperty.CONFLICT_OLD, conflictOldFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String conflictNewFile = parseString(line); if (conflictNewFile != null) { entryAttrs.put(SVNProperty.CONFLICT_NEW, conflictNewFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String conflictWorkFile = parseString(line); if (conflictWorkFile != null) { entryAttrs.put(SVNProperty.CONFLICT_WRK, conflictWorkFile); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isCopied = parseBoolean(line, ATTRIBUTE_COPIED); if (isCopied) { entryAttrs.put(SVNProperty.COPIED, SVNProperty.toString(isCopied)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String copyfromURL = parseString(line); if (copyfromURL != null) { entryAttrs.put(SVNProperty.COPYFROM_URL, copyfromURL); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String copyfromRevision = parseValue(line); if (copyfromRevision != null) { entryAttrs.put(SVNProperty.COPYFROM_REVISION, copyfromRevision); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isDeleted = parseBoolean(line, ATTRIBUTE_DELETED); if (isDeleted) { entryAttrs.put(SVNProperty.DELETED, SVNProperty.toString(isDeleted)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isAbsent = parseBoolean(line, ATTRIBUTE_ABSENT); if (isAbsent) { entryAttrs.put(SVNProperty.ABSENT, SVNProperty.toString(isAbsent)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } boolean isIncomplete = parseBoolean(line, ATTRIBUTE_INCOMPLETE); if (isIncomplete) { entryAttrs.put(SVNProperty.INCOMPLETE, SVNProperty.toString(isIncomplete)); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String uuid = parseString(line); if (uuid != null) { entryAttrs.put(SVNProperty.UUID, uuid); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockToken = parseString(line); if (lockToken != null) { entryAttrs.put(SVNProperty.LOCK_TOKEN, lockToken); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockOwner = parseString(line); if (lockOwner != null) { entryAttrs.put(SVNProperty.LOCK_OWNER, lockOwner); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockComment = parseString(line); if (lockComment != null) { entryAttrs.put(SVNProperty.LOCK_COMMENT, lockComment); } line = reader.readLine(); if (isEntryFinished(line)) { return entry; } String lockCreationDate = parseValue(line); if (lockCreationDate != null) { entryAttrs.put(SVNProperty.LOCK_CREATION_DATE, lockCreationDate); } do { line = reader.readLine(); if (line == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Missing entry terminator"); SVNErrorManager.error(err); } else if (line.length() == 1 && line.charAt(0) != '\f') { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Invalid entry terminator"); SVNErrorManager.error(err); } else if (line.length() == 1 && line.charAt(0) == '\f') { break; } } while (line != null); return entry; }
diff --git a/src/org/nutz/json/JsonParsing.java b/src/org/nutz/json/JsonParsing.java index 912da7fd2..ae40e8648 100644 --- a/src/org/nutz/json/JsonParsing.java +++ b/src/org/nutz/json/JsonParsing.java @@ -1,126 +1,126 @@ package org.nutz.json; import java.io.Reader; import java.lang.reflect.Array; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.nutz.castor.Castors; import org.nutz.json.entity.JsonEntity; import org.nutz.json.entity.JsonEntityField; import org.nutz.lang.Lang; import org.nutz.lang.Mirror; public class JsonParsing { Object parse(Type type, Reader reader) { Object obj = new JsonCompile().parse(reader); return convert(type, obj); } @SuppressWarnings("unchecked") Object convert(Type type, Object obj) { if (obj == null) return null; if (type == null) return obj; if (obj instanceof Map) { return map2Object(type, (Map<String, Object>) obj); } else if (obj instanceof List) { return list2Object(type, (List<Object>) obj); } else {// obj是基本数据类型或String return Castors.me().castTo(obj, (Class<?>) type); } } @SuppressWarnings({"rawtypes", "unchecked"}) Object map2Object(Type type, Map<String, Object> map) { Class<?> clazz = Lang.getTypeClass(type); Mirror<?> me = Mirror.me(clazz); if (Map.class.isAssignableFrom(clazz)) { Map re = null; if (clazz.isInterface()) re = new HashMap(); else re = (Map) me.born(); if (type instanceof ParameterizedType) { // 看来有泛型信息哦 ParameterizedType pt = (ParameterizedType) type; Type[] ts = pt.getActualTypeArguments(); Type tt = null; if (ts != null && ts.length > 1) tt = Lang.getTypeClass(ts[1]);// TODO 只能做到一层的泛型 for (Entry<String, Object> entry : map.entrySet()) { re.put(entry.getKey(), convert(tt, entry.getValue())); } } else re.putAll(map); return re; } else { // 看来是Pojo JsonEntity jen = Json.getEntity(me.getType()); Object re = jen.born(); // 遍历目标对象的全部字段 for (JsonEntityField jef : jen.getFields()) { Object value = map.get(jef.getName()); if (value == null) continue; jef.setValue(re, convert(jef.getGenericType(), value)); } return re; } } @SuppressWarnings({"unchecked", "rawtypes"}) Object list2Object(Type type, List<Object> list) { Class<?> clazz = Lang.getTypeClass(type); Type tt = null; if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Type[] ts = pt.getActualTypeArguments(); if (ts != null && ts.length > 0) tt = Lang.getTypeClass(ts[0]);// TODO 只能做到一层的泛型 } if (clazz.isArray()) {// 看来是数组 List re = new ArrayList(list.size()); for (Object object : list) { re.add(convert(clazz.getComponentType(), object)); } Object ary = Array.newInstance(clazz.getComponentType(), list.size()); int i = 0; - for (Iterator it = list.iterator(); it.hasNext();) { + for (Iterator it = re.iterator(); it.hasNext();) { if (tt != null) Array.set(ary, i++, convert(tt, it.next())); else Array.set(ary, i++, Castors.me().castTo(it.next(), clazz.getComponentType())); } return ary; } if (List.class.isAssignableFrom(clazz)) { if (tt == null) // 没有泛型信息? 那只好直接返回了 return list; Mirror me = Mirror.me(clazz); List re = null; if (clazz.isInterface()) re = new LinkedList(); else re = (List) me.born(); for (Object object : list) { re.add(convert(tt, object)); } return re; } throw unexpectedType(List.class, clazz); } private static final RuntimeException unexpectedType(Type expect, Type act) { return Lang.makeThrow("expect %s but %s", expect, act); } }
true
true
Object list2Object(Type type, List<Object> list) { Class<?> clazz = Lang.getTypeClass(type); Type tt = null; if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Type[] ts = pt.getActualTypeArguments(); if (ts != null && ts.length > 0) tt = Lang.getTypeClass(ts[0]);// TODO 只能做到一层的泛型 } if (clazz.isArray()) {// 看来是数组 List re = new ArrayList(list.size()); for (Object object : list) { re.add(convert(clazz.getComponentType(), object)); } Object ary = Array.newInstance(clazz.getComponentType(), list.size()); int i = 0; for (Iterator it = list.iterator(); it.hasNext();) { if (tt != null) Array.set(ary, i++, convert(tt, it.next())); else Array.set(ary, i++, Castors.me().castTo(it.next(), clazz.getComponentType())); } return ary; } if (List.class.isAssignableFrom(clazz)) { if (tt == null) // 没有泛型信息? 那只好直接返回了 return list; Mirror me = Mirror.me(clazz); List re = null; if (clazz.isInterface()) re = new LinkedList(); else re = (List) me.born(); for (Object object : list) { re.add(convert(tt, object)); } return re; } throw unexpectedType(List.class, clazz); }
Object list2Object(Type type, List<Object> list) { Class<?> clazz = Lang.getTypeClass(type); Type tt = null; if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; Type[] ts = pt.getActualTypeArguments(); if (ts != null && ts.length > 0) tt = Lang.getTypeClass(ts[0]);// TODO 只能做到一层的泛型 } if (clazz.isArray()) {// 看来是数组 List re = new ArrayList(list.size()); for (Object object : list) { re.add(convert(clazz.getComponentType(), object)); } Object ary = Array.newInstance(clazz.getComponentType(), list.size()); int i = 0; for (Iterator it = re.iterator(); it.hasNext();) { if (tt != null) Array.set(ary, i++, convert(tt, it.next())); else Array.set(ary, i++, Castors.me().castTo(it.next(), clazz.getComponentType())); } return ary; } if (List.class.isAssignableFrom(clazz)) { if (tt == null) // 没有泛型信息? 那只好直接返回了 return list; Mirror me = Mirror.me(clazz); List re = null; if (clazz.isInterface()) re = new LinkedList(); else re = (List) me.born(); for (Object object : list) { re.add(convert(tt, object)); } return re; } throw unexpectedType(List.class, clazz); }
diff --git a/src/org/sharedsolar/adapter/VendorAddCreditAdapter.java b/src/org/sharedsolar/adapter/VendorAddCreditAdapter.java index 64b2523..fc808d3 100644 --- a/src/org/sharedsolar/adapter/VendorAddCreditAdapter.java +++ b/src/org/sharedsolar/adapter/VendorAddCreditAdapter.java @@ -1,128 +1,132 @@ package org.sharedsolar.adapter; import java.util.ArrayList; import org.sharedsolar.model.CreditSummaryModel; import org.sharedsolar.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class VendorAddCreditAdapter extends ArrayAdapter<CreditSummaryModel> { private LayoutInflater mInflater; private ArrayList<CreditSummaryModel> modelList; private TextView creditAddedTV; public VendorAddCreditAdapter(Context context, int textViewResourceId, ArrayList<CreditSummaryModel> modelList, TextView creditAddedTV) { super(context, textViewResourceId); mInflater = LayoutInflater.from(context); this.modelList = modelList; this.creditAddedTV = creditAddedTV; } public int getCount() { return modelList.size(); } public CreditSummaryModel getItem(int position) { return modelList.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater .inflate(R.layout.vendor_add_credit_item, null); holder = new ViewHolder(); holder.denominationText = (TextView) convertView .findViewById(R.id.vendorAddCreditDenomination); holder.addedCountText = (TextView) convertView .findViewById(R.id.vendorAddCreditAddedCount); holder.remainCountText = (TextView) convertView .findViewById(R.id.vendorAddCreditRemainCount); holder.minusBtn = (Button) convertView .findViewById(R.id.vendorAddCreditMinusBtn); holder.plusBtn = (Button) convertView .findViewById(R.id.vendorAddCreditPlusBtn); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } CreditSummaryModel model = modelList.get(position); if (model != null) { holder.denominationText.setText(String.valueOf(model.getDenomination())); holder.addedCountText.setText("0"); holder.remainCountText.setText(String.valueOf(model.getCount())); holder.minusBtn.setEnabled(false); - if (model.getCount() == 0) holder.plusBtn.setEnabled(false); + if (model.getCount() >= 1) { + holder.plusBtn.setEnabled(true); + } else { + holder.plusBtn.setEnabled(false); + } holder.plusBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { updateCredit(v, 1); } }); holder.minusBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { updateCredit(v, -1); } }); } return convertView; } public void updateCredit(View v, int sign) { LinearLayout row = (LinearLayout) v.getParent().getParent(); TextView denominationText = (TextView) row.getChildAt(1); TextView addedCountText = (TextView) row.getChildAt(2); TextView remainCountText = (TextView) row.getChildAt(3); int denomination = Integer.parseInt(denominationText.getText().toString()); int addedCount = Integer.parseInt(addedCountText.getText().toString()); int remainCount = Integer.parseInt(remainCountText.getText().toString()); int creditAdded = Integer.parseInt(creditAddedTV.getText().toString()); // update text addedCount += sign; addedCountText.setText(String.valueOf(addedCount)); remainCount -= sign; remainCountText.setText(String.valueOf(remainCount)); creditAddedTV.setText(String.valueOf(creditAdded + sign * denomination)); // minusBtn if (sign == -1) { if (addedCount <= 0) { v.setEnabled(false); } if (remainCount >= 1) { ((Button)(((LinearLayout)v.getParent()).getChildAt(0))).setEnabled(true); } } // plusBtn if (sign == 1) { if (addedCount >= 1) { ((Button)(((LinearLayout)v.getParent()).getChildAt(1))).setEnabled(true); } if (remainCount <= 0) { v.setEnabled(false); } } } static class ViewHolder { TextView denominationText; TextView addedCountText; TextView remainCountText; Button minusBtn; Button plusBtn; } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater .inflate(R.layout.vendor_add_credit_item, null); holder = new ViewHolder(); holder.denominationText = (TextView) convertView .findViewById(R.id.vendorAddCreditDenomination); holder.addedCountText = (TextView) convertView .findViewById(R.id.vendorAddCreditAddedCount); holder.remainCountText = (TextView) convertView .findViewById(R.id.vendorAddCreditRemainCount); holder.minusBtn = (Button) convertView .findViewById(R.id.vendorAddCreditMinusBtn); holder.plusBtn = (Button) convertView .findViewById(R.id.vendorAddCreditPlusBtn); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } CreditSummaryModel model = modelList.get(position); if (model != null) { holder.denominationText.setText(String.valueOf(model.getDenomination())); holder.addedCountText.setText("0"); holder.remainCountText.setText(String.valueOf(model.getCount())); holder.minusBtn.setEnabled(false); if (model.getCount() == 0) holder.plusBtn.setEnabled(false); holder.plusBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { updateCredit(v, 1); } }); holder.minusBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { updateCredit(v, -1); } }); } return convertView; }
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater .inflate(R.layout.vendor_add_credit_item, null); holder = new ViewHolder(); holder.denominationText = (TextView) convertView .findViewById(R.id.vendorAddCreditDenomination); holder.addedCountText = (TextView) convertView .findViewById(R.id.vendorAddCreditAddedCount); holder.remainCountText = (TextView) convertView .findViewById(R.id.vendorAddCreditRemainCount); holder.minusBtn = (Button) convertView .findViewById(R.id.vendorAddCreditMinusBtn); holder.plusBtn = (Button) convertView .findViewById(R.id.vendorAddCreditPlusBtn); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } CreditSummaryModel model = modelList.get(position); if (model != null) { holder.denominationText.setText(String.valueOf(model.getDenomination())); holder.addedCountText.setText("0"); holder.remainCountText.setText(String.valueOf(model.getCount())); holder.minusBtn.setEnabled(false); if (model.getCount() >= 1) { holder.plusBtn.setEnabled(true); } else { holder.plusBtn.setEnabled(false); } holder.plusBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { updateCredit(v, 1); } }); holder.minusBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { updateCredit(v, -1); } }); } return convertView; }
diff --git a/src/main/javassist/bytecode/ClassFile.java b/src/main/javassist/bytecode/ClassFile.java index f03537c..6c90b35 100644 --- a/src/main/javassist/bytecode/ClassFile.java +++ b/src/main/javassist/bytecode/ClassFile.java @@ -1,842 +1,841 @@ /* * Javassist, a Java-bytecode translator toolkit. * Copyright (C) 1999-2007 Shigeru Chiba. All Rights Reserved. * * 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. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later. * * 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. */ package javassist.bytecode; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import javassist.CannotCompileException; /** * <code>ClassFile</code> represents a Java <code>.class</code> file, which * consists of a constant pool, methods, fields, and attributes. * * @see javassist.CtClass#getClassFile() */ public final class ClassFile { int major, minor; // version number ConstPool constPool; int thisClass; int accessFlags; int superClass; int[] interfaces; ArrayList fields; ArrayList methods; LinkedList attributes; String thisclassname; // not JVM-internal name String[] cachedInterfaces; String cachedSuperclass; /** * The major version number of class files * for JDK 1.1. */ public static final int JAVA_1 = 45; /** * The major version number of class files * for JDK 1.2. */ public static final int JAVA_2 = 46; /** * The major version number of class files * for JDK 1.3. */ public static final int JAVA_3 = 47; /** * The major version number of class files * for JDK 1.4. */ public static final int JAVA_4 = 48; /** * The major version number of class files * for JDK 1.5. */ public static final int JAVA_5 = 49; /** * The major version number of class files * for JDK 1.6. */ public static final int JAVA_6 = 50; /** * The major version number of class files created * from scratch. The default value is 47 (JDK 1.3) * or 49 (JDK 1.5) if the JVM supports <code>java.lang.StringBuilder</code>. */ public static int MAJOR_VERSION = JAVA_3; static { try { Class.forName("java.lang.StringBuilder"); MAJOR_VERSION = JAVA_5; } catch (Throwable t) {} } /** * Constructs a class file from a byte stream. */ public ClassFile(DataInputStream in) throws IOException { read(in); } /** * Constructs a class file including no members. * * @param isInterface * true if this is an interface. false if this is a class. * @param classname * a fully-qualified class name * @param superclass * a fully-qualified super class name */ public ClassFile(boolean isInterface, String classname, String superclass) { major = MAJOR_VERSION; minor = 0; // JDK 1.3 or later constPool = new ConstPool(classname); thisClass = constPool.getThisClassInfo(); if (isInterface) accessFlags = AccessFlag.INTERFACE | AccessFlag.ABSTRACT; else accessFlags = AccessFlag.SUPER; initSuperclass(superclass); interfaces = null; fields = new ArrayList(); methods = new ArrayList(); thisclassname = classname; attributes = new LinkedList(); attributes.add(new SourceFileAttribute(constPool, getSourcefileName(thisclassname))); } private void initSuperclass(String superclass) { if (superclass != null) { this.superClass = constPool.addClassInfo(superclass); cachedSuperclass = superclass; } else { this.superClass = constPool.addClassInfo("java.lang.Object"); cachedSuperclass = "java.lang.Object"; } } private static String getSourcefileName(String qname) { int index = qname.lastIndexOf('.'); if (index >= 0) qname = qname.substring(index + 1); return qname + ".java"; } /** * Eliminates dead constant pool items. If a method or a field is removed, * the constant pool items used by that method/field become dead items. This * method recreates a constant pool. */ public void compact() { ConstPool cp = compact0(); ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); minfo.compact(cp); } list = fields; n = list.size(); for (int i = 0; i < n; ++i) { FieldInfo finfo = (FieldInfo)list.get(i); finfo.compact(cp); } attributes = AttributeInfo.copyAll(attributes, cp); constPool = cp; } private ConstPool compact0() { ConstPool cp = new ConstPool(thisclassname); thisClass = cp.getThisClassInfo(); String sc = getSuperclass(); if (sc != null) superClass = cp.addClassInfo(getSuperclass()); if (interfaces != null) { int n = interfaces.length; for (int i = 0; i < n; ++i) interfaces[i] = cp.addClassInfo(constPool.getClassInfo(interfaces[i])); } return cp; } /** * Discards all attributes, associated with both the class file and the * members such as a code attribute and exceptions attribute. The unused * constant pool entries are also discarded (a new packed constant pool is * constructed). */ public void prune() { ConstPool cp = compact0(); LinkedList newAttributes = new LinkedList(); AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag); if (invisibleAnnotations != null) { invisibleAnnotations = invisibleAnnotations.copy(cp, null); newAttributes.add(invisibleAnnotations); } AttributeInfo visibleAnnotations = getAttribute(AnnotationsAttribute.visibleTag); if (visibleAnnotations != null) { visibleAnnotations = visibleAnnotations.copy(cp, null); newAttributes.add(visibleAnnotations); } AttributeInfo signature = getAttribute(SignatureAttribute.tag); if (signature != null) { signature = signature.copy(cp, null); newAttributes.add(signature); } ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); minfo.prune(cp); } list = fields; n = list.size(); for (int i = 0; i < n; ++i) { FieldInfo finfo = (FieldInfo)list.get(i); finfo.prune(cp); } attributes = newAttributes; - cp.prune(); constPool = cp; } /** * Returns a constant pool table. */ public ConstPool getConstPool() { return constPool; } /** * Returns true if this is an interface. */ public boolean isInterface() { return (accessFlags & AccessFlag.INTERFACE) != 0; } /** * Returns true if this is a final class or interface. */ public boolean isFinal() { return (accessFlags & AccessFlag.FINAL) != 0; } /** * Returns true if this is an abstract class or an interface. */ public boolean isAbstract() { return (accessFlags & AccessFlag.ABSTRACT) != 0; } /** * Returns access flags. * * @see javassist.bytecode.AccessFlag */ public int getAccessFlags() { return accessFlags; } /** * Changes access flags. * * @see javassist.bytecode.AccessFlag */ public void setAccessFlags(int acc) { if ((acc & AccessFlag.INTERFACE) == 0) acc |= AccessFlag.SUPER; accessFlags = acc; } /** * Returns access and property flags of this nested class. * This method returns -1 if the class is not a nested class. * * <p>The returned value is obtained from <code>inner_class_access_flags</code> * of the entry representing this nested class itself * in <code>InnerClasses_attribute</code>>. */ public int getInnerAccessFlags() { InnerClassesAttribute ica = (InnerClassesAttribute)getAttribute(InnerClassesAttribute.tag); if (ica == null) return -1; String name = getName(); int n = ica.tableLength(); for (int i = 0; i < n; ++i) if (name.equals(ica.innerClass(i))) return ica.accessFlags(i); return -1; } /** * Returns the class name. */ public String getName() { return thisclassname; } /** * Sets the class name. This method substitutes the new name for all * occurrences of the old class name in the class file. */ public void setName(String name) { renameClass(thisclassname, name); } /** * Returns the super class name. */ public String getSuperclass() { if (cachedSuperclass == null) cachedSuperclass = constPool.getClassInfo(superClass); return cachedSuperclass; } /** * Returns the index of the constant pool entry representing the super * class. */ public int getSuperclassId() { return superClass; } /** * Sets the super class. * * <p> * The new super class should inherit from the old super class. * This method modifies constructors so that they call constructors declared * in the new super class. */ public void setSuperclass(String superclass) throws CannotCompileException { if (superclass == null) superclass = "java.lang.Object"; try { this.superClass = constPool.addClassInfo(superclass); ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); minfo.setSuperclass(superclass); } } catch (BadBytecode e) { throw new CannotCompileException(e); } cachedSuperclass = superclass; } /** * Replaces all occurrences of a class name in the class file. * * <p> * If class X is substituted for class Y in the class file, X and Y must * have the same signature. If Y provides a method m(), X must provide it * even if X inherits m() from the super class. If this fact is not * guaranteed, the bytecode verifier may cause an error. * * @param oldname * the replaced class name * @param newname * the substituted class name */ public final void renameClass(String oldname, String newname) { ArrayList list; int n; if (oldname.equals(newname)) return; if (oldname.equals(thisclassname)) thisclassname = newname; oldname = Descriptor.toJvmName(oldname); newname = Descriptor.toJvmName(newname); constPool.renameClass(oldname, newname); AttributeInfo.renameClass(attributes, oldname, newname); list = methods; n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); String desc = minfo.getDescriptor(); minfo.setDescriptor(Descriptor.rename(desc, oldname, newname)); AttributeInfo.renameClass(minfo.getAttributes(), oldname, newname); } list = fields; n = list.size(); for (int i = 0; i < n; ++i) { FieldInfo finfo = (FieldInfo)list.get(i); String desc = finfo.getDescriptor(); finfo.setDescriptor(Descriptor.rename(desc, oldname, newname)); AttributeInfo.renameClass(finfo.getAttributes(), oldname, newname); } } /** * Replaces all occurrences of several class names in the class file. * * @param classnames * specifies which class name is replaced with which new name. * Class names must be described with the JVM-internal * representation like <code>java/lang/Object</code>. * @see #renameClass(String,String) */ public final void renameClass(Map classnames) { String jvmNewThisName = (String)classnames.get(Descriptor .toJvmName(thisclassname)); if (jvmNewThisName != null) thisclassname = Descriptor.toJavaName(jvmNewThisName); constPool.renameClass(classnames); AttributeInfo.renameClass(attributes, classnames); ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); String desc = minfo.getDescriptor(); minfo.setDescriptor(Descriptor.rename(desc, classnames)); AttributeInfo.renameClass(minfo.getAttributes(), classnames); } list = fields; n = list.size(); for (int i = 0; i < n; ++i) { FieldInfo finfo = (FieldInfo)list.get(i); String desc = finfo.getDescriptor(); finfo.setDescriptor(Descriptor.rename(desc, classnames)); AttributeInfo.renameClass(finfo.getAttributes(), classnames); } } /** * Returns the names of the interfaces implemented by the class. * The returned array is read only. */ public String[] getInterfaces() { if (cachedInterfaces != null) return cachedInterfaces; String[] rtn = null; if (interfaces == null) rtn = new String[0]; else { int n = interfaces.length; String[] list = new String[n]; for (int i = 0; i < n; ++i) list[i] = constPool.getClassInfo(interfaces[i]); rtn = list; } cachedInterfaces = rtn; return rtn; } /** * Sets the interfaces. * * @param nameList * the names of the interfaces. */ public void setInterfaces(String[] nameList) { cachedInterfaces = null; if (nameList != null) { int n = nameList.length; interfaces = new int[n]; for (int i = 0; i < n; ++i) interfaces[i] = constPool.addClassInfo(nameList[i]); } } /** * Appends an interface to the interfaces implemented by the class. */ public void addInterface(String name) { cachedInterfaces = null; int info = constPool.addClassInfo(name); if (interfaces == null) { interfaces = new int[1]; interfaces[0] = info; } else { int n = interfaces.length; int[] newarray = new int[n + 1]; System.arraycopy(interfaces, 0, newarray, 0, n); newarray[n] = info; interfaces = newarray; } } /** * Returns all the fields declared in the class. * * @return a list of <code>FieldInfo</code>. * @see FieldInfo */ public List getFields() { return fields; } /** * Appends a field to the class. * * @throws DuplicateMemberException when the field is already included. */ public void addField(FieldInfo finfo) throws DuplicateMemberException { testExistingField(finfo.getName(), finfo.getDescriptor()); fields.add(finfo); } private void addField0(FieldInfo finfo) { fields.add(finfo); } private void testExistingField(String name, String descriptor) throws DuplicateMemberException { ListIterator it = fields.listIterator(0); while (it.hasNext()) { FieldInfo minfo = (FieldInfo)it.next(); if (minfo.getName().equals(name)) throw new DuplicateMemberException("duplicate field: " + name); } } /** * Returns all the methods declared in the class. * * @return a list of <code>MethodInfo</code>. * @see MethodInfo */ public List getMethods() { return methods; } /** * Returns the method with the specified name. If there are multiple methods * with that name, this method returns one of them. * * @return null if no such a method is found. */ public MethodInfo getMethod(String name) { ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); if (minfo.getName().equals(name)) return minfo; } return null; } /** * Returns a static initializer (class initializer), or null if it does not * exist. */ public MethodInfo getStaticInitializer() { return getMethod(MethodInfo.nameClinit); } /** * Appends a method to the class. * If there is a bridge method with the same name and signature, * then the bridge method is removed before a new method is added. * * @throws DuplicateMemberException when the method is already included. */ public void addMethod(MethodInfo minfo) throws DuplicateMemberException { testExistingMethod(minfo); methods.add(minfo); } private void addMethod0(MethodInfo minfo) { methods.add(minfo); } private void testExistingMethod(MethodInfo newMinfo) throws DuplicateMemberException { String name = newMinfo.getName(); String descriptor = newMinfo.getDescriptor(); ListIterator it = methods.listIterator(0); while (it.hasNext()) if (isDuplicated(newMinfo, name, descriptor, (MethodInfo)it.next(), it)) throw new DuplicateMemberException("duplicate method: " + name + " in " + this.getName()); } private static boolean isDuplicated(MethodInfo newMethod, String newName, String newDesc, MethodInfo minfo, ListIterator it) { if (!minfo.getName().equals(newName)) return false; String desc = minfo.getDescriptor(); if (!Descriptor.eqParamTypes(desc, newDesc)) return false; if (desc.equals(newDesc)) { if (notBridgeMethod(minfo)) return true; else { it.remove(); return false; } } else return notBridgeMethod(minfo) && notBridgeMethod(newMethod); } /* For a bridge method, see Sec. 15.12.4.5 of JLS 3rd Ed. */ private static boolean notBridgeMethod(MethodInfo minfo) { return (minfo.getAccessFlags() & AccessFlag.BRIDGE) == 0; } /** * Returns all the attributes. The returned <code>List</code> object * is shared with this object. If you add a new attribute to the list, * the attribute is also added to the classs file represented by this * object. If you remove an attribute from the list, it is also removed * from the class file. * * @return a list of <code>AttributeInfo</code> objects. * @see AttributeInfo */ public List getAttributes() { return attributes; } /** * Returns the attribute with the specified name. If there are multiple * attributes with that name, this method returns either of them. It * returns null if the specified attributed is not found. * * @param name attribute name * @see #getAttributes() */ public AttributeInfo getAttribute(String name) { LinkedList list = attributes; int n = list.size(); for (int i = 0; i < n; ++i) { AttributeInfo ai = (AttributeInfo)list.get(i); if (ai.getName().equals(name)) return ai; } return null; } /** * Appends an attribute. If there is already an attribute with the same * name, the new one substitutes for it. * * @see #getAttributes() */ public void addAttribute(AttributeInfo info) { AttributeInfo.remove(attributes, info.getName()); attributes.add(info); } /** * Returns the source file containing this class. * * @return null if this information is not available. */ public String getSourceFile() { SourceFileAttribute sf = (SourceFileAttribute)getAttribute(SourceFileAttribute.tag); if (sf == null) return null; else return sf.getFileName(); } private void read(DataInputStream in) throws IOException { int i, n; int magic = in.readInt(); if (magic != 0xCAFEBABE) throw new IOException("bad magic number: " + Integer.toHexString(magic)); minor = in.readUnsignedShort(); major = in.readUnsignedShort(); constPool = new ConstPool(in); accessFlags = in.readUnsignedShort(); thisClass = in.readUnsignedShort(); constPool.setThisClassInfo(thisClass); superClass = in.readUnsignedShort(); n = in.readUnsignedShort(); if (n == 0) interfaces = null; else { interfaces = new int[n]; for (i = 0; i < n; ++i) interfaces[i] = in.readUnsignedShort(); } ConstPool cp = constPool; n = in.readUnsignedShort(); fields = new ArrayList(); for (i = 0; i < n; ++i) addField0(new FieldInfo(cp, in)); n = in.readUnsignedShort(); methods = new ArrayList(); for (i = 0; i < n; ++i) addMethod0(new MethodInfo(cp, in)); attributes = new LinkedList(); n = in.readUnsignedShort(); for (i = 0; i < n; ++i) addAttribute(AttributeInfo.read(cp, in)); thisclassname = constPool.getClassInfo(thisClass); } /** * Writes a class file represened by this object into an output stream. */ public void write(DataOutputStream out) throws IOException { int i, n; out.writeInt(0xCAFEBABE); // magic out.writeShort(minor); // minor version out.writeShort(major); // major version constPool.write(out); // constant pool out.writeShort(accessFlags); out.writeShort(thisClass); out.writeShort(superClass); if (interfaces == null) n = 0; else n = interfaces.length; out.writeShort(n); for (i = 0; i < n; ++i) out.writeShort(interfaces[i]); ArrayList list = fields; n = list.size(); out.writeShort(n); for (i = 0; i < n; ++i) { FieldInfo finfo = (FieldInfo)list.get(i); finfo.write(out); } list = methods; n = list.size(); out.writeShort(n); for (i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); minfo.write(out); } out.writeShort(attributes.size()); AttributeInfo.writeAll(attributes, out); } /** * Get the Major version. * * @return the major version */ public int getMajorVersion() { return major; } /** * Set the major version. * * @param major * the major version */ public void setMajorVersion(int major) { this.major = major; } /** * Get the minor version. * * @return the minor version */ public int getMinorVersion() { return minor; } /** * Set the minor version. * * @param minor * the minor version */ public void setMinorVersion(int minor) { this.minor = minor; } /** * Sets the major and minor version to Java 5. * * If the major version is older than 49, Java 5 * extensions such as annotations are ignored * by the JVM. */ public void setVersionToJava5() { this.major = 49; this.minor = 0; } }
true
true
public void prune() { ConstPool cp = compact0(); LinkedList newAttributes = new LinkedList(); AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag); if (invisibleAnnotations != null) { invisibleAnnotations = invisibleAnnotations.copy(cp, null); newAttributes.add(invisibleAnnotations); } AttributeInfo visibleAnnotations = getAttribute(AnnotationsAttribute.visibleTag); if (visibleAnnotations != null) { visibleAnnotations = visibleAnnotations.copy(cp, null); newAttributes.add(visibleAnnotations); } AttributeInfo signature = getAttribute(SignatureAttribute.tag); if (signature != null) { signature = signature.copy(cp, null); newAttributes.add(signature); } ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); minfo.prune(cp); } list = fields; n = list.size(); for (int i = 0; i < n; ++i) { FieldInfo finfo = (FieldInfo)list.get(i); finfo.prune(cp); } attributes = newAttributes; cp.prune(); constPool = cp; }
public void prune() { ConstPool cp = compact0(); LinkedList newAttributes = new LinkedList(); AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag); if (invisibleAnnotations != null) { invisibleAnnotations = invisibleAnnotations.copy(cp, null); newAttributes.add(invisibleAnnotations); } AttributeInfo visibleAnnotations = getAttribute(AnnotationsAttribute.visibleTag); if (visibleAnnotations != null) { visibleAnnotations = visibleAnnotations.copy(cp, null); newAttributes.add(visibleAnnotations); } AttributeInfo signature = getAttribute(SignatureAttribute.tag); if (signature != null) { signature = signature.copy(cp, null); newAttributes.add(signature); } ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); minfo.prune(cp); } list = fields; n = list.size(); for (int i = 0; i < n; ++i) { FieldInfo finfo = (FieldInfo)list.get(i); finfo.prune(cp); } attributes = newAttributes; constPool = cp; }
diff --git a/ardor3d-ui/src/main/java/com/ardor3d/extension/ui/UIFrameStatusBar.java b/ardor3d-ui/src/main/java/com/ardor3d/extension/ui/UIFrameStatusBar.java index 7fe4ae9..daa8307 100755 --- a/ardor3d-ui/src/main/java/com/ardor3d/extension/ui/UIFrameStatusBar.java +++ b/ardor3d-ui/src/main/java/com/ardor3d/extension/ui/UIFrameStatusBar.java @@ -1,185 +1,189 @@ /** * Copyright (c) 2008-2009 Ardor Labs, Inc. * * This file is part of Ardor3D. * * Ardor3D is free software: you can redistribute it and/or modify it * under the terms of its license which may be found in the accompanying * LICENSE file or at <http://www.ardor3d.com/LICENSE>. */ package com.ardor3d.extension.ui; import com.ardor3d.extension.ui.event.DragListener; import com.ardor3d.extension.ui.layout.BorderLayout; import com.ardor3d.extension.ui.layout.BorderLayoutData; import com.ardor3d.input.InputState; import com.ardor3d.math.Vector3; /** * This panel extension defines a frame status bar (used at the bottom of a frame) with a text label and resize handle. */ public class UIFrameStatusBar extends UIPanel { /** Our text label. */ private final UILabel _statusLabel; /** Resize handle, used to drag out this content's size when the frame is set as resizeable. */ private final FrameResizeButton _resizeButton; /** A drag listener used to perform resize operations on this frame. */ private final ResizeListener _resizeListener = new ResizeListener(); /** * Construct a new status bar */ public UIFrameStatusBar() { super(new BorderLayout()); _statusLabel = new UILabel(""); _statusLabel.setLayoutData(BorderLayoutData.CENTER); add(_statusLabel); _resizeButton = new FrameResizeButton(); _resizeButton.setLayoutData(BorderLayoutData.EAST); add(_resizeButton); } public FrameResizeButton getResizeButton() { return _resizeButton; } public UILabel getStatusLabel() { return _statusLabel; } @Override public void attachedToHud() { super.attachedToHud(); final UIHud hud = getHud(); if (hud != null) { hud.addDragListener(_resizeListener); } } @Override public void detachedFromHud() { super.detachedFromHud(); final UIHud hud = getHud(); if (hud != null) { hud.removeDragListener(_resizeListener); } } private final class ResizeListener implements DragListener { private int _oldX = 0; private int _oldY = 0; public void startDrag(final int mouseX, final int mouseY) { final Vector3 vec = Vector3.fetchTempInstance(); vec.set(mouseX, mouseY, 0); getWorldTransform().applyInverse(vec); _oldX = Math.round(vec.getXf()); _oldY = Math.round(vec.getYf()); Vector3.releaseTempInstance(vec); } public void drag(final int mouseX, final int mouseY) { resizeFrameByPosition(mouseX, mouseY); } public void endDrag(final UIComponent component, final int mouseX, final int mouseY) { resizeFrameByPosition(mouseX, mouseY); } private void resizeFrameByPosition(final int mouseX, final int mouseY) { final Vector3 vec = Vector3.fetchTempInstance(); vec.set(mouseX, mouseY, 0); getWorldTransform().applyInverse(vec); final int x = Math.round(vec.getXf()); final int y = Math.round(vec.getYf()); final UIFrame frame = UIFrame.findParentFrame(UIFrameStatusBar.this); // Set the new width to the current width + the change in mouse x position. int newWidth = frame.getLocalComponentWidth() + x - _oldX; if (newWidth < UIFrame.MIN_FRAME_WIDTH) { // don't let us get smaller than min size newWidth = UIFrame.MIN_FRAME_WIDTH; } // Set the new height to the current width + the change in mouse y position. int heightDif = y - _oldY; int newHeight = frame.getLocalComponentHeight() + _oldY - y; if (newHeight < UIFrame.MIN_FRAME_HEIGHT) { - // don't let us get smaller than min size + // don't let us get smaller than absolute min size newHeight = UIFrame.MIN_FRAME_HEIGHT; heightDif = frame.getLocalComponentHeight() - newHeight; + } else if (newHeight < frame.getMinimumLocalComponentHeight()) { + // don't let us get smaller than frame min size + newHeight = frame.getMinimumLocalComponentHeight(); + heightDif = frame.getLocalComponentHeight() - newHeight; } frame.setLocalComponentSize(newWidth, newHeight); vec.set(0, heightDif, 0); getWorldTransform().applyForwardVector(vec); frame.addTranslation(vec); Vector3.releaseTempInstance(vec); frame.layout(); _oldX = x; _oldY = y - heightDif; } public boolean isDragHandle(final UIComponent component, final int mouseX, final int mouseY) { return component == _resizeButton; } } class FrameResizeButton extends UIButton { public FrameResizeButton() { super("..."); _pressedState = new MyPressedState(); _defaultState = new MyDefaultState(); _mouseOverState = new MyMouseOverState(); switchState(_defaultState); } @Override protected void applySkin() { ; // keep this from happening by default } class MyPressedState extends UIButton.PressedState { @Override public void mouseDeparted(final int mouseX, final int mouseY, final InputState state) { super.mouseDeparted(mouseX, mouseY, state); // TODO: Reset mouse cursor. } } class MyDefaultState extends UIButton.DefaultState { @Override public void mouseEntered(final int mouseX, final int mouseY, final InputState state) { super.mouseEntered(mouseX, mouseY, state); // TODO: Set mouse cursor to resize. } @Override public void mouseDeparted(final int mouseX, final int mouseY, final InputState state) { super.mouseDeparted(mouseX, mouseY, state); // TODO: Reset mouse cursor. } } class MyMouseOverState extends UIButton.MouseOverState { @Override public void mouseDeparted(final int mouseX, final int mouseY, final InputState state) { super.mouseDeparted(mouseX, mouseY, state); // TODO: Reset mouse cursor. } } } }
false
true
private void resizeFrameByPosition(final int mouseX, final int mouseY) { final Vector3 vec = Vector3.fetchTempInstance(); vec.set(mouseX, mouseY, 0); getWorldTransform().applyInverse(vec); final int x = Math.round(vec.getXf()); final int y = Math.round(vec.getYf()); final UIFrame frame = UIFrame.findParentFrame(UIFrameStatusBar.this); // Set the new width to the current width + the change in mouse x position. int newWidth = frame.getLocalComponentWidth() + x - _oldX; if (newWidth < UIFrame.MIN_FRAME_WIDTH) { // don't let us get smaller than min size newWidth = UIFrame.MIN_FRAME_WIDTH; } // Set the new height to the current width + the change in mouse y position. int heightDif = y - _oldY; int newHeight = frame.getLocalComponentHeight() + _oldY - y; if (newHeight < UIFrame.MIN_FRAME_HEIGHT) { // don't let us get smaller than min size newHeight = UIFrame.MIN_FRAME_HEIGHT; heightDif = frame.getLocalComponentHeight() - newHeight; } frame.setLocalComponentSize(newWidth, newHeight); vec.set(0, heightDif, 0); getWorldTransform().applyForwardVector(vec); frame.addTranslation(vec); Vector3.releaseTempInstance(vec); frame.layout(); _oldX = x; _oldY = y - heightDif; }
private void resizeFrameByPosition(final int mouseX, final int mouseY) { final Vector3 vec = Vector3.fetchTempInstance(); vec.set(mouseX, mouseY, 0); getWorldTransform().applyInverse(vec); final int x = Math.round(vec.getXf()); final int y = Math.round(vec.getYf()); final UIFrame frame = UIFrame.findParentFrame(UIFrameStatusBar.this); // Set the new width to the current width + the change in mouse x position. int newWidth = frame.getLocalComponentWidth() + x - _oldX; if (newWidth < UIFrame.MIN_FRAME_WIDTH) { // don't let us get smaller than min size newWidth = UIFrame.MIN_FRAME_WIDTH; } // Set the new height to the current width + the change in mouse y position. int heightDif = y - _oldY; int newHeight = frame.getLocalComponentHeight() + _oldY - y; if (newHeight < UIFrame.MIN_FRAME_HEIGHT) { // don't let us get smaller than absolute min size newHeight = UIFrame.MIN_FRAME_HEIGHT; heightDif = frame.getLocalComponentHeight() - newHeight; } else if (newHeight < frame.getMinimumLocalComponentHeight()) { // don't let us get smaller than frame min size newHeight = frame.getMinimumLocalComponentHeight(); heightDif = frame.getLocalComponentHeight() - newHeight; } frame.setLocalComponentSize(newWidth, newHeight); vec.set(0, heightDif, 0); getWorldTransform().applyForwardVector(vec); frame.addTranslation(vec); Vector3.releaseTempInstance(vec); frame.layout(); _oldX = x; _oldY = y - heightDif; }
diff --git a/src/com/android/settings/TextToSpeechSettings.java b/src/com/android/settings/TextToSpeechSettings.java index 23959c87c..fa9ea583f 100644 --- a/src/com/android/settings/TextToSpeechSettings.java +++ b/src/com/android/settings/TextToSpeechSettings.java @@ -1,692 +1,714 @@ /* * Copyright (C) 2009 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.provider.Settings.Secure.TTS_USE_DEFAULTS; import static android.provider.Settings.Secure.TTS_DEFAULT_RATE; import static android.provider.Settings.Secure.TTS_DEFAULT_LANG; import static android.provider.Settings.Secure.TTS_DEFAULT_COUNTRY; import static android.provider.Settings.Secure.TTS_DEFAULT_VARIANT; import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH; import static android.provider.Settings.Secure.TTS_ENABLED_PLUGINS; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceScreen; import android.preference.CheckBoxPreference; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.speech.tts.TextToSpeech; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; public class TextToSpeechSettings extends PreferenceActivity implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener, TextToSpeech.OnInitListener { private static final String TAG = "TextToSpeechSettings"; private static final String SYSTEM_TTS = "com.svox.pico"; private static final String KEY_TTS_PLAY_EXAMPLE = "tts_play_example"; private static final String KEY_TTS_INSTALL_DATA = "tts_install_data"; private static final String KEY_TTS_USE_DEFAULT = "toggle_use_default_tts_settings"; private static final String KEY_TTS_DEFAULT_RATE = "tts_default_rate"; private static final String KEY_TTS_DEFAULT_LANG = "tts_default_lang"; private static final String KEY_TTS_DEFAULT_COUNTRY = "tts_default_country"; private static final String KEY_TTS_DEFAULT_VARIANT = "tts_default_variant"; private static final String KEY_TTS_DEFAULT_SYNTH = "tts_default_synth"; private static final String KEY_PLUGIN_ENABLED_PREFIX = "ENABLED_"; private static final String KEY_PLUGIN_SETTINGS_PREFIX = "SETTINGS_"; // TODO move default Locale values to TextToSpeech.Engine private static final String DEFAULT_LANG_VAL = "eng"; private static final String DEFAULT_COUNTRY_VAL = "USA"; private static final String DEFAULT_VARIANT_VAL = ""; private static final String LOCALE_DELIMITER = "-"; private static final String FALLBACK_TTS_DEFAULT_SYNTH = TextToSpeech.Engine.DEFAULT_SYNTH; private Preference mPlayExample = null; private Preference mInstallData = null; private CheckBoxPreference mUseDefaultPref = null; private ListPreference mDefaultRatePref = null; private ListPreference mDefaultLocPref = null; private ListPreference mDefaultSynthPref = null; private String mDefaultLanguage = null; private String mDefaultCountry = null; private String mDefaultLocVariant = null; private String mDefaultEng = ""; private int mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE; // Array of strings used to demonstrate TTS in the different languages. private String[] mDemoStrings; // Index of the current string to use for the demo. private int mDemoStringIndex = 0; private boolean mEnableDemo = false; private boolean mVoicesMissing = false; private TextToSpeech mTts = null; /** * Request code (arbitrary value) for voice data check through * startActivityForResult. */ private static final int VOICE_DATA_INTEGRITY_CHECK = 1977; private static final int GET_SAMPLE_TEXT = 1983; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.tts_settings); addEngineSpecificSettings(); mDemoStrings = getResources().getStringArray(R.array.tts_demo_strings); setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM); mEnableDemo = false; initClickers(); initDefaultSettings(); mTts = new TextToSpeech(this, this); } @Override protected void onStart() { super.onStart(); // whenever we return to this screen, we don't know the state of the // system, so we have to recheck that we can play the demo, or it must be disabled. // TODO make the TTS service listen to "changes in the system", i.e. sd card un/mount initClickers(); updateWidgetState(); checkVoiceData(); } @Override protected void onDestroy() { super.onDestroy(); if (mTts != null) { mTts.shutdown(); } } private void addEngineSpecificSettings() { PreferenceGroup enginesCategory = (PreferenceGroup) findPreference("tts_engines_section"); Intent intent = new Intent("android.intent.action.START_TTS_ENGINE"); ResolveInfo[] enginesArray = new ResolveInfo[0]; PackageManager pm = getPackageManager(); enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray); for (int i = 0; i < enginesArray.length; i++) { String prefKey = ""; final String pluginPackageName = enginesArray[i].activityInfo.packageName; if (!enginesArray[i].activityInfo.packageName.equals(SYSTEM_TTS)) { CheckBoxPreference chkbxPref = new CheckBoxPreference(this); prefKey = KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName; chkbxPref.setKey(prefKey); chkbxPref.setTitle(enginesArray[i].loadLabel(pm)); enginesCategory.addPreference(chkbxPref); } if (pluginHasSettings(pluginPackageName)) { Preference pref = new Preference(this); prefKey = KEY_PLUGIN_SETTINGS_PREFIX + pluginPackageName; pref.setKey(prefKey); pref.setTitle(enginesArray[i].loadLabel(pm)); CharSequence settingsLabel = getResources().getString( R.string.tts_engine_name_settings, enginesArray[i].loadLabel(pm)); pref.setSummary(settingsLabel); pref.setOnPreferenceClickListener(new OnPreferenceClickListener(){ public boolean onPreferenceClick(Preference preference){ Intent i = new Intent(); i.setClassName(pluginPackageName, pluginPackageName + ".EngineSettings"); startActivity(i); return true; } }); enginesCategory.addPreference(pref); } } } private boolean pluginHasSettings(String pluginPackageName) { PackageManager pm = getPackageManager(); Intent i = new Intent(); i.setClassName(pluginPackageName, pluginPackageName + ".EngineSettings"); if (pm.resolveActivity(i, PackageManager.MATCH_DEFAULT_ONLY) != null){ return true; } return false; } private void initClickers() { mPlayExample = findPreference(KEY_TTS_PLAY_EXAMPLE); mPlayExample.setOnPreferenceClickListener(this); mInstallData = findPreference(KEY_TTS_INSTALL_DATA); mInstallData.setOnPreferenceClickListener(this); } private void initDefaultSettings() { ContentResolver resolver = getContentResolver(); // Find the default TTS values in the settings, initialize and store the // settings if they are not found. // "Use Defaults" int useDefault = 0; mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT); try { useDefault = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS); } catch (SettingNotFoundException e) { // "use default" setting not found, initialize it useDefault = TextToSpeech.Engine.USE_DEFAULTS; Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, useDefault); } mUseDefaultPref.setChecked(useDefault == 1); mUseDefaultPref.setOnPreferenceChangeListener(this); // Default synthesis engine mDefaultSynthPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH); loadEngines(); mDefaultSynthPref.setOnPreferenceChangeListener(this); String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH); if (engine == null) { // TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech engine = FALLBACK_TTS_DEFAULT_SYNTH; Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine); } mDefaultEng = engine; // Default rate mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE); try { mDefaultRate = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE); } catch (SettingNotFoundException e) { // default rate setting not found, initialize it mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE; Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, mDefaultRate); } mDefaultRatePref.setValue(String.valueOf(mDefaultRate)); mDefaultRatePref.setOnPreferenceChangeListener(this); // Default language / country / variant : these three values map to a single ListPref // representing the matching Locale mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG); initDefaultLang(); mDefaultLocPref.setOnPreferenceChangeListener(this); } /** * Ask the current default engine to launch the matching CHECK_TTS_DATA activity * to check the required TTS files are properly installed. */ private void checkVoiceData() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK); } } } /** * Ask the current default engine to launch the matching INSTALL_TTS_DATA activity * so the required TTS files are properly installed. */ private void installVoiceData() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); intent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivity(intent); } } } /** * Ask the current default engine to return a string of sample text to be * spoken to the user. */ private void getSampleText() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); // TODO (clchen): Replace Intent string with the actual // Intent defined in the list of platform Intents. intent.setAction("android.speech.tts.engine.GET_SAMPLE_TEXT"); intent.putExtra("language", mDefaultLanguage); intent.putExtra("country", mDefaultCountry); intent.putExtra("variant", mDefaultLocVariant); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivityForResult(intent, GET_SAMPLE_TEXT); } } } /** * Called when the TTS engine is initialized. */ public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { Log.v(TAG, "TTS engine for settings screen initialized."); mEnableDemo = true; if (mDefaultLanguage == null) { mDefaultLanguage = Locale.getDefault().getISO3Language(); } if (mDefaultCountry == null) { mDefaultCountry = Locale.getDefault().getISO3Country(); } if (mDefaultLocVariant == null) { mDefaultLocVariant = new String(); } mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); mTts.setSpeechRate((float)(mDefaultRate/100.0f)); } else { Log.v(TAG, "TTS engine for settings screen failed to initialize successfully."); mEnableDemo = false; } updateWidgetState(); } /** * Called when voice data integrity check returns */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (data == null){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } // TODO (clchen): Add these extras to TextToSpeech.Engine ArrayList<String> available = data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES"); ArrayList<String> unavailable = data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES"); if ((available == null) || (unavailable == null)){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } if (available.size() > 0){ if (mTts == null) { mTts = new TextToSpeech(this, this); } ListPreference ttsLanguagePref = (ListPreference) findPreference("tts_default_lang"); CharSequence[] entries = new CharSequence[available.size()]; CharSequence[] entryValues = new CharSequence[available.size()]; for (int i=0; i<available.size(); i++){ String[] langCountryVariant = available.get(i).split("-"); Locale loc = null; if (langCountryVariant.length == 1){ loc = new Locale(langCountryVariant[0]); } else if (langCountryVariant.length == 2){ loc = new Locale(langCountryVariant[0], langCountryVariant[1]); } else if (langCountryVariant.length == 3){ loc = new Locale(langCountryVariant[0], langCountryVariant[1], langCountryVariant[2]); } if (loc != null){ entries[i] = loc.getDisplayName(); entryValues[i] = available.get(i); } } ttsLanguagePref.setEntries(entries); ttsLanguagePref.setEntryValues(entryValues); mEnableDemo = true; + // Make sure that the default language can be used. + int languageResult = mTts.setLanguage( + new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); + if (languageResult < TextToSpeech.LANG_AVAILABLE){ + Locale currentLocale = Locale.getDefault(); + mDefaultLanguage = currentLocale.getISO3Language(); + mDefaultCountry = currentLocale.getISO3Country(); + mDefaultLocVariant = currentLocale.getVariant(); + languageResult = mTts.setLanguage( + new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); + // If the default Locale isn't supported, just choose the first available + // language so that there is at least something. + if (languageResult < TextToSpeech.LANG_AVAILABLE){ + parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString()); + mTts.setLanguage( + new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); + } + ContentResolver resolver = getContentResolver(); + Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); + Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); + Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); + } } else { mEnableDemo = false; } if (unavailable.size() > 0){ mVoicesMissing = true; } else { mVoicesMissing = false; } updateWidgetState(); } else if (requestCode == GET_SAMPLE_TEXT) { if (resultCode == TextToSpeech.LANG_AVAILABLE) { String sample = getString(R.string.tts_demo); if ((data != null) && (data.getStringExtra("sampleText") != null)) { sample = data.getStringExtra("sampleText"); } if (mTts != null) { mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null); } } else { // TODO: Display an error here to the user. Log.e(TAG, "Did not have a sample string for the requested language"); } } } public boolean onPreferenceChange(Preference preference, Object objValue) { if (KEY_TTS_USE_DEFAULT.equals(preference.getKey())) { // "Use Defaults" int value = (Boolean)objValue ? 1 : 0; Settings.Secure.putInt(getContentResolver(), TTS_USE_DEFAULTS, value); Log.i(TAG, "TTS use default settings is "+objValue.toString()); } else if (KEY_TTS_DEFAULT_RATE.equals(preference.getKey())) { // Default rate mDefaultRate = Integer.parseInt((String) objValue); try { Settings.Secure.putInt(getContentResolver(), TTS_DEFAULT_RATE, mDefaultRate); if (mTts != null) { mTts.setSpeechRate((float)(mDefaultRate/100.0f)); } Log.i(TAG, "TTS default rate is " + mDefaultRate); } catch (NumberFormatException e) { Log.e(TAG, "could not persist default TTS rate setting", e); } } else if (KEY_TTS_DEFAULT_LANG.equals(preference.getKey())) { // Default locale ContentResolver resolver = getContentResolver(); parseLocaleInfo((String) objValue); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); Log.v(TAG, "TTS default lang/country/variant set to " + mDefaultLanguage + "/" + mDefaultCountry + "/" + mDefaultLocVariant); if (mTts != null) { mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } int newIndex = mDefaultLocPref.findIndexOfValue((String)objValue); Log.v("Settings", " selected is " + newIndex); mDemoStringIndex = newIndex > -1 ? newIndex : 0; } else if (KEY_TTS_DEFAULT_SYNTH.equals(preference.getKey())) { mDefaultEng = objValue.toString(); Settings.Secure.putString(getContentResolver(), TTS_DEFAULT_SYNTH, mDefaultEng); if (mTts != null) { mTts.setEngineByPackageName(mDefaultEng); mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); checkVoiceData(); } Log.v("Settings", "The default synth is: " + objValue.toString()); } return true; } /** * Called when mPlayExample or mInstallData is clicked */ public boolean onPreferenceClick(Preference preference) { if (preference == mPlayExample) { // Get the sample text from the TTS engine; onActivityResult will do // the actual speaking getSampleText(); return true; } if (preference == mInstallData) { installVoiceData(); // quit this activity so it needs to be restarted after installation of the voice data finish(); return true; } return false; } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (Utils.isMonkeyRunning()) { return false; } if (preference instanceof CheckBoxPreference) { final CheckBoxPreference chkPref = (CheckBoxPreference) preference; if (!chkPref.getKey().equals(KEY_TTS_USE_DEFAULT)){ if (chkPref.isChecked()) { chkPref.setChecked(false); AlertDialog d = (new AlertDialog.Builder(this)) .setTitle(android.R.string.dialog_alert_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(getString(R.string.tts_engine_security_warning, chkPref.getTitle())) .setCancelable(true) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { chkPref.setChecked(true); loadEngines(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .create(); d.show(); } else { loadEngines(); } return true; } } return false; } private void updateWidgetState() { mPlayExample.setEnabled(mEnableDemo); mUseDefaultPref.setEnabled(mEnableDemo); mDefaultRatePref.setEnabled(mEnableDemo); mDefaultLocPref.setEnabled(mEnableDemo); mInstallData.setEnabled(mVoicesMissing); } private void parseLocaleInfo(String locale) { StringTokenizer tokenizer = new StringTokenizer(locale, LOCALE_DELIMITER); mDefaultLanguage = ""; mDefaultCountry = ""; mDefaultLocVariant = ""; if (tokenizer.hasMoreTokens()) { mDefaultLanguage = tokenizer.nextToken().trim(); } if (tokenizer.hasMoreTokens()) { mDefaultCountry = tokenizer.nextToken().trim(); } if (tokenizer.hasMoreTokens()) { mDefaultLocVariant = tokenizer.nextToken().trim(); } } /** * Initialize the default language in the UI and in the preferences. * After this method has been invoked, the default language is a supported Locale. */ private void initDefaultLang() { // if there isn't already a default language preference if (!hasLangPref()) { // if the current Locale is supported if (isCurrentLocSupported()) { // then use the current Locale as the default language useCurrentLocAsDefault(); } else { // otherwise use a default supported Locale as the default language useSupportedLocAsDefault(); } } // Update the language preference list with the default language and the matching // demo string (at this stage there is a default language pref) ContentResolver resolver = getContentResolver(); mDefaultLanguage = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG); mDefaultCountry = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY); mDefaultLocVariant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT); // update the demo string mDemoStringIndex = mDefaultLocPref.findIndexOfValue(mDefaultLanguage + LOCALE_DELIMITER + mDefaultCountry); if (mDemoStringIndex > -1){ mDefaultLocPref.setValueIndex(mDemoStringIndex); } } /** * (helper function for initDefaultLang() ) * Returns whether there is a default language in the TTS settings. */ private boolean hasLangPref() { String language = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_LANG); return (language != null); } /** * (helper function for initDefaultLang() ) * Returns whether the current Locale is supported by this Settings screen */ private boolean isCurrentLocSupported() { String currentLocID = Locale.getDefault().getISO3Language() + LOCALE_DELIMITER + Locale.getDefault().getISO3Country(); return (mDefaultLocPref.findIndexOfValue(currentLocID) > -1); } /** * (helper function for initDefaultLang() ) * Sets the default language in TTS settings to be the current Locale. * This should only be used after checking that the current Locale is supported. */ private void useCurrentLocAsDefault() { Locale currentLocale = Locale.getDefault(); ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, currentLocale.getISO3Language()); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, currentLocale.getISO3Country()); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, currentLocale.getVariant()); } /** * (helper function for initDefaultLang() ) * Sets the default language in TTS settings to be one known to be supported */ private void useSupportedLocAsDefault() { ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, DEFAULT_LANG_VAL); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, DEFAULT_COUNTRY_VAL); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, DEFAULT_VARIANT_VAL); } private void loadEngines() { ListPreference enginesPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH); // TODO (clchen): Try to see if it is possible to be more efficient here // and not search for plugins again. Intent intent = new Intent("android.intent.action.START_TTS_ENGINE"); ResolveInfo[] enginesArray = new ResolveInfo[0]; PackageManager pm = getPackageManager(); enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray); ArrayList<CharSequence> entries = new ArrayList<CharSequence>(); ArrayList<CharSequence> values = new ArrayList<CharSequence>(); String enabledEngines = ""; for (int i = 0; i < enginesArray.length; i++) { String pluginPackageName = enginesArray[i].activityInfo.packageName; if (pluginPackageName.equals(SYSTEM_TTS)) { entries.add(enginesArray[i].loadLabel(pm)); values.add(pluginPackageName); } else { CheckBoxPreference pref = (CheckBoxPreference) findPreference( KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName); if ((pref != null) && pref.isChecked()){ entries.add(enginesArray[i].loadLabel(pm)); values.add(pluginPackageName); enabledEngines = enabledEngines + pluginPackageName + " "; } } } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_ENABLED_PLUGINS, enabledEngines); CharSequence entriesArray[] = new CharSequence[entries.size()]; CharSequence valuesArray[] = new CharSequence[values.size()]; enginesPref.setEntries(entries.toArray(entriesArray)); enginesPref.setEntryValues(values.toArray(valuesArray)); // Set the selected engine based on the saved preference String selectedEngine = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_SYNTH); int selectedEngineIndex = enginesPref.findIndexOfValue(selectedEngine); if (selectedEngineIndex == -1){ selectedEngineIndex = enginesPref.findIndexOfValue(SYSTEM_TTS); } enginesPref.setValueIndex(selectedEngineIndex); } }
true
true
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (data == null){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } // TODO (clchen): Add these extras to TextToSpeech.Engine ArrayList<String> available = data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES"); ArrayList<String> unavailable = data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES"); if ((available == null) || (unavailable == null)){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } if (available.size() > 0){ if (mTts == null) { mTts = new TextToSpeech(this, this); } ListPreference ttsLanguagePref = (ListPreference) findPreference("tts_default_lang"); CharSequence[] entries = new CharSequence[available.size()]; CharSequence[] entryValues = new CharSequence[available.size()]; for (int i=0; i<available.size(); i++){ String[] langCountryVariant = available.get(i).split("-"); Locale loc = null; if (langCountryVariant.length == 1){ loc = new Locale(langCountryVariant[0]); } else if (langCountryVariant.length == 2){ loc = new Locale(langCountryVariant[0], langCountryVariant[1]); } else if (langCountryVariant.length == 3){ loc = new Locale(langCountryVariant[0], langCountryVariant[1], langCountryVariant[2]); } if (loc != null){ entries[i] = loc.getDisplayName(); entryValues[i] = available.get(i); } } ttsLanguagePref.setEntries(entries); ttsLanguagePref.setEntryValues(entryValues); mEnableDemo = true; } else { mEnableDemo = false; } if (unavailable.size() > 0){ mVoicesMissing = true; } else { mVoicesMissing = false; } updateWidgetState(); } else if (requestCode == GET_SAMPLE_TEXT) { if (resultCode == TextToSpeech.LANG_AVAILABLE) { String sample = getString(R.string.tts_demo); if ((data != null) && (data.getStringExtra("sampleText") != null)) { sample = data.getStringExtra("sampleText"); } if (mTts != null) { mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null); } } else { // TODO: Display an error here to the user. Log.e(TAG, "Did not have a sample string for the requested language"); } } }
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (data == null){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } // TODO (clchen): Add these extras to TextToSpeech.Engine ArrayList<String> available = data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES"); ArrayList<String> unavailable = data.getStringArrayListExtra("TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES"); if ((available == null) || (unavailable == null)){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } if (available.size() > 0){ if (mTts == null) { mTts = new TextToSpeech(this, this); } ListPreference ttsLanguagePref = (ListPreference) findPreference("tts_default_lang"); CharSequence[] entries = new CharSequence[available.size()]; CharSequence[] entryValues = new CharSequence[available.size()]; for (int i=0; i<available.size(); i++){ String[] langCountryVariant = available.get(i).split("-"); Locale loc = null; if (langCountryVariant.length == 1){ loc = new Locale(langCountryVariant[0]); } else if (langCountryVariant.length == 2){ loc = new Locale(langCountryVariant[0], langCountryVariant[1]); } else if (langCountryVariant.length == 3){ loc = new Locale(langCountryVariant[0], langCountryVariant[1], langCountryVariant[2]); } if (loc != null){ entries[i] = loc.getDisplayName(); entryValues[i] = available.get(i); } } ttsLanguagePref.setEntries(entries); ttsLanguagePref.setEntryValues(entryValues); mEnableDemo = true; // Make sure that the default language can be used. int languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); if (languageResult < TextToSpeech.LANG_AVAILABLE){ Locale currentLocale = Locale.getDefault(); mDefaultLanguage = currentLocale.getISO3Language(); mDefaultCountry = currentLocale.getISO3Country(); mDefaultLocVariant = currentLocale.getVariant(); languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); // If the default Locale isn't supported, just choose the first available // language so that there is at least something. if (languageResult < TextToSpeech.LANG_AVAILABLE){ parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString()); mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); } } else { mEnableDemo = false; } if (unavailable.size() > 0){ mVoicesMissing = true; } else { mVoicesMissing = false; } updateWidgetState(); } else if (requestCode == GET_SAMPLE_TEXT) { if (resultCode == TextToSpeech.LANG_AVAILABLE) { String sample = getString(R.string.tts_demo); if ((data != null) && (data.getStringExtra("sampleText") != null)) { sample = data.getStringExtra("sampleText"); } if (mTts != null) { mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null); } } else { // TODO: Display an error here to the user. Log.e(TAG, "Did not have a sample string for the requested language"); } } }
diff --git a/swing/ui/src/main/java/org/sola/clients/swing/ui/referencedata/RequestTypePanel.java b/swing/ui/src/main/java/org/sola/clients/swing/ui/referencedata/RequestTypePanel.java index e4cfdb2a..f0f0d633 100644 --- a/swing/ui/src/main/java/org/sola/clients/swing/ui/referencedata/RequestTypePanel.java +++ b/swing/ui/src/main/java/org/sola/clients/swing/ui/referencedata/RequestTypePanel.java @@ -1,826 +1,821 @@ /** * ****************************************************************************************** * Copyright (C) 2012 - Food and Agriculture Organization of the United Nations (FAO). * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice,this list * of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice,this list * of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * 3. Neither the name of FAO nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,STRICT LIABILITY,OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ********************************************************************************************* */ package org.sola.clients.swing.ui.referencedata; import org.sola.clients.beans.AbstractCodeBean; import org.sola.clients.beans.referencedata.RequestCategoryTypeListBean; import org.sola.clients.beans.referencedata.RequestTypeBean; import org.sola.clients.beans.referencedata.TypeActionListBean; import org.sola.clients.beans.referencedata.RrrTypeListBean; import org.sola.clients.swing.ui.renderers.FormattersFactory; import org.sola.clients.swing.ui.renderers.TableCellTextAreaRenderer; import org.sola.webservices.transferobjects.referencedata.RequestTypeTO; /** * Used to manage {@link RequestTypeBean} objects. */ public class RequestTypePanel extends javax.swing.JPanel { private RequestTypeBean requestTypeBean; /** Creates new form RequestTypePanel */ public RequestTypePanel() { initComponents(); setupRequestTypeBean(null); } private RrrTypeListBean createRrrTypes() { if (rrrTypes == null) { rrrTypes = new RrrTypeListBean(true); } return rrrTypes; } private RequestCategoryTypeListBean createRequestCategoryTypes() { if (requestCategoryTypes == null) { requestCategoryTypes = new RequestCategoryTypeListBean(true); } return requestCategoryTypes; } private TypeActionListBean createTypeActions() { if (typeActions == null) { typeActions = new TypeActionListBean(true); } return typeActions; } public RequestTypeBean getRequestTypeBean() { return requestTypeBean; } public void setRequestTypeBean(RequestTypeBean requestTypeBean) { this.requestTypeBean = requestTypeBean; setupRequestTypeBean(requestTypeBean); } /** Setup reference data bean object, used to bind data on the form. */ private void setupRequestTypeBean(RequestTypeBean requestTypeBean) { txtCode.setEnabled(requestTypeBean == null); tabsPanel.setSelectedIndex(0); if (requestTypeBean != null) { this.requestTypeBean = requestTypeBean; } else { this.requestTypeBean = new RequestTypeBean(); cbxCategory.setSelectedIndex(0); cbxTypeAction.setSelectedIndex(0); cbxRrrType.setSelectedIndex(0); } descriptionValues.loadLocalizedValues(this.requestTypeBean.getDescription()); displayValues.loadLocalizedValues(this.requestTypeBean.getDisplayValue()); sourceTypeHelpers.setSourceTypeCodes(this.requestTypeBean.getSourceTypeCodes()); firePropertyChange("requestTypeBean", null, this.requestTypeBean); } /** Validates reference data object. */ public boolean validateRequestType(boolean showMessage){ return requestTypeBean.validate(showMessage).size() < 1; } /** Calls saving procedure of request type data object. */ public boolean save(boolean showMessage){ requestTypeBean.setDisplayValue(displayValues.buildMultilingualString()); requestTypeBean.setDescription(descriptionValues.buildMultilingualString()); if(validateRequestType(showMessage)){ AbstractCodeBean.saveRefData(requestTypeBean, RequestTypeTO.class); return true; }else { return false; } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); displayValues = new org.sola.clients.beans.system.LocalizedValuesListBean(); descriptionValues = new org.sola.clients.beans.system.LocalizedValuesListBean(); requestCategoryTypes = createRequestCategoryTypes(); rrrTypes = createRrrTypes(); typeActions = createTypeActions(); sourceTypeHelpers = new org.sola.clients.beans.referencedata.SourceTypeHelperListBean(); tabsPanel = new javax.swing.JTabbedPane(); jPanel19 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); txtCode = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); cbxCategory = new javax.swing.JComboBox(); jPanel4 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); txtSatus = new javax.swing.JTextField(); jPanel8 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); txtBaseFee = new javax.swing.JFormattedTextField(); jPanel9 = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); txtAreaFee = new javax.swing.JFormattedTextField(); jPanel10 = new javax.swing.JPanel(); jLabel9 = new javax.swing.JLabel(); txtValueBaseFee = new javax.swing.JFormattedTextField(); jPanel11 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); txtCompleteDays = new javax.swing.JFormattedTextField(); jPanel15 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); txtRequiredPropObjects = new javax.swing.JFormattedTextField(); jPanel1 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tableDisplayValue = new org.sola.clients.swing.common.controls.JTableWithDefaultStyles(); jPanel20 = new javax.swing.JPanel(); jPanel14 = new javax.swing.JPanel(); txtNotation = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); jPanel13 = new javax.swing.JPanel(); jLabel12 = new javax.swing.JLabel(); cbxRrrType = new javax.swing.JComboBox(); jPanel12 = new javax.swing.JPanel(); jLabel13 = new javax.swing.JLabel(); cbxTypeAction = new javax.swing.JComboBox(); jPanel17 = new javax.swing.JPanel(); jPanel16 = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); tableSources = new org.sola.clients.swing.common.controls.JTableWithDefaultStyles(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); tableDescriptions = new org.sola.clients.swing.common.controls.JTableWithDefaultStyles(); jLabel4 = new javax.swing.JLabel(); setMinimumSize(new java.awt.Dimension(604, 405)); tabsPanel.setName("tabsPanel"); // NOI18N jPanel19.setName("jPanel19"); // NOI18N jPanel5.setName("jPanel5"); // NOI18N jPanel5.setLayout(new java.awt.GridLayout(3, 3, 15, 0)); jPanel3.setName("jPanel3"); // NOI18N txtCode.setName("txtCode"); // NOI18N txtCode.setNextFocusableComponent(cbxCategory); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.code}"), txtCode, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/sola/clients/swing/ui/referencedata/Bundle"); // NOI18N jLabel1.setText(bundle.getString("RequestTypePanel.jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addContainerGap(140, Short.MAX_VALUE)) .addComponent(txtCode, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel3); jPanel7.setName("jPanel7"); // NOI18N jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel5.setText(bundle.getString("RequestTypePanel.jLabel5.text")); // NOI18N jLabel5.setName("jLabel5"); // NOI18N cbxCategory.setName("cbxCategory"); // NOI18N cbxCategory.setNextFocusableComponent(txtSatus); org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${requestCategoryTypes}"); org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, requestCategoryTypes, eLProperty, cbxCategory); bindingGroup.addBinding(jComboBoxBinding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.requestCategory}"), cbxCategory, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(jLabel5) .addContainerGap(120, Short.MAX_VALUE)) .addComponent(cbxCategory, 0, 183, Short.MAX_VALUE) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel7); jPanel4.setName("jPanel4"); // NOI18N jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel2.setText(bundle.getString("RequestTypePanel.jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N txtSatus.setName("txtSatus"); // NOI18N txtSatus.setNextFocusableComponent(txtBaseFee); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.status}"), txtSatus, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel2) .addContainerGap(138, Short.MAX_VALUE)) .addComponent(txtSatus, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtSatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel4); jPanel8.setName("jPanel8"); // NOI18N jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel7.setText(bundle.getString("RequestTypePanel.jLabel7.text")); // NOI18N jLabel7.setName("jLabel7"); // NOI18N txtBaseFee.setFormatterFactory(FormattersFactory.getInstance().getDecimalFormatterFactory()); - txtBaseFee.setText(bundle.getString("RequestTypePanel.txtBaseFee.text")); // NOI18N txtBaseFee.setName("txtBaseFee"); // NOI18N txtBaseFee.setNextFocusableComponent(txtAreaFee); - binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.baseFee}"), txtBaseFee, org.jdesktop.beansbinding.BeanProperty.create("value")); + binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.baseFee}"), txtBaseFee, org.jdesktop.beansbinding.BeanProperty.create("text"), ""); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addComponent(jLabel7) .addContainerGap(123, Short.MAX_VALUE)) .addComponent(txtBaseFee, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtBaseFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel8); jPanel9.setName("jPanel9"); // NOI18N jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel8.setText(bundle.getString("RequestTypePanel.jLabel8.text")); // NOI18N jLabel8.setName("jLabel8"); // NOI18N txtAreaFee.setFormatterFactory(FormattersFactory.getInstance().getDecimalFormatterFactory()); - txtAreaFee.setText(bundle.getString("RequestTypePanel.txtAreaFee.text")); // NOI18N txtAreaFee.setName("txtAreaFee"); // NOI18N txtAreaFee.setNextFocusableComponent(txtValueBaseFee); - binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.areaBaseFee}"), txtAreaFee, org.jdesktop.beansbinding.BeanProperty.create("value")); + binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.areaBaseFee}"), txtAreaFee, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jLabel8) .addContainerGap(97, Short.MAX_VALUE)) .addComponent(txtAreaFee, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtAreaFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel9); jPanel10.setName("jPanel10"); // NOI18N jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel9.setText(bundle.getString("RequestTypePanel.jLabel9.text")); // NOI18N jLabel9.setName("jLabel9"); // NOI18N txtValueBaseFee.setFormatterFactory(FormattersFactory.getInstance().getDecimalFormatterFactory()); - txtValueBaseFee.setText(bundle.getString("RequestTypePanel.txtValueBaseFee.text")); // NOI18N txtValueBaseFee.setName("txtValueBaseFee"); // NOI18N txtValueBaseFee.setNextFocusableComponent(txtCompleteDays); - binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.valueBaseFee}"), txtValueBaseFee, org.jdesktop.beansbinding.BeanProperty.create("value")); + binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.valueBaseFee}"), txtValueBaseFee, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10); jPanel10.setLayout(jPanel10Layout); jPanel10Layout.setHorizontalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(jLabel9) .addContainerGap(94, Short.MAX_VALUE)) .addComponent(txtValueBaseFee, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel10Layout.setVerticalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtValueBaseFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel10); jPanel11.setName("jPanel11"); // NOI18N jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel6.setText(bundle.getString("RequestTypePanel.jLabel6.text")); // NOI18N jLabel6.setName("jLabel6"); // NOI18N txtCompleteDays.setFormatterFactory(FormattersFactory.getInstance().getIntegerFormatterFactory()); - txtCompleteDays.setText(bundle.getString("RequestTypePanel.txtCompleteDays.text")); // NOI18N txtCompleteDays.setName("txtCompleteDays"); // NOI18N txtCompleteDays.setNextFocusableComponent(cbxRrrType); - binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.nrDaysToComplete}"), txtCompleteDays, org.jdesktop.beansbinding.BeanProperty.create("value")); + binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.nrDaysToComplete}"), txtCompleteDays, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11); jPanel11.setLayout(jPanel11Layout); jPanel11Layout.setHorizontalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup() .addComponent(jLabel6) .addContainerGap(59, Short.MAX_VALUE)) .addComponent(txtCompleteDays, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel11Layout.setVerticalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCompleteDays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel11); jPanel15.setName("jPanel15"); // NOI18N jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel10.setText(bundle.getString("RequestTypePanel.jLabel10.text")); // NOI18N jLabel10.setName("jLabel10"); // NOI18N txtRequiredPropObjects.setFormatterFactory(FormattersFactory.getInstance().getIntegerFormatterFactory()); - txtRequiredPropObjects.setText(bundle.getString("RequestTypePanel.txtRequiredPropObjects.text")); // NOI18N txtRequiredPropObjects.setName("txtRequiredPropObjects"); // NOI18N txtRequiredPropObjects.setNextFocusableComponent(txtNotation); - binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.nrPropertiesRequired}"), txtRequiredPropObjects, org.jdesktop.beansbinding.BeanProperty.create("value")); + binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.nrPropertiesRequired}"), txtRequiredPropObjects, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15); jPanel15.setLayout(jPanel15Layout); jPanel15Layout.setHorizontalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jLabel10) .addContainerGap(46, Short.MAX_VALUE)) .addComponent(txtRequiredPropObjects, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel15Layout.setVerticalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtRequiredPropObjects, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel15); jPanel1.setName("jPanel1"); // NOI18N jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel3.setText(bundle.getString("RequestTypePanel.jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N tableDisplayValue.setName("tableDisplayValue"); // NOI18N tableDisplayValue.setNextFocusableComponent(tableSources); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${localizedValues}"); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, displayValues, eLProperty, tableDisplayValue); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${language.displayValue}")); columnBinding.setColumnName("Language.display Value"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${localizedValue}")); columnBinding.setColumnName("Localized Value"); columnBinding.setColumnClass(String.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(tableDisplayValue); tableDisplayValue.getColumnModel().getColumn(0).setPreferredWidth(150); tableDisplayValue.getColumnModel().getColumn(0).setMaxWidth(200); tableDisplayValue.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("RequestTypePanel.tableDisplayValue.columnModel.title0_1")); // NOI18N tableDisplayValue.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("RequestTypePanel.tableDisplayValue.columnModel.title1_1")); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addContainerGap(493, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19); jPanel19.setLayout(jPanel19Layout); jPanel19Layout.setHorizontalGroup( jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel19Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)) .addContainerGap()) ); jPanel19Layout.setVerticalGroup( jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel19Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); tabsPanel.addTab(bundle.getString("RequestTypePanel.jPanel19.TabConstraints.tabTitle"), jPanel19); // NOI18N jPanel20.setName("jPanel20"); // NOI18N jPanel14.setName("jPanel14"); // NOI18N txtNotation.setName("txtNotation"); // NOI18N txtNotation.setNextFocusableComponent(tableDisplayValue); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.notationTemplate}"), txtNotation, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jLabel11.setText(bundle.getString("RequestTypePanel.jLabel11.text")); // NOI18N jLabel11.setName("jLabel11"); // NOI18N javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14); jPanel14.setLayout(jPanel14Layout); jPanel14Layout.setHorizontalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jLabel11) .addContainerGap(489, Short.MAX_VALUE)) .addComponent(txtNotation, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) ); jPanel14Layout.setVerticalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtNotation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel6.setName("jPanel6"); // NOI18N jPanel6.setLayout(new java.awt.GridLayout(1, 2, 15, 0)); jPanel13.setName("jPanel13"); // NOI18N jLabel12.setText(bundle.getString("RequestTypePanel.jLabel12.text")); // NOI18N jLabel12.setName("jLabel12"); // NOI18N cbxRrrType.setName("cbxRrrType"); // NOI18N cbxRrrType.setNextFocusableComponent(cbxTypeAction); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${rrrTypeBeanList}"); jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, rrrTypes, eLProperty, cbxRrrType); bindingGroup.addBinding(jComboBoxBinding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.rrrType}"), cbxRrrType, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13); jPanel13.setLayout(jPanel13Layout); jPanel13Layout.setHorizontalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jLabel12) .addContainerGap(238, Short.MAX_VALUE)) .addComponent(cbxRrrType, 0, 282, Short.MAX_VALUE) ); jPanel13Layout.setVerticalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxRrrType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel6.add(jPanel13); jPanel12.setName("jPanel12"); // NOI18N jLabel13.setText(bundle.getString("RequestTypePanel.jLabel13.text")); // NOI18N jLabel13.setName("jLabel13"); // NOI18N cbxTypeAction.setName("cbxTypeAction"); // NOI18N cbxTypeAction.setNextFocusableComponent(txtRequiredPropObjects); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${typeActions}"); jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, typeActions, eLProperty, cbxTypeAction); bindingGroup.addBinding(jComboBoxBinding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.typeAction}"), cbxTypeAction, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12); jPanel12.setLayout(jPanel12Layout); jPanel12Layout.setHorizontalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(jLabel13) .addContainerGap(217, Short.MAX_VALUE)) .addComponent(cbxTypeAction, 0, 282, Short.MAX_VALUE) ); jPanel12Layout.setVerticalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxTypeAction, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel6.add(jPanel12); jPanel17.setName("jPanel17"); // NOI18N jPanel17.setLayout(new java.awt.GridLayout(1, 2, 15, 0)); jPanel16.setName("jPanel16"); // NOI18N jLabel14.setText(bundle.getString("RequestTypePanel.jLabel14.text")); // NOI18N jLabel14.setName("jLabel14"); // NOI18N jScrollPane3.setName("jScrollPane3"); // NOI18N tableSources.setName("tableSources"); // NOI18N tableSources.setNextFocusableComponent(tableDescriptions); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${sourceTypeHelpers}"); jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, sourceTypeHelpers, eLProperty, tableSources); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${inList}")); columnBinding.setColumnName("In List"); columnBinding.setColumnClass(Boolean.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${sourceType.displayValue}")); columnBinding.setColumnName("Source Type.display Value"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane3.setViewportView(tableSources); tableSources.getColumnModel().getColumn(0).setPreferredWidth(30); tableSources.getColumnModel().getColumn(0).setMaxWidth(30); tableSources.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("RequestTypePanel.tableSources.columnModel.title0_1")); // NOI18N tableSources.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("RequestTypePanel.tableSources.columnModel.title1_1")); // NOI18N javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16); jPanel16.setLayout(jPanel16Layout); jPanel16Layout.setHorizontalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel16Layout.createSequentialGroup() .addComponent(jLabel14) .addContainerGap(200, Short.MAX_VALUE)) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE) ); jPanel16Layout.setVerticalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel16Layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)) ); jPanel17.add(jPanel16); jPanel2.setName("jPanel2"); // NOI18N jScrollPane2.setName("jScrollPane2"); // NOI18N tableDescriptions.setName("tableDescriptions"); // NOI18N eLProperty = org.jdesktop.beansbinding.ELProperty.create("${localizedValues}"); jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, descriptionValues, eLProperty, tableDescriptions); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${language.displayValue}")); columnBinding.setColumnName("Language.display Value"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${localizedValue}")); columnBinding.setColumnName("Localized Value"); columnBinding.setColumnClass(String.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane2.setViewportView(tableDescriptions); tableDescriptions.getColumnModel().getColumn(0).setPreferredWidth(120); tableDescriptions.getColumnModel().getColumn(0).setMaxWidth(120); tableDescriptions.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("RequestTypePanel.tableDescriptions.columnModel.title0_1")); // NOI18N tableDescriptions.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("RequestTypePanel.tableDescriptions.columnModel.title1_1")); // NOI18N tableDescriptions.getColumnModel().getColumn(1).setCellRenderer(new TableCellTextAreaRenderer()); jLabel4.setText(bundle.getString("RequestTypePanel.jLabel4.text")); // NOI18N jLabel4.setName("jLabel4"); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4) .addContainerGap(220, Short.MAX_VALUE)) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)) ); jPanel17.add(jPanel2); javax.swing.GroupLayout jPanel20Layout = new javax.swing.GroupLayout(jPanel20); jPanel20.setLayout(jPanel20Layout); jPanel20Layout.setHorizontalGroup( jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel20Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel17, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) .addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel20Layout.setVerticalGroup( jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel20Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel17, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE) .addContainerGap()) ); tabsPanel.addTab(bundle.getString("RequestTypePanel.jPanel20.TabConstraints.tabTitle"), jPanel20); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tabsPanel) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tabsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE) ); bindingGroup.bind(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox cbxCategory; private javax.swing.JComboBox cbxRrrType; private javax.swing.JComboBox cbxTypeAction; private org.sola.clients.beans.system.LocalizedValuesListBean descriptionValues; private org.sola.clients.beans.system.LocalizedValuesListBean displayValues; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel13; private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel16; private javax.swing.JPanel jPanel17; private javax.swing.JPanel jPanel19; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel20; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private org.sola.clients.beans.referencedata.RequestCategoryTypeListBean requestCategoryTypes; private org.sola.clients.beans.referencedata.RrrTypeListBean rrrTypes; private org.sola.clients.beans.referencedata.SourceTypeHelperListBean sourceTypeHelpers; private org.sola.clients.swing.common.controls.JTableWithDefaultStyles tableDescriptions; private org.sola.clients.swing.common.controls.JTableWithDefaultStyles tableDisplayValue; private org.sola.clients.swing.common.controls.JTableWithDefaultStyles tableSources; private javax.swing.JTabbedPane tabsPanel; private javax.swing.JFormattedTextField txtAreaFee; private javax.swing.JFormattedTextField txtBaseFee; private javax.swing.JTextField txtCode; private javax.swing.JFormattedTextField txtCompleteDays; private javax.swing.JTextField txtNotation; private javax.swing.JFormattedTextField txtRequiredPropObjects; private javax.swing.JTextField txtSatus; private javax.swing.JFormattedTextField txtValueBaseFee; private org.sola.clients.beans.referencedata.TypeActionListBean typeActions; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); displayValues = new org.sola.clients.beans.system.LocalizedValuesListBean(); descriptionValues = new org.sola.clients.beans.system.LocalizedValuesListBean(); requestCategoryTypes = createRequestCategoryTypes(); rrrTypes = createRrrTypes(); typeActions = createTypeActions(); sourceTypeHelpers = new org.sola.clients.beans.referencedata.SourceTypeHelperListBean(); tabsPanel = new javax.swing.JTabbedPane(); jPanel19 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); txtCode = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); cbxCategory = new javax.swing.JComboBox(); jPanel4 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); txtSatus = new javax.swing.JTextField(); jPanel8 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); txtBaseFee = new javax.swing.JFormattedTextField(); jPanel9 = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); txtAreaFee = new javax.swing.JFormattedTextField(); jPanel10 = new javax.swing.JPanel(); jLabel9 = new javax.swing.JLabel(); txtValueBaseFee = new javax.swing.JFormattedTextField(); jPanel11 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); txtCompleteDays = new javax.swing.JFormattedTextField(); jPanel15 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); txtRequiredPropObjects = new javax.swing.JFormattedTextField(); jPanel1 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tableDisplayValue = new org.sola.clients.swing.common.controls.JTableWithDefaultStyles(); jPanel20 = new javax.swing.JPanel(); jPanel14 = new javax.swing.JPanel(); txtNotation = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); jPanel13 = new javax.swing.JPanel(); jLabel12 = new javax.swing.JLabel(); cbxRrrType = new javax.swing.JComboBox(); jPanel12 = new javax.swing.JPanel(); jLabel13 = new javax.swing.JLabel(); cbxTypeAction = new javax.swing.JComboBox(); jPanel17 = new javax.swing.JPanel(); jPanel16 = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); tableSources = new org.sola.clients.swing.common.controls.JTableWithDefaultStyles(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); tableDescriptions = new org.sola.clients.swing.common.controls.JTableWithDefaultStyles(); jLabel4 = new javax.swing.JLabel(); setMinimumSize(new java.awt.Dimension(604, 405)); tabsPanel.setName("tabsPanel"); // NOI18N jPanel19.setName("jPanel19"); // NOI18N jPanel5.setName("jPanel5"); // NOI18N jPanel5.setLayout(new java.awt.GridLayout(3, 3, 15, 0)); jPanel3.setName("jPanel3"); // NOI18N txtCode.setName("txtCode"); // NOI18N txtCode.setNextFocusableComponent(cbxCategory); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.code}"), txtCode, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/sola/clients/swing/ui/referencedata/Bundle"); // NOI18N jLabel1.setText(bundle.getString("RequestTypePanel.jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addContainerGap(140, Short.MAX_VALUE)) .addComponent(txtCode, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel3); jPanel7.setName("jPanel7"); // NOI18N jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel5.setText(bundle.getString("RequestTypePanel.jLabel5.text")); // NOI18N jLabel5.setName("jLabel5"); // NOI18N cbxCategory.setName("cbxCategory"); // NOI18N cbxCategory.setNextFocusableComponent(txtSatus); org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${requestCategoryTypes}"); org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, requestCategoryTypes, eLProperty, cbxCategory); bindingGroup.addBinding(jComboBoxBinding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.requestCategory}"), cbxCategory, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(jLabel5) .addContainerGap(120, Short.MAX_VALUE)) .addComponent(cbxCategory, 0, 183, Short.MAX_VALUE) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel7); jPanel4.setName("jPanel4"); // NOI18N jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel2.setText(bundle.getString("RequestTypePanel.jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N txtSatus.setName("txtSatus"); // NOI18N txtSatus.setNextFocusableComponent(txtBaseFee); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.status}"), txtSatus, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel2) .addContainerGap(138, Short.MAX_VALUE)) .addComponent(txtSatus, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtSatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel4); jPanel8.setName("jPanel8"); // NOI18N jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel7.setText(bundle.getString("RequestTypePanel.jLabel7.text")); // NOI18N jLabel7.setName("jLabel7"); // NOI18N txtBaseFee.setFormatterFactory(FormattersFactory.getInstance().getDecimalFormatterFactory()); txtBaseFee.setText(bundle.getString("RequestTypePanel.txtBaseFee.text")); // NOI18N txtBaseFee.setName("txtBaseFee"); // NOI18N txtBaseFee.setNextFocusableComponent(txtAreaFee); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.baseFee}"), txtBaseFee, org.jdesktop.beansbinding.BeanProperty.create("value")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addComponent(jLabel7) .addContainerGap(123, Short.MAX_VALUE)) .addComponent(txtBaseFee, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtBaseFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel8); jPanel9.setName("jPanel9"); // NOI18N jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel8.setText(bundle.getString("RequestTypePanel.jLabel8.text")); // NOI18N jLabel8.setName("jLabel8"); // NOI18N txtAreaFee.setFormatterFactory(FormattersFactory.getInstance().getDecimalFormatterFactory()); txtAreaFee.setText(bundle.getString("RequestTypePanel.txtAreaFee.text")); // NOI18N txtAreaFee.setName("txtAreaFee"); // NOI18N txtAreaFee.setNextFocusableComponent(txtValueBaseFee); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.areaBaseFee}"), txtAreaFee, org.jdesktop.beansbinding.BeanProperty.create("value")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jLabel8) .addContainerGap(97, Short.MAX_VALUE)) .addComponent(txtAreaFee, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtAreaFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel9); jPanel10.setName("jPanel10"); // NOI18N jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel9.setText(bundle.getString("RequestTypePanel.jLabel9.text")); // NOI18N jLabel9.setName("jLabel9"); // NOI18N txtValueBaseFee.setFormatterFactory(FormattersFactory.getInstance().getDecimalFormatterFactory()); txtValueBaseFee.setText(bundle.getString("RequestTypePanel.txtValueBaseFee.text")); // NOI18N txtValueBaseFee.setName("txtValueBaseFee"); // NOI18N txtValueBaseFee.setNextFocusableComponent(txtCompleteDays); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.valueBaseFee}"), txtValueBaseFee, org.jdesktop.beansbinding.BeanProperty.create("value")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10); jPanel10.setLayout(jPanel10Layout); jPanel10Layout.setHorizontalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(jLabel9) .addContainerGap(94, Short.MAX_VALUE)) .addComponent(txtValueBaseFee, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel10Layout.setVerticalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtValueBaseFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel10); jPanel11.setName("jPanel11"); // NOI18N jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel6.setText(bundle.getString("RequestTypePanel.jLabel6.text")); // NOI18N jLabel6.setName("jLabel6"); // NOI18N txtCompleteDays.setFormatterFactory(FormattersFactory.getInstance().getIntegerFormatterFactory()); txtCompleteDays.setText(bundle.getString("RequestTypePanel.txtCompleteDays.text")); // NOI18N txtCompleteDays.setName("txtCompleteDays"); // NOI18N txtCompleteDays.setNextFocusableComponent(cbxRrrType); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.nrDaysToComplete}"), txtCompleteDays, org.jdesktop.beansbinding.BeanProperty.create("value")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11); jPanel11.setLayout(jPanel11Layout); jPanel11Layout.setHorizontalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup() .addComponent(jLabel6) .addContainerGap(59, Short.MAX_VALUE)) .addComponent(txtCompleteDays, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel11Layout.setVerticalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCompleteDays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel11); jPanel15.setName("jPanel15"); // NOI18N jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel10.setText(bundle.getString("RequestTypePanel.jLabel10.text")); // NOI18N jLabel10.setName("jLabel10"); // NOI18N txtRequiredPropObjects.setFormatterFactory(FormattersFactory.getInstance().getIntegerFormatterFactory()); txtRequiredPropObjects.setText(bundle.getString("RequestTypePanel.txtRequiredPropObjects.text")); // NOI18N txtRequiredPropObjects.setName("txtRequiredPropObjects"); // NOI18N txtRequiredPropObjects.setNextFocusableComponent(txtNotation); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.nrPropertiesRequired}"), txtRequiredPropObjects, org.jdesktop.beansbinding.BeanProperty.create("value")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15); jPanel15.setLayout(jPanel15Layout); jPanel15Layout.setHorizontalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jLabel10) .addContainerGap(46, Short.MAX_VALUE)) .addComponent(txtRequiredPropObjects, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel15Layout.setVerticalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtRequiredPropObjects, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel15); jPanel1.setName("jPanel1"); // NOI18N jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel3.setText(bundle.getString("RequestTypePanel.jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N tableDisplayValue.setName("tableDisplayValue"); // NOI18N tableDisplayValue.setNextFocusableComponent(tableSources); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${localizedValues}"); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, displayValues, eLProperty, tableDisplayValue); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${language.displayValue}")); columnBinding.setColumnName("Language.display Value"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${localizedValue}")); columnBinding.setColumnName("Localized Value"); columnBinding.setColumnClass(String.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(tableDisplayValue); tableDisplayValue.getColumnModel().getColumn(0).setPreferredWidth(150); tableDisplayValue.getColumnModel().getColumn(0).setMaxWidth(200); tableDisplayValue.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("RequestTypePanel.tableDisplayValue.columnModel.title0_1")); // NOI18N tableDisplayValue.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("RequestTypePanel.tableDisplayValue.columnModel.title1_1")); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addContainerGap(493, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19); jPanel19.setLayout(jPanel19Layout); jPanel19Layout.setHorizontalGroup( jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel19Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)) .addContainerGap()) ); jPanel19Layout.setVerticalGroup( jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel19Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); tabsPanel.addTab(bundle.getString("RequestTypePanel.jPanel19.TabConstraints.tabTitle"), jPanel19); // NOI18N jPanel20.setName("jPanel20"); // NOI18N jPanel14.setName("jPanel14"); // NOI18N txtNotation.setName("txtNotation"); // NOI18N txtNotation.setNextFocusableComponent(tableDisplayValue); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.notationTemplate}"), txtNotation, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jLabel11.setText(bundle.getString("RequestTypePanel.jLabel11.text")); // NOI18N jLabel11.setName("jLabel11"); // NOI18N javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14); jPanel14.setLayout(jPanel14Layout); jPanel14Layout.setHorizontalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jLabel11) .addContainerGap(489, Short.MAX_VALUE)) .addComponent(txtNotation, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) ); jPanel14Layout.setVerticalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtNotation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel6.setName("jPanel6"); // NOI18N jPanel6.setLayout(new java.awt.GridLayout(1, 2, 15, 0)); jPanel13.setName("jPanel13"); // NOI18N jLabel12.setText(bundle.getString("RequestTypePanel.jLabel12.text")); // NOI18N jLabel12.setName("jLabel12"); // NOI18N cbxRrrType.setName("cbxRrrType"); // NOI18N cbxRrrType.setNextFocusableComponent(cbxTypeAction); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${rrrTypeBeanList}"); jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, rrrTypes, eLProperty, cbxRrrType); bindingGroup.addBinding(jComboBoxBinding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.rrrType}"), cbxRrrType, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13); jPanel13.setLayout(jPanel13Layout); jPanel13Layout.setHorizontalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jLabel12) .addContainerGap(238, Short.MAX_VALUE)) .addComponent(cbxRrrType, 0, 282, Short.MAX_VALUE) ); jPanel13Layout.setVerticalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxRrrType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel6.add(jPanel13); jPanel12.setName("jPanel12"); // NOI18N jLabel13.setText(bundle.getString("RequestTypePanel.jLabel13.text")); // NOI18N jLabel13.setName("jLabel13"); // NOI18N cbxTypeAction.setName("cbxTypeAction"); // NOI18N cbxTypeAction.setNextFocusableComponent(txtRequiredPropObjects); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${typeActions}"); jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, typeActions, eLProperty, cbxTypeAction); bindingGroup.addBinding(jComboBoxBinding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.typeAction}"), cbxTypeAction, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12); jPanel12.setLayout(jPanel12Layout); jPanel12Layout.setHorizontalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(jLabel13) .addContainerGap(217, Short.MAX_VALUE)) .addComponent(cbxTypeAction, 0, 282, Short.MAX_VALUE) ); jPanel12Layout.setVerticalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxTypeAction, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel6.add(jPanel12); jPanel17.setName("jPanel17"); // NOI18N jPanel17.setLayout(new java.awt.GridLayout(1, 2, 15, 0)); jPanel16.setName("jPanel16"); // NOI18N jLabel14.setText(bundle.getString("RequestTypePanel.jLabel14.text")); // NOI18N jLabel14.setName("jLabel14"); // NOI18N jScrollPane3.setName("jScrollPane3"); // NOI18N tableSources.setName("tableSources"); // NOI18N tableSources.setNextFocusableComponent(tableDescriptions); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${sourceTypeHelpers}"); jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, sourceTypeHelpers, eLProperty, tableSources); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${inList}")); columnBinding.setColumnName("In List"); columnBinding.setColumnClass(Boolean.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${sourceType.displayValue}")); columnBinding.setColumnName("Source Type.display Value"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane3.setViewportView(tableSources); tableSources.getColumnModel().getColumn(0).setPreferredWidth(30); tableSources.getColumnModel().getColumn(0).setMaxWidth(30); tableSources.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("RequestTypePanel.tableSources.columnModel.title0_1")); // NOI18N tableSources.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("RequestTypePanel.tableSources.columnModel.title1_1")); // NOI18N javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16); jPanel16.setLayout(jPanel16Layout); jPanel16Layout.setHorizontalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel16Layout.createSequentialGroup() .addComponent(jLabel14) .addContainerGap(200, Short.MAX_VALUE)) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE) ); jPanel16Layout.setVerticalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel16Layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)) ); jPanel17.add(jPanel16); jPanel2.setName("jPanel2"); // NOI18N jScrollPane2.setName("jScrollPane2"); // NOI18N tableDescriptions.setName("tableDescriptions"); // NOI18N eLProperty = org.jdesktop.beansbinding.ELProperty.create("${localizedValues}"); jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, descriptionValues, eLProperty, tableDescriptions); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${language.displayValue}")); columnBinding.setColumnName("Language.display Value"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${localizedValue}")); columnBinding.setColumnName("Localized Value"); columnBinding.setColumnClass(String.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane2.setViewportView(tableDescriptions); tableDescriptions.getColumnModel().getColumn(0).setPreferredWidth(120); tableDescriptions.getColumnModel().getColumn(0).setMaxWidth(120); tableDescriptions.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("RequestTypePanel.tableDescriptions.columnModel.title0_1")); // NOI18N tableDescriptions.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("RequestTypePanel.tableDescriptions.columnModel.title1_1")); // NOI18N tableDescriptions.getColumnModel().getColumn(1).setCellRenderer(new TableCellTextAreaRenderer()); jLabel4.setText(bundle.getString("RequestTypePanel.jLabel4.text")); // NOI18N jLabel4.setName("jLabel4"); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4) .addContainerGap(220, Short.MAX_VALUE)) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)) ); jPanel17.add(jPanel2); javax.swing.GroupLayout jPanel20Layout = new javax.swing.GroupLayout(jPanel20); jPanel20.setLayout(jPanel20Layout); jPanel20Layout.setHorizontalGroup( jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel20Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel17, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) .addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel20Layout.setVerticalGroup( jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel20Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel17, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE) .addContainerGap()) ); tabsPanel.addTab(bundle.getString("RequestTypePanel.jPanel20.TabConstraints.tabTitle"), jPanel20); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tabsPanel) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tabsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE) ); bindingGroup.bind(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); displayValues = new org.sola.clients.beans.system.LocalizedValuesListBean(); descriptionValues = new org.sola.clients.beans.system.LocalizedValuesListBean(); requestCategoryTypes = createRequestCategoryTypes(); rrrTypes = createRrrTypes(); typeActions = createTypeActions(); sourceTypeHelpers = new org.sola.clients.beans.referencedata.SourceTypeHelperListBean(); tabsPanel = new javax.swing.JTabbedPane(); jPanel19 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); txtCode = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); cbxCategory = new javax.swing.JComboBox(); jPanel4 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); txtSatus = new javax.swing.JTextField(); jPanel8 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); txtBaseFee = new javax.swing.JFormattedTextField(); jPanel9 = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); txtAreaFee = new javax.swing.JFormattedTextField(); jPanel10 = new javax.swing.JPanel(); jLabel9 = new javax.swing.JLabel(); txtValueBaseFee = new javax.swing.JFormattedTextField(); jPanel11 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); txtCompleteDays = new javax.swing.JFormattedTextField(); jPanel15 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); txtRequiredPropObjects = new javax.swing.JFormattedTextField(); jPanel1 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tableDisplayValue = new org.sola.clients.swing.common.controls.JTableWithDefaultStyles(); jPanel20 = new javax.swing.JPanel(); jPanel14 = new javax.swing.JPanel(); txtNotation = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); jPanel13 = new javax.swing.JPanel(); jLabel12 = new javax.swing.JLabel(); cbxRrrType = new javax.swing.JComboBox(); jPanel12 = new javax.swing.JPanel(); jLabel13 = new javax.swing.JLabel(); cbxTypeAction = new javax.swing.JComboBox(); jPanel17 = new javax.swing.JPanel(); jPanel16 = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); tableSources = new org.sola.clients.swing.common.controls.JTableWithDefaultStyles(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); tableDescriptions = new org.sola.clients.swing.common.controls.JTableWithDefaultStyles(); jLabel4 = new javax.swing.JLabel(); setMinimumSize(new java.awt.Dimension(604, 405)); tabsPanel.setName("tabsPanel"); // NOI18N jPanel19.setName("jPanel19"); // NOI18N jPanel5.setName("jPanel5"); // NOI18N jPanel5.setLayout(new java.awt.GridLayout(3, 3, 15, 0)); jPanel3.setName("jPanel3"); // NOI18N txtCode.setName("txtCode"); // NOI18N txtCode.setNextFocusableComponent(cbxCategory); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.code}"), txtCode, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/sola/clients/swing/ui/referencedata/Bundle"); // NOI18N jLabel1.setText(bundle.getString("RequestTypePanel.jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addContainerGap(140, Short.MAX_VALUE)) .addComponent(txtCode, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel3); jPanel7.setName("jPanel7"); // NOI18N jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel5.setText(bundle.getString("RequestTypePanel.jLabel5.text")); // NOI18N jLabel5.setName("jLabel5"); // NOI18N cbxCategory.setName("cbxCategory"); // NOI18N cbxCategory.setNextFocusableComponent(txtSatus); org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${requestCategoryTypes}"); org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, requestCategoryTypes, eLProperty, cbxCategory); bindingGroup.addBinding(jComboBoxBinding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.requestCategory}"), cbxCategory, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(jLabel5) .addContainerGap(120, Short.MAX_VALUE)) .addComponent(cbxCategory, 0, 183, Short.MAX_VALUE) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel7); jPanel4.setName("jPanel4"); // NOI18N jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel2.setText(bundle.getString("RequestTypePanel.jLabel2.text")); // NOI18N jLabel2.setName("jLabel2"); // NOI18N txtSatus.setName("txtSatus"); // NOI18N txtSatus.setNextFocusableComponent(txtBaseFee); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.status}"), txtSatus, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel2) .addContainerGap(138, Short.MAX_VALUE)) .addComponent(txtSatus, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtSatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel4); jPanel8.setName("jPanel8"); // NOI18N jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel7.setText(bundle.getString("RequestTypePanel.jLabel7.text")); // NOI18N jLabel7.setName("jLabel7"); // NOI18N txtBaseFee.setFormatterFactory(FormattersFactory.getInstance().getDecimalFormatterFactory()); txtBaseFee.setName("txtBaseFee"); // NOI18N txtBaseFee.setNextFocusableComponent(txtAreaFee); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.baseFee}"), txtBaseFee, org.jdesktop.beansbinding.BeanProperty.create("text"), ""); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addComponent(jLabel7) .addContainerGap(123, Short.MAX_VALUE)) .addComponent(txtBaseFee, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtBaseFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel8); jPanel9.setName("jPanel9"); // NOI18N jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel8.setText(bundle.getString("RequestTypePanel.jLabel8.text")); // NOI18N jLabel8.setName("jLabel8"); // NOI18N txtAreaFee.setFormatterFactory(FormattersFactory.getInstance().getDecimalFormatterFactory()); txtAreaFee.setName("txtAreaFee"); // NOI18N txtAreaFee.setNextFocusableComponent(txtValueBaseFee); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.areaBaseFee}"), txtAreaFee, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jLabel8) .addContainerGap(97, Short.MAX_VALUE)) .addComponent(txtAreaFee, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtAreaFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel9); jPanel10.setName("jPanel10"); // NOI18N jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel9.setText(bundle.getString("RequestTypePanel.jLabel9.text")); // NOI18N jLabel9.setName("jLabel9"); // NOI18N txtValueBaseFee.setFormatterFactory(FormattersFactory.getInstance().getDecimalFormatterFactory()); txtValueBaseFee.setName("txtValueBaseFee"); // NOI18N txtValueBaseFee.setNextFocusableComponent(txtCompleteDays); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.valueBaseFee}"), txtValueBaseFee, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10); jPanel10.setLayout(jPanel10Layout); jPanel10Layout.setHorizontalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(jLabel9) .addContainerGap(94, Short.MAX_VALUE)) .addComponent(txtValueBaseFee, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel10Layout.setVerticalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtValueBaseFee, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel10); jPanel11.setName("jPanel11"); // NOI18N jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel6.setText(bundle.getString("RequestTypePanel.jLabel6.text")); // NOI18N jLabel6.setName("jLabel6"); // NOI18N txtCompleteDays.setFormatterFactory(FormattersFactory.getInstance().getIntegerFormatterFactory()); txtCompleteDays.setName("txtCompleteDays"); // NOI18N txtCompleteDays.setNextFocusableComponent(cbxRrrType); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.nrDaysToComplete}"), txtCompleteDays, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11); jPanel11.setLayout(jPanel11Layout); jPanel11Layout.setHorizontalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup() .addComponent(jLabel6) .addContainerGap(59, Short.MAX_VALUE)) .addComponent(txtCompleteDays, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel11Layout.setVerticalGroup( jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel11Layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtCompleteDays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel11); jPanel15.setName("jPanel15"); // NOI18N jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel10.setText(bundle.getString("RequestTypePanel.jLabel10.text")); // NOI18N jLabel10.setName("jLabel10"); // NOI18N txtRequiredPropObjects.setFormatterFactory(FormattersFactory.getInstance().getIntegerFormatterFactory()); txtRequiredPropObjects.setName("txtRequiredPropObjects"); // NOI18N txtRequiredPropObjects.setNextFocusableComponent(txtNotation); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.nrPropertiesRequired}"), txtRequiredPropObjects, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15); jPanel15.setLayout(jPanel15Layout); jPanel15Layout.setHorizontalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jLabel10) .addContainerGap(46, Short.MAX_VALUE)) .addComponent(txtRequiredPropObjects, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE) ); jPanel15Layout.setVerticalGroup( jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel15Layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtRequiredPropObjects, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel5.add(jPanel15); jPanel1.setName("jPanel1"); // NOI18N jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/common/red_asterisk.gif"))); // NOI18N jLabel3.setText(bundle.getString("RequestTypePanel.jLabel3.text")); // NOI18N jLabel3.setName("jLabel3"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N tableDisplayValue.setName("tableDisplayValue"); // NOI18N tableDisplayValue.setNextFocusableComponent(tableSources); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${localizedValues}"); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, displayValues, eLProperty, tableDisplayValue); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${language.displayValue}")); columnBinding.setColumnName("Language.display Value"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${localizedValue}")); columnBinding.setColumnName("Localized Value"); columnBinding.setColumnClass(String.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(tableDisplayValue); tableDisplayValue.getColumnModel().getColumn(0).setPreferredWidth(150); tableDisplayValue.getColumnModel().getColumn(0).setMaxWidth(200); tableDisplayValue.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("RequestTypePanel.tableDisplayValue.columnModel.title0_1")); // NOI18N tableDisplayValue.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("RequestTypePanel.tableDisplayValue.columnModel.title1_1")); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addContainerGap(493, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19); jPanel19.setLayout(jPanel19Layout); jPanel19Layout.setHorizontalGroup( jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel19Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)) .addContainerGap()) ); jPanel19Layout.setVerticalGroup( jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel19Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); tabsPanel.addTab(bundle.getString("RequestTypePanel.jPanel19.TabConstraints.tabTitle"), jPanel19); // NOI18N jPanel20.setName("jPanel20"); // NOI18N jPanel14.setName("jPanel14"); // NOI18N txtNotation.setName("txtNotation"); // NOI18N txtNotation.setNextFocusableComponent(tableDisplayValue); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.notationTemplate}"), txtNotation, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jLabel11.setText(bundle.getString("RequestTypePanel.jLabel11.text")); // NOI18N jLabel11.setName("jLabel11"); // NOI18N javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14); jPanel14.setLayout(jPanel14Layout); jPanel14Layout.setHorizontalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jLabel11) .addContainerGap(489, Short.MAX_VALUE)) .addComponent(txtNotation, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) ); jPanel14Layout.setVerticalGroup( jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel14Layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtNotation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel6.setName("jPanel6"); // NOI18N jPanel6.setLayout(new java.awt.GridLayout(1, 2, 15, 0)); jPanel13.setName("jPanel13"); // NOI18N jLabel12.setText(bundle.getString("RequestTypePanel.jLabel12.text")); // NOI18N jLabel12.setName("jLabel12"); // NOI18N cbxRrrType.setName("cbxRrrType"); // NOI18N cbxRrrType.setNextFocusableComponent(cbxTypeAction); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${rrrTypeBeanList}"); jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, rrrTypes, eLProperty, cbxRrrType); bindingGroup.addBinding(jComboBoxBinding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.rrrType}"), cbxRrrType, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13); jPanel13.setLayout(jPanel13Layout); jPanel13Layout.setHorizontalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jLabel12) .addContainerGap(238, Short.MAX_VALUE)) .addComponent(cbxRrrType, 0, 282, Short.MAX_VALUE) ); jPanel13Layout.setVerticalGroup( jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel13Layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxRrrType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel6.add(jPanel13); jPanel12.setName("jPanel12"); // NOI18N jLabel13.setText(bundle.getString("RequestTypePanel.jLabel13.text")); // NOI18N jLabel13.setName("jLabel13"); // NOI18N cbxTypeAction.setName("cbxTypeAction"); // NOI18N cbxTypeAction.setNextFocusableComponent(txtRequiredPropObjects); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${typeActions}"); jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, typeActions, eLProperty, cbxTypeAction); bindingGroup.addBinding(jComboBoxBinding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${requestTypeBean.typeAction}"), cbxTypeAction, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12); jPanel12.setLayout(jPanel12Layout); jPanel12Layout.setHorizontalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(jLabel13) .addContainerGap(217, Short.MAX_VALUE)) .addComponent(cbxTypeAction, 0, 282, Short.MAX_VALUE) ); jPanel12Layout.setVerticalGroup( jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel12Layout.createSequentialGroup() .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cbxTypeAction, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel6.add(jPanel12); jPanel17.setName("jPanel17"); // NOI18N jPanel17.setLayout(new java.awt.GridLayout(1, 2, 15, 0)); jPanel16.setName("jPanel16"); // NOI18N jLabel14.setText(bundle.getString("RequestTypePanel.jLabel14.text")); // NOI18N jLabel14.setName("jLabel14"); // NOI18N jScrollPane3.setName("jScrollPane3"); // NOI18N tableSources.setName("tableSources"); // NOI18N tableSources.setNextFocusableComponent(tableDescriptions); eLProperty = org.jdesktop.beansbinding.ELProperty.create("${sourceTypeHelpers}"); jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, sourceTypeHelpers, eLProperty, tableSources); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${inList}")); columnBinding.setColumnName("In List"); columnBinding.setColumnClass(Boolean.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${sourceType.displayValue}")); columnBinding.setColumnName("Source Type.display Value"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane3.setViewportView(tableSources); tableSources.getColumnModel().getColumn(0).setPreferredWidth(30); tableSources.getColumnModel().getColumn(0).setMaxWidth(30); tableSources.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("RequestTypePanel.tableSources.columnModel.title0_1")); // NOI18N tableSources.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("RequestTypePanel.tableSources.columnModel.title1_1")); // NOI18N javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16); jPanel16.setLayout(jPanel16Layout); jPanel16Layout.setHorizontalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel16Layout.createSequentialGroup() .addComponent(jLabel14) .addContainerGap(200, Short.MAX_VALUE)) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE) ); jPanel16Layout.setVerticalGroup( jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel16Layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)) ); jPanel17.add(jPanel16); jPanel2.setName("jPanel2"); // NOI18N jScrollPane2.setName("jScrollPane2"); // NOI18N tableDescriptions.setName("tableDescriptions"); // NOI18N eLProperty = org.jdesktop.beansbinding.ELProperty.create("${localizedValues}"); jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, descriptionValues, eLProperty, tableDescriptions); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${language.displayValue}")); columnBinding.setColumnName("Language.display Value"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${localizedValue}")); columnBinding.setColumnName("Localized Value"); columnBinding.setColumnClass(String.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane2.setViewportView(tableDescriptions); tableDescriptions.getColumnModel().getColumn(0).setPreferredWidth(120); tableDescriptions.getColumnModel().getColumn(0).setMaxWidth(120); tableDescriptions.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("RequestTypePanel.tableDescriptions.columnModel.title0_1")); // NOI18N tableDescriptions.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("RequestTypePanel.tableDescriptions.columnModel.title1_1")); // NOI18N tableDescriptions.getColumnModel().getColumn(1).setCellRenderer(new TableCellTextAreaRenderer()); jLabel4.setText(bundle.getString("RequestTypePanel.jLabel4.text")); // NOI18N jLabel4.setName("jLabel4"); // NOI18N javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4) .addContainerGap(220, Short.MAX_VALUE)) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)) ); jPanel17.add(jPanel2); javax.swing.GroupLayout jPanel20Layout = new javax.swing.GroupLayout(jPanel20); jPanel20.setLayout(jPanel20Layout); jPanel20Layout.setHorizontalGroup( jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel20Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel17, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) .addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel20Layout.setVerticalGroup( jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel20Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel17, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE) .addContainerGap()) ); tabsPanel.addTab(bundle.getString("RequestTypePanel.jPanel20.TabConstraints.tabTitle"), jPanel20); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tabsPanel) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tabsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE) ); bindingGroup.bind(); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/com/nullwire/trace/ExceptionClickListener.java b/src/com/nullwire/trace/ExceptionClickListener.java index 3bf7adc..525b755 100644 --- a/src/com/nullwire/trace/ExceptionClickListener.java +++ b/src/com/nullwire/trace/ExceptionClickListener.java @@ -1,49 +1,49 @@ /** * */ package com.nullwire.trace; import java.lang.ref.WeakReference; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.util.Log; /** * @author Kenny Root * */ public class ExceptionClickListener implements OnClickListener { public static String TAG = "com.nullwire.trace.ExceptionClickListener"; WeakReference<Context> context; public ExceptionClickListener() { } public void onClick(DialogInterface dialog, int whichButton) { switch (whichButton) { case DialogInterface.BUTTON_POSITIVE: dialog.dismiss(); Log.d(TAG, "Trying to submit stack traces"); new Thread(new Runnable() { public void run() { ExceptionHandler.submitStackTraces(); } - }).run(); + }).start(); break; case DialogInterface.BUTTON_NEGATIVE: dialog.dismiss(); Log.d(TAG, "Deleting old stack traces."); new Thread(new Runnable() { public void run() { ExceptionHandler.removeStackTraces(); } - }).run(); + }).start(); break; default: Log.d("ExceptionClickListener", "Got unknown button click: " + whichButton); dialog.cancel(); } } }
false
true
public void onClick(DialogInterface dialog, int whichButton) { switch (whichButton) { case DialogInterface.BUTTON_POSITIVE: dialog.dismiss(); Log.d(TAG, "Trying to submit stack traces"); new Thread(new Runnable() { public void run() { ExceptionHandler.submitStackTraces(); } }).run(); break; case DialogInterface.BUTTON_NEGATIVE: dialog.dismiss(); Log.d(TAG, "Deleting old stack traces."); new Thread(new Runnable() { public void run() { ExceptionHandler.removeStackTraces(); } }).run(); break; default: Log.d("ExceptionClickListener", "Got unknown button click: " + whichButton); dialog.cancel(); } }
public void onClick(DialogInterface dialog, int whichButton) { switch (whichButton) { case DialogInterface.BUTTON_POSITIVE: dialog.dismiss(); Log.d(TAG, "Trying to submit stack traces"); new Thread(new Runnable() { public void run() { ExceptionHandler.submitStackTraces(); } }).start(); break; case DialogInterface.BUTTON_NEGATIVE: dialog.dismiss(); Log.d(TAG, "Deleting old stack traces."); new Thread(new Runnable() { public void run() { ExceptionHandler.removeStackTraces(); } }).start(); break; default: Log.d("ExceptionClickListener", "Got unknown button click: " + whichButton); dialog.cancel(); } }
diff --git a/dspace/src/org/dspace/content/InstallItem.java b/dspace/src/org/dspace/content/InstallItem.java index a4a85cafe..1e719a264 100644 --- a/dspace/src/org/dspace/content/InstallItem.java +++ b/dspace/src/org/dspace/content/InstallItem.java @@ -1,212 +1,228 @@ /* * InstallItem.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.content; import java.io.IOException; import java.sql.SQLException; import org.dspace.authorize.AuthorizeException; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.handle.HandleManager; import org.dspace.search.DSIndexer; /** * Support to install item in the archive * * @author dstuve * @version $Revision$ */ public class InstallItem { /** * Take an InProgressSubmission and turn it into a fully-archived Item, * creating a new Handle * * @param c * DSpace Context * @param is * submission to install * * @return the fully archived Item */ public static Item installItem(Context c, InProgressSubmission is) throws SQLException, IOException, AuthorizeException { return installItem(c, is, null); } /** * Take an InProgressSubmission and turn it into a fully-archived Item. * * @param c current context * @param is * submission to install * @param suppliedHandle * the existing Handle to give the installed item * * @return the fully archived Item */ public static Item installItem(Context c, InProgressSubmission is, String suppliedHandle) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); String handle; // set the language to default if it's not set already DCValue[] dc = item.getDC("language", "iso", Item.ANY); + // FIXME: May need to review this arbitrary assignment of default language. The + // context of the submission should probably determine if the default language + // should be set rather than a (somewhat arbitrary) test of whether it has been set + // somewhere along a submission workflow or not. Maybe it has deliberately been left + // unset. + // Also if supporting multiple schemas, the default metadata fields should probably + // also be made configurable. if (dc.length < 1) { // Just set default language item.addDC("language", "iso", null, ConfigurationManager .getProperty("default.language")); } + else + { + // N/A selected in UI sets an empty string field so remove it + // Use this method for now to filter the N/A entry until FIXME above is addressed. + if (dc[0].value.equals("")) + { + item.clearDC("language", "iso", Item.ANY); + } + } // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if (currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // if no previous handle supplied, create one if (suppliedHandle == null) { // create handle handle = HandleManager.createHandle(c, item); } else { handle = HandleManager.createHandle(c, item, suppliedHandle); } String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value item.addDC("identifier", "uri", null, handleref); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i] .getSize()) + " bytes"); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // set owning collection item.setOwningCollection(is.getCollection()); // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexContent(c, item); // remove in-progress submission is.deleteWrapper(); // remove the item's policies and replace them with // the defaults from the collection item.inheritCollectionDefaultPolicies(is.getCollection()); return item; } /** * Generate provenance-worthy description of the bitstreams contained in an * item. * * @param myitem the item generate description for * * @return provenance description */ public static String getBitstreamProvenanceMessage(Item myitem) throws SQLException { // Get non-internal format bitstreams Bitstream[] bitstreams = myitem.getNonInternalBitstreams(); // Create provenance description String mymessage = "No. of bitstreams: " + bitstreams.length + "\n"; // Add sizes and checksums of bitstreams for (int j = 0; j < bitstreams.length; j++) { mymessage = mymessage + bitstreams[j].getName() + ": " + bitstreams[j].getSize() + " bytes, checksum: " + bitstreams[j].getChecksum() + " (" + bitstreams[j].getChecksumAlgorithm() + ")\n"; } return mymessage; } }
false
true
public static Item installItem(Context c, InProgressSubmission is, String suppliedHandle) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); String handle; // set the language to default if it's not set already DCValue[] dc = item.getDC("language", "iso", Item.ANY); if (dc.length < 1) { // Just set default language item.addDC("language", "iso", null, ConfigurationManager .getProperty("default.language")); } // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if (currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // if no previous handle supplied, create one if (suppliedHandle == null) { // create handle handle = HandleManager.createHandle(c, item); } else { handle = HandleManager.createHandle(c, item, suppliedHandle); } String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value item.addDC("identifier", "uri", null, handleref); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i] .getSize()) + " bytes"); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // set owning collection item.setOwningCollection(is.getCollection()); // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexContent(c, item); // remove in-progress submission is.deleteWrapper(); // remove the item's policies and replace them with // the defaults from the collection item.inheritCollectionDefaultPolicies(is.getCollection()); return item; }
public static Item installItem(Context c, InProgressSubmission is, String suppliedHandle) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); String handle; // set the language to default if it's not set already DCValue[] dc = item.getDC("language", "iso", Item.ANY); // FIXME: May need to review this arbitrary assignment of default language. The // context of the submission should probably determine if the default language // should be set rather than a (somewhat arbitrary) test of whether it has been set // somewhere along a submission workflow or not. Maybe it has deliberately been left // unset. // Also if supporting multiple schemas, the default metadata fields should probably // also be made configurable. if (dc.length < 1) { // Just set default language item.addDC("language", "iso", null, ConfigurationManager .getProperty("default.language")); } else { // N/A selected in UI sets an empty string field so remove it // Use this method for now to filter the N/A entry until FIXME above is addressed. if (dc[0].value.equals("")) { item.clearDC("language", "iso", Item.ANY); } } // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if (currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // if no previous handle supplied, create one if (suppliedHandle == null) { // create handle handle = HandleManager.createHandle(c, item); } else { handle = HandleManager.createHandle(c, item, suppliedHandle); } String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value item.addDC("identifier", "uri", null, handleref); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i] .getSize()) + " bytes"); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // set owning collection item.setOwningCollection(is.getCollection()); // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexContent(c, item); // remove in-progress submission is.deleteWrapper(); // remove the item's policies and replace them with // the defaults from the collection item.inheritCollectionDefaultPolicies(is.getCollection()); return item; }
diff --git a/src/ussr/builder/saveLoadXML/SaveLoadXMLTemplate.java b/src/ussr/builder/saveLoadXML/SaveLoadXMLTemplate.java index a4747b90..69f282f8 100644 --- a/src/ussr/builder/saveLoadXML/SaveLoadXMLTemplate.java +++ b/src/ussr/builder/saveLoadXML/SaveLoadXMLTemplate.java @@ -1,540 +1,545 @@ package ussr.builder.saveLoadXML; import java.awt.Color; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import ussr.builder.helpers.BuilderHelper; import ussr.builder.labelingTools.LabelingTemplate; import ussr.model.Module; /** * The main responsibility of this class is to host the methods common to children classes. * It is following design pattern called TEMPLATE method. As a result contains Template, * common and primitive methods. * @author Konstantinas * */ public abstract class SaveLoadXMLTemplate implements SaveLoadXMLFileTemplateInter { protected String robotMorphologyFileDirectoryName; /** * The string representation of XML encoding */ private final static String XML_ENCODING = "ISO-8859-1"; /** * The empty attributes for the tag, in case there is no need to have attributes. */ public final static AttributesImpl EMPTY_ATT = new AttributesImpl(); /** * String representation of "CONNECTOR" tag. */ public final static String CONNECTOR_TAG = "CONNECTOR"; /** * The name of the attribute for connector tag. */ private final static String ATT_NUMBER = "NUMBER"; /** * Adornment of quaternion appearing when transforming quaternion into String. */ private final static String QUATERNION_ADORNMENT ="com.jme.math.Quaternion:"; /** * Adornment of Vector3f appearing when transforming Vector3f into String. */ private final static String VECTOR3F_ADORNMENT = "com.jme.math.Vector3f"; /** * The states of connectors. */ private final static String CONNECTED = "connected", DISCONNECTED = "disconnected"; /** * Acts a host for common, template and primitive methods to children classes. * @param simulation, the physical simulation. */ public SaveLoadXMLTemplate(){ } /** * Saves the data about simulation in chosen XML format file. * This operation is TEMPLATE method. Operation means that it should be executed on the object. * @param fileDirectoryName, the name of directory, like for example: "C:/newXMLfile". */ public void saveXMLfile(UssrXmlFileTypes ussrXmlFileType, String fileDirectoryName) { TransformerHandler transformerHandler = initializeTransformer(fileDirectoryName); this.robotMorphologyFileDirectoryName = fileDirectoryName; printOutXML(ussrXmlFileType, transformerHandler); } /** * Loads the data about simulation from chosen XML file into simulation. * This operation is TEMPLATE method. Operation means that it should be executed on the object. * @param fileDirectoryName, the name of directory, like for example: "C:/newXMLfile". */ public void loadXMLfile(UssrXmlFileTypes ussrXmlFileType, String fileDirectoryName){ Document document = initializeDocument(fileDirectoryName); this.robotMorphologyFileDirectoryName = fileDirectoryName; loadInXML(ussrXmlFileType, document); } /** * Initializes SAX 2.0 content handler and assigns it to newly created XML file. * This method is so-called common and at the same time "Primitive operation" for above TEMPLATE method, called "saveXMLfile(String fileDirectoryName)". * @param fileDirectoryName,the name of directory, like for example: "C:/newXMLfile". * @return transformerHandler, the content handler used to print out XML format. */ public TransformerHandler initializeTransformer(String fileDirectoryName) { - File newFile = new File (fileDirectoryName + XML_EXTENSION); + File newFile; + if (fileDirectoryName.contains(XML_EXTENSION)){ + newFile = new File (fileDirectoryName); + }else{ + newFile = new File (fileDirectoryName + XML_EXTENSION); + } BufferedWriter characterWriter = null; try { characterWriter = new BufferedWriter(new FileWriter(newFile, true)); } catch (IOException e) { throw new Error ("Input Output exception for file appeared and named as: "+ e.toString()); } StreamResult streamResult = new StreamResult(characterWriter); SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); /* SAX2.0 ContentHandler*/ TransformerHandler transformerHandler = null; try { transformerHandler = transformerFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error ("SAX exception appeared and named as: "+ e.toString()); } Transformer serializer = transformerHandler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING,XML_ENCODING); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); transformerHandler.setResult(streamResult); return transformerHandler; } /** * Initializes the document object of DOM for reading xml file. * This method is so-called common and at the same time "Primitive operation" for above TEMPLATE method, called "loadXMLfile(String fileDirectoryName)". * @param fileDirectoryName,the name of directory, like for example: "C:/newXMLfile". * @return doc, DOM object of document. */ private Document initializeDocument(String fileDirectoryName) { File file = new File(fileDirectoryName); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Document doc = null; try { db = dbf.newDocumentBuilder(); doc = db.parse(file); doc.getDocumentElement().normalize(); }catch (Throwable e) { throw new Error ("DOM exception appeared and named as: "+ e.toString()); } return doc; } /** * Method for defining the format of XML to print into the xml file. In other words * what to save in the file about simulation. * This method is so-called "Primitive operation" for above TEMPLATE method, called "saveXMLfile(String fileDirectoryName)". * @param ussrXmlFileType, the type of xml file (ROBOT or Simulation) * @param transformerHandler,the content handler used to print out XML format. */ public abstract void printOutXML(UssrXmlFileTypes ussrXmlFileType, TransformerHandler transformerHandler); /** * Method for defining the format of reading the data from XML file. In other words * what to read from the file into simulation. * This method is so-called "Primitive operation" for above TEMPLATE method, called "loadXMLfile(String fileDirectoryName)". * @param ussrXmlFileType,the type of xml file (ROBOT or Simulation). * @param document,DOM object of document. */ public abstract void loadInXML(UssrXmlFileTypes ussrXmlFileType, Document document); /** * Prints out the first start tag in the hierarchy of XML file. Now for example this is "<MODULES>". * @param transformerHandler,the content handler used to print out XML format. * @param firstStartTagName, the name of the tag. */ public void printFirstStartTag(TransformerHandler transformerHandler, XMLTagsUsed firstStartTagName){ try { transformerHandler.startDocument(); transformerHandler.startElement("","",firstStartTagName.toString(),EMPTY_ATT); } catch (SAXException e) { throw new Error ("SAX exception appeared and named as: "+ e.toString()); } } /** * Prints out the first end tag in the hierarchy of XML file(from bottom). Now for example this * is "</MODULES>". * @param transformerHandler,the content handler used to print out XML format. * @param firstEndTagName, the name of the tag. */ public void printFirstEndTag(TransformerHandler transformerHandler, XMLTagsUsed firstEndTagName){ try { transformerHandler.endElement("","",firstEndTagName.toString()); transformerHandler.endDocument(); } catch (SAXException e) { throw new Error ("SAX exception appeared and named as: "+ e.toString()); } } /** * Prints out the start and end tags, plus the value(data) between them. This can be anything. * In current version this is for example: "<ID>1</ID>" or "<TYPE>ATRON</TYPE>". * @param transformerHandler,the content handler used to print out XML format. * @param tagName, the name of the tag. * @param value, the value between the tags. */ public void printSubTagsWithValue(TransformerHandler transformerHandler, XMLTagsUsed tagName, char[] value){ try { transformerHandler.startElement("","",tagName.toString(),EMPTY_ATT); transformerHandler.characters(value,0,value.length); transformerHandler.endElement("","",tagName.toString()); } catch (SAXException e) { throw new Error ("SAX exception appeared and named as: "+ e.toString()); } } /** * Prints out the state of connectors for the module in simulation. * @param transformerHandler, the content handler used to print out XML format. * @param statesConnectors, the states of connectors, for example "connected" or disconnected. * @param numbersConnectors, the numbers of connectors, for example 1,2,3 and so on. */ //FIXME MAYBE WILL BE NEEDED /* public void printInfoConnectors(TransformerHandler transformerHandler,ArrayList<String> statesConnectors, ArrayList<String> numbersConnectors ){ AttributesImpl atts1 = new AttributesImpl(); for (int index=0; index<statesConnectors.size();index++){ atts1.addAttribute("","",ATT_NUMBER,"first",numbersConnectors.get(index)); try { transformerHandler.startElement("","",CONNECTOR_TAG,atts1); char[] state = statesConnectors.get(index).toCharArray(); transformerHandler.characters(state,0,state.length); transformerHandler.endElement("","",CONNECTOR_TAG); } catch (SAXException e) { throw new Error ("SAX exception appeared and named as: "+ e.toString()); } } }*/ /** * Returns the type of module, like for example ATRON,MTRAN and so on. * @param currentModule, the module in simulation environment * @return char[], the type of the module. */ public char[] getType(Module currentModule){ return currentModule.getProperty(BuilderHelper.getModuleTypeKey()).toCharArray(); } /** * Returns the global ID of the module. * @param currentModule, the module in simulation environment * @return char[], the global ID of the module in simulation. */ public char[] getID(Module currentModule){ return String.valueOf(currentModule.getID()).toCharArray(); } /** * Returns the name of the module, which can be anything. For example: "driver","leftwheel" and so on. * @param currentModule,the module in simulation environment. * @return char[], the name of the module. */ public char[] getName(Module currentModule){ return currentModule.getProperty(BuilderHelper.getModuleNameKey()).toCharArray(); } /** * Returns the rotation (RotationDescription) of the module in simulation environment, * as rotation of its zero component. * @param currentModule,the module in simulation environment. * @return char[], the rotation as RotationDescription of the module. */ public char[] getRotation(Module currentModule){ return currentModule.getPhysics().get(0).getRotation().toString().toCharArray(); } /** * Returns the rotation quaternion of the module in simulation environment, as rotation of its component * @param currentModule, the module in simulation environment. * @return moduleRotationQuat,the rotation as quaternion of component of the module. */ public char[] getRotationQuaternion(Module currentModule){ String moduleRotationQuat = currentModule.getPhysics().get(0).getRotation().getRotation().toString(); moduleRotationQuat = moduleRotationQuat.replace(QUATERNION_ADORNMENT, ""); return moduleRotationQuat.toCharArray(); } /** * Returns the position(VectorDescription) of the module (component) * @param currentModule, the module in simulation environment. * @return modulePosition,the position(as VectorDescription) of the module (component) */ public char[] getPosition(Module currentModule){ char[] modulePosition; if(currentModule.getProperty(BuilderHelper.getModuleTypeKey()).equalsIgnoreCase("MTRAN")){ modulePosition = currentModule.getPhysics().get(1).getPosition().toString().toCharArray(); }else { modulePosition = currentModule.getPhysics().get(0).getPosition().toString().toCharArray(); } return modulePosition; } /** * Returns the position (Vector3f)of the module (component) * @param currentModule, the module in simulation environment. * @return modulePositionVect, the position (as Vector3f)of the module (component) */ public char[] getPositionVector(Module currentModule){ String modulePositionVect = null; if(currentModule.getProperty(BuilderHelper.getModuleTypeKey()).equalsIgnoreCase("MTRAN")){ modulePositionVect = currentModule.getPhysics().get(1).getPosition().getVector().toString(); }else { modulePositionVect = currentModule.getPhysics().get(0).getPosition().getVector().toString(); } modulePositionVect = modulePositionVect.replace(VECTOR3F_ADORNMENT, ""); return modulePositionVect.toCharArray(); } /** * Returns the amount of components the module consists of. * @param currentModule, the module in simulation environment. * @return amountComponents, the amount of components the module consists of. */ public char[] getAmountComponents(Module currentModule){ int amountComponents = currentModule.getNumberOfComponents(); return (""+amountComponents).toCharArray(); } /** * Returns the colours of the module components in RGB format. * @param currentModule, the module in simulation environment. * @return colorsComponents,the colours of the module components in RGB format. */ public char[] getColorsComponents(Module currentModule){ String colorsComponents= ""; int amountComponents = currentModule.getNumberOfComponents(); for (int component=0; component<amountComponents;component++){ colorsComponents = colorsComponents + currentModule.getComponent(component).getModuleComponentColor().getRed()+",";//For debugging colorsComponents = colorsComponents + currentModule.getComponent(component).getModuleComponentColor().getGreen()+","; colorsComponents = colorsComponents + currentModule.getComponent(component).getModuleComponentColor().getBlue()+";"; } return colorsComponents.toCharArray(); } /** * Returns amount of connectors on the module. * @param currentModule, the module in simulation environment. * @return amountConnectors, the amount of connectors on the module. */ public char[] getAmountConnectors(Module currentModule){ int amountConnectors = currentModule.getConnectors().size(); return (""+amountConnectors).toCharArray(); } /** * Returns the colours of connectors on the module. * @param currentModule, the module in simulation environment. * @return colorsConnectors,the colours of connectors on the module. */ public char[] getColorsConnectors(Module currentModule){ String colorsConnectors = ""; int amountConnectors = currentModule.getConnectors().size(); for (int connector=0; connector<amountConnectors;connector++){ colorsConnectors= colorsConnectors + currentModule.getConnectors().get(connector).getColor().getRed()+",";//For debugging colorsConnectors = colorsConnectors + currentModule.getConnectors().get(connector).getColor().getGreen()+","; colorsConnectors = colorsConnectors + currentModule.getConnectors().get(connector).getColor().getBlue()+";"; } return colorsConnectors.toCharArray(); } /** * Returns the labels assigned to the module. * @param currentModule, the module in simulation environment. * @return char[], the labels assigned to the module. */ public char[] getLabelsModule(Module currentModule){ String labels = currentModule.getProperty(BuilderHelper.getLabelsKey()); if (labels == null){// means there are no labels assigned to this module. labels = BuilderHelper.getTempLabel(); }else if (labels.contains(LabelingTemplate.NONE)){/*do nothing*/} return labels.toCharArray(); } /** * Returns the labels of connectors on specific module. * @param currentModule,the module in simulation environment. * @return labels, the labels of all connectors on the module. */ public char[] getLabelsConnectors(Module currentModule){ int amountConnectors = currentModule.getConnectors().size(); String labels = null; int counter=0; for (int connector=0; connector<amountConnectors;connector++){ counter++; String label = currentModule.getConnectors().get(connector).getProperty(BuilderHelper.getLabelsKey()); if (label == null||labels==null){//module do not even have labels assigned if (counter==1){//for 0 connector do not consider labels, because they not yet exist labels=BuilderHelper.getTempLabel()+ LabelingTemplate.LABEL_SEPARATOR; }else{ labels=labels+BuilderHelper.getTempLabel()+LabelingTemplate.LABEL_SEPARATOR; } }else{ labels = labels+label+LabelingTemplate.LABEL_SEPARATOR; } } return labels.toCharArray(); } /** * Returns states of connectors(for example:"connected" or "disconnected") or numbers of connectors of the module. * @param currentModule, the module in simulation environment. * @param state, flag to indicate what should be returned. True when states of connectors should be returned. * False when numbers of connectors should be returned. * @return statesConnectors or numbersConnectors. */ //FIXME Maybe will be needed later /* public ArrayList<String> getInfoConnectors (Module currentModule, boolean state){ int amountConnectors = currentModule.getConnectors().size(); ArrayList<String> statesConnectors = new ArrayList<String>(); ArrayList<String> numbersConnectors = new ArrayList<String>(); for (int connector=0; connector<amountConnectors;connector++){ boolean connectorState = currentModule.getConnectors().get(connector).isConnected(); String connectorNumber = currentModule.getConnectors().get(connector).getProperty(BuilderHelper.getModuleConnectorNrKey()); numbersConnectors.add(connectorNumber); if (connectorState){ statesConnectors.add(CONNECTED); }else { statesConnectors.add(DISCONNECTED); } } if (state ==true){ return statesConnectors; }else return numbersConnectors; }*/ /** * Extract the data between the start and end tags. * @param firstElmnt, first appearance of the node. * @param tagName, the name of the tag. * @return value, the data between the start and end tags. */ public String extractTagValue(Element firstElmnt,XMLTagsUsed tagName){ NodeList firstNmElmntLst = firstElmnt.getElementsByTagName(tagName.toString()); Element firstNmElmnt = (Element) firstNmElmntLst.item(0); NodeList firstNm = firstNmElmnt.getChildNodes(); return ((Node) firstNm.item(0)).getNodeValue(); } /** * Extracts the colors of components from the String. * @param amountComponents, the amount of components. * @param colorsComponents, the string representing the colors in RGB form. * @return listColorsComponents, the list of colors of components. */ public LinkedList<Color> extractColorsComponents(int amountComponents, String colorsComponents){ String[] newColorsComponents = colorsComponents.split(";"); LinkedList<Color> listColorsComponents = new LinkedList<Color>(); for (int component=0;component<amountComponents;component++){ String[] specificColors = newColorsComponents[component].split(","); int red = Integer.parseInt(specificColors[0]); int green = Integer.parseInt(specificColors[1]); int blue = Integer.parseInt(specificColors[2]); Color newColor = new Color(red,green,blue); listColorsComponents.add(newColor); } return listColorsComponents; } /** * Extracts the colors of connectors from the String. * @param amountConnectors, the amount of connectors. * @param colorsConnectors,the string representing the colors in RGB form. * @return listColorsConnectors, the list of colors of connectors. */ public LinkedList<Color> extractColorsConnectors(int amountConnectors, String colorsConnectors){ String[] newColorsConnectors= colorsConnectors.split(";"); LinkedList<Color> listColorsConnectors= new LinkedList<Color>(); for (int connector=0;connector<amountConnectors;connector++){ String[] specificColors = newColorsConnectors[connector].split(","); int red = Integer.parseInt(specificColors[0]); int green = Integer.parseInt(specificColors[1]); int blue = Integer.parseInt(specificColors[2]); Color newColor = new Color(red,green,blue); listColorsConnectors.add(newColor); } return listColorsConnectors; } /** * Extracts the specific coordinate from Quaternion string. * @param textString, the string representing Quaternion; * @param coordinate, the coordinate to extract. * @return extractedValue, the value of coordinate. */ public float extractFromQuaternion(String textString, String coordinate){ textString =textString.replace("]", ""); textString =textString.replace("x", ""); textString =textString.replace("y", ""); textString =textString.replace("z", ""); textString =textString.replace("w", ""); textString =textString.replace("=", ","); String[] temporary = textString.split(","); float extractedValue = 100000; if (coordinate.equalsIgnoreCase("X")){ extractedValue = Float.parseFloat(temporary[1]); }else if (coordinate.equalsIgnoreCase("Y")){ extractedValue = Float.parseFloat(temporary[2]); }else if (coordinate.equalsIgnoreCase("Z")){ extractedValue = Float.parseFloat(temporary[3]); }else if (coordinate.equalsIgnoreCase("W")){ extractedValue = Float.parseFloat(temporary[4]); }else throw new Error ("There is no such coordinate"); return extractedValue; } /*EXPERIMENTAL PART FOR SIMULATION SET UP*/ public char[] getControllerLocation(Module currentModule){ String roughControllerLocation = currentModule.getController().toString();//.toString(); String[]controllerLocation = null; if (roughControllerLocation.contains("@")){ controllerLocation = roughControllerLocation.split("@"); }else if (roughControllerLocation.contains("$")){ controllerLocation = roughControllerLocation.split("$"); } return controllerLocation[0].toCharArray(); } }
true
true
public TransformerHandler initializeTransformer(String fileDirectoryName) { File newFile = new File (fileDirectoryName + XML_EXTENSION); BufferedWriter characterWriter = null; try { characterWriter = new BufferedWriter(new FileWriter(newFile, true)); } catch (IOException e) { throw new Error ("Input Output exception for file appeared and named as: "+ e.toString()); } StreamResult streamResult = new StreamResult(characterWriter); SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); /* SAX2.0 ContentHandler*/ TransformerHandler transformerHandler = null; try { transformerHandler = transformerFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error ("SAX exception appeared and named as: "+ e.toString()); } Transformer serializer = transformerHandler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING,XML_ENCODING); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); transformerHandler.setResult(streamResult); return transformerHandler; }
public TransformerHandler initializeTransformer(String fileDirectoryName) { File newFile; if (fileDirectoryName.contains(XML_EXTENSION)){ newFile = new File (fileDirectoryName); }else{ newFile = new File (fileDirectoryName + XML_EXTENSION); } BufferedWriter characterWriter = null; try { characterWriter = new BufferedWriter(new FileWriter(newFile, true)); } catch (IOException e) { throw new Error ("Input Output exception for file appeared and named as: "+ e.toString()); } StreamResult streamResult = new StreamResult(characterWriter); SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); /* SAX2.0 ContentHandler*/ TransformerHandler transformerHandler = null; try { transformerHandler = transformerFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error ("SAX exception appeared and named as: "+ e.toString()); } Transformer serializer = transformerHandler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING,XML_ENCODING); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); transformerHandler.setResult(streamResult); return transformerHandler; }
diff --git a/src/com/android/deskclock/AlarmReceiver.java b/src/com/android/deskclock/AlarmReceiver.java index 1e3e6df1a..db327c22d 100644 --- a/src/com/android/deskclock/AlarmReceiver.java +++ b/src/com/android/deskclock/AlarmReceiver.java @@ -1,261 +1,262 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.deskclock; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Parcel; import android.os.PowerManager.WakeLock; import android.text.TextUtils; import com.android.deskclock.provider.Alarm; import java.util.Calendar; /** * Glue class: connects AlarmAlert IntentReceiver to AlarmAlert * activity. Passes through Alarm ID. */ public class AlarmReceiver extends BroadcastReceiver { /** If the alarm is older than STALE_WINDOW, ignore. It is probably the result of a time or timezone change */ private final static int STALE_WINDOW = 30 * 60 * 1000; @Override public void onReceive(final Context context, final Intent intent) { final PendingResult result = goAsync(); final WakeLock wl = AlarmAlertWakeLock.createPartialWakeLock(context); wl.acquire(); AsyncHandler.post(new Runnable() { @Override public void run() { handleIntent(context, intent); result.finish(); wl.release(); } }); } private void handleIntent(Context context, Intent intent) { if (Alarms.ALARM_KILLED.equals(intent.getAction())) { // The alarm has been killed, update the notification updateNotification(context, (Alarm) intent.getParcelableExtra(Alarms.ALARM_INTENT_EXTRA), intent.getIntExtra(Alarms.ALARM_KILLED_TIMEOUT, -1)); return; } else if (Alarms.CANCEL_SNOOZE.equals(intent.getAction())) { Alarm alarm = null; if (intent.hasExtra(Alarms.ALARM_INTENT_EXTRA)) { // Get the alarm out of the Intent alarm = intent.getParcelableExtra(Alarms.ALARM_INTENT_EXTRA); } if (alarm != null) { Alarms.disableSnoozeAlert(context, alarm.id); Alarms.setNextAlert(context); } else { // Don't know what snoozed alarm to cancel, so cancel them all. This // shouldn't happen Log.wtf("Unable to parse Alarm from intent."); Alarms.saveSnoozeAlert(context, Alarm.INVALID_ID, -1); } // Inform any active UI that alarm snooze was cancelled context.sendBroadcast(new Intent(Alarms.ALARM_SNOOZE_CANCELLED)); return; } else if (!Alarms.ALARM_ALERT_ACTION.equals(intent.getAction())) { // Unknown intent, bail. return; } Alarm alarm = null; // Grab the alarm from the intent. Since the remote AlarmManagerService // fills in the Intent to add some extra data, it must unparcel the // Alarm object. It throws a ClassNotFoundException when unparcelling. // To avoid this, do the marshalling ourselves. final byte[] data = intent.getByteArrayExtra(Alarms.ALARM_RAW_DATA); if (data != null) { Parcel in = Parcel.obtain(); in.unmarshall(data, 0, data.length); in.setDataPosition(0); alarm = Alarm.CREATOR.createFromParcel(in); } if (alarm == null) { Log.wtf("Failed to parse the alarm from the intent"); // Make sure we set the next alert if needed. Alarms.setNextAlert(context); return; } // Disable the snooze alert if this alarm is the snooze. Alarms.disableSnoozeAlert(context, alarm.id); // Disable this alarm if it does not repeat. if (!alarm.daysOfWeek.isRepeating()) { Alarms.enableAlarm(context, alarm.id, false); } else { // Enable the next alert if there is one. The above call to // enableAlarm will call setNextAlert so avoid calling it twice. Alarms.setNextAlert(context); } // Intentionally verbose: always log the alarm time to provide useful // information in bug reports. long now = System.currentTimeMillis(); long alarmTime = alarm.calculateAlarmTime(); Log.v("Received alarm set for id=" + alarm.id + " " + Log.formatTime(alarmTime) + " " + alarm.label); // Always verbose to track down time change problems. if (now > alarmTime + STALE_WINDOW) { Log.v("Ignoring stale alarm"); return; } // Maintain a cpu wake lock until the AlarmAlert and AlarmKlaxon can // pick it up. AlarmAlertWakeLock.acquireCpuWakeLock(context); /* Close dialogs and window shade */ Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); context.sendBroadcast(closeDialogs); // Decide which activity to start based on the state of the keyguard. Class c = AlarmAlertFullScreen.class; /* KeyguardManager km = (KeyguardManager) context.getSystemService( Context.KEYGUARD_SERVICE); if (km.inKeyguardRestrictedInputMode()) { // Use the full screen activity for security. c = AlarmAlertFullScreen.class; } */ // Play the alarm alert and vibrate the device. Intent playAlarm = new Intent(Alarms.ALARM_ALERT_ACTION); + playAlarm.setClass(context,AlarmKlaxon.class); playAlarm.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); context.startService(playAlarm); // Trigger a notification that, when clicked, will show the alarm alert // dialog. No need to check for fullscreen since this will always be // launched from a user action. // NEW: Embed the full-screen UI here. The notification manager will // take care of displaying it if it's OK to do so. Intent alarmAlert = new Intent(context, c); alarmAlert.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); alarmAlert.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); // Make sure to use FLAG_CANCEL_CURRENT or the notification manager will just // use the older intent if it has the same alarm.id PendingIntent pendingIntent = PendingIntent.getActivity(context, (int)alarm.id, alarmAlert, PendingIntent.FLAG_UPDATE_CURRENT); // These two notifications will be used for the action buttons on the notification. Intent snoozeIntent = new Intent(Alarms.ALARM_SNOOZE_ACTION); snoozeIntent.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); PendingIntent pendingSnooze = PendingIntent.getBroadcast(context, (int)alarm.id, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent dismissIntent = new Intent(Alarms.ALARM_DISMISS_ACTION); dismissIntent.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); PendingIntent pendingDismiss = PendingIntent.getBroadcast(context, (int)alarm.id, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(alarmTime); String alarmTimeLabel = Alarms.formatTime(context, cal); // Use the alarm's label or the default label main text of the notification. String label = alarm.getLabelOrDefault(context); Notification n = new Notification.Builder(context) .setContentTitle(label) .setContentText(alarmTimeLabel) .setSmallIcon(R.drawable.stat_notify_alarm) .setOngoing(true) .setAutoCancel(false) .setPriority(Notification.PRIORITY_MAX) .setDefaults(Notification.DEFAULT_LIGHTS) .setWhen(0) .addAction(R.drawable.stat_notify_alarm, context.getResources().getString(R.string.alarm_alert_snooze_text), pendingSnooze) .addAction(android.R.drawable.ic_menu_close_clear_cancel, context.getResources().getString(R.string.alarm_alert_dismiss_text), pendingDismiss) .build(); n.contentIntent = pendingIntent; n.fullScreenIntent = pendingIntent; // Send the notification using the alarm id to easily identify the // correct notification. NotificationManager nm = getNotificationManager(context); nm.cancel((int)alarm.id); nm.notify((int)alarm.id, n); } private NotificationManager getNotificationManager(Context context) { return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); } private void updateNotification(Context context, Alarm alarm, int timeout) { NotificationManager nm = getNotificationManager(context); // If the alarm is null, just cancel the notification. if (alarm == null) { if (Log.LOGV) { Log.v("Cannot update notification for killer callback"); } return; } // Launch AlarmClock when clicked. Intent viewAlarm = new Intent(context, DeskClock.class); viewAlarm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); viewAlarm.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); viewAlarm.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.ALARM_TAB_INDEX); PendingIntent intent = PendingIntent.getActivity(context, (int)alarm.id, viewAlarm, PendingIntent.FLAG_UPDATE_CURRENT); // Update the notification to indicate that the alert has been // silenced. String title = context.getString(R.string.alarm_missed_title); String label = alarm.label; String alarmTime = Alarms.formatTime(context, alarm.calculateAlarmCalendar()); // If the label is null, just show the alarm time. If not, show "time - label". String text = TextUtils.isEmpty(label)? alarmTime : context.getString(R.string.alarm_missed_text, alarmTime, label); Notification n = new Notification.Builder(context) .setContentTitle(title) .setContentText(text) .setSmallIcon(R.drawable.stat_notify_alarm) .setAutoCancel(true) .setPriority(Notification.PRIORITY_HIGH) .setDefaults(Notification.DEFAULT_ALL) .build(); n.contentIntent = intent; // We have to cancel the original notification since it is in the // ongoing section and we want the "killed" notification to be a plain // notification. nm.cancel((int)alarm.id); nm.notify((int)alarm.id, n); } }
true
true
private void handleIntent(Context context, Intent intent) { if (Alarms.ALARM_KILLED.equals(intent.getAction())) { // The alarm has been killed, update the notification updateNotification(context, (Alarm) intent.getParcelableExtra(Alarms.ALARM_INTENT_EXTRA), intent.getIntExtra(Alarms.ALARM_KILLED_TIMEOUT, -1)); return; } else if (Alarms.CANCEL_SNOOZE.equals(intent.getAction())) { Alarm alarm = null; if (intent.hasExtra(Alarms.ALARM_INTENT_EXTRA)) { // Get the alarm out of the Intent alarm = intent.getParcelableExtra(Alarms.ALARM_INTENT_EXTRA); } if (alarm != null) { Alarms.disableSnoozeAlert(context, alarm.id); Alarms.setNextAlert(context); } else { // Don't know what snoozed alarm to cancel, so cancel them all. This // shouldn't happen Log.wtf("Unable to parse Alarm from intent."); Alarms.saveSnoozeAlert(context, Alarm.INVALID_ID, -1); } // Inform any active UI that alarm snooze was cancelled context.sendBroadcast(new Intent(Alarms.ALARM_SNOOZE_CANCELLED)); return; } else if (!Alarms.ALARM_ALERT_ACTION.equals(intent.getAction())) { // Unknown intent, bail. return; } Alarm alarm = null; // Grab the alarm from the intent. Since the remote AlarmManagerService // fills in the Intent to add some extra data, it must unparcel the // Alarm object. It throws a ClassNotFoundException when unparcelling. // To avoid this, do the marshalling ourselves. final byte[] data = intent.getByteArrayExtra(Alarms.ALARM_RAW_DATA); if (data != null) { Parcel in = Parcel.obtain(); in.unmarshall(data, 0, data.length); in.setDataPosition(0); alarm = Alarm.CREATOR.createFromParcel(in); } if (alarm == null) { Log.wtf("Failed to parse the alarm from the intent"); // Make sure we set the next alert if needed. Alarms.setNextAlert(context); return; } // Disable the snooze alert if this alarm is the snooze. Alarms.disableSnoozeAlert(context, alarm.id); // Disable this alarm if it does not repeat. if (!alarm.daysOfWeek.isRepeating()) { Alarms.enableAlarm(context, alarm.id, false); } else { // Enable the next alert if there is one. The above call to // enableAlarm will call setNextAlert so avoid calling it twice. Alarms.setNextAlert(context); } // Intentionally verbose: always log the alarm time to provide useful // information in bug reports. long now = System.currentTimeMillis(); long alarmTime = alarm.calculateAlarmTime(); Log.v("Received alarm set for id=" + alarm.id + " " + Log.formatTime(alarmTime) + " " + alarm.label); // Always verbose to track down time change problems. if (now > alarmTime + STALE_WINDOW) { Log.v("Ignoring stale alarm"); return; } // Maintain a cpu wake lock until the AlarmAlert and AlarmKlaxon can // pick it up. AlarmAlertWakeLock.acquireCpuWakeLock(context); /* Close dialogs and window shade */ Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); context.sendBroadcast(closeDialogs); // Decide which activity to start based on the state of the keyguard. Class c = AlarmAlertFullScreen.class; /* KeyguardManager km = (KeyguardManager) context.getSystemService( Context.KEYGUARD_SERVICE); if (km.inKeyguardRestrictedInputMode()) { // Use the full screen activity for security. c = AlarmAlertFullScreen.class; } */ // Play the alarm alert and vibrate the device. Intent playAlarm = new Intent(Alarms.ALARM_ALERT_ACTION); playAlarm.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); context.startService(playAlarm); // Trigger a notification that, when clicked, will show the alarm alert // dialog. No need to check for fullscreen since this will always be // launched from a user action. // NEW: Embed the full-screen UI here. The notification manager will // take care of displaying it if it's OK to do so. Intent alarmAlert = new Intent(context, c); alarmAlert.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); alarmAlert.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); // Make sure to use FLAG_CANCEL_CURRENT or the notification manager will just // use the older intent if it has the same alarm.id PendingIntent pendingIntent = PendingIntent.getActivity(context, (int)alarm.id, alarmAlert, PendingIntent.FLAG_UPDATE_CURRENT); // These two notifications will be used for the action buttons on the notification. Intent snoozeIntent = new Intent(Alarms.ALARM_SNOOZE_ACTION); snoozeIntent.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); PendingIntent pendingSnooze = PendingIntent.getBroadcast(context, (int)alarm.id, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent dismissIntent = new Intent(Alarms.ALARM_DISMISS_ACTION); dismissIntent.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); PendingIntent pendingDismiss = PendingIntent.getBroadcast(context, (int)alarm.id, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(alarmTime); String alarmTimeLabel = Alarms.formatTime(context, cal); // Use the alarm's label or the default label main text of the notification. String label = alarm.getLabelOrDefault(context); Notification n = new Notification.Builder(context) .setContentTitle(label) .setContentText(alarmTimeLabel) .setSmallIcon(R.drawable.stat_notify_alarm) .setOngoing(true) .setAutoCancel(false) .setPriority(Notification.PRIORITY_MAX) .setDefaults(Notification.DEFAULT_LIGHTS) .setWhen(0) .addAction(R.drawable.stat_notify_alarm, context.getResources().getString(R.string.alarm_alert_snooze_text), pendingSnooze) .addAction(android.R.drawable.ic_menu_close_clear_cancel, context.getResources().getString(R.string.alarm_alert_dismiss_text), pendingDismiss) .build(); n.contentIntent = pendingIntent; n.fullScreenIntent = pendingIntent; // Send the notification using the alarm id to easily identify the // correct notification. NotificationManager nm = getNotificationManager(context); nm.cancel((int)alarm.id); nm.notify((int)alarm.id, n); }
private void handleIntent(Context context, Intent intent) { if (Alarms.ALARM_KILLED.equals(intent.getAction())) { // The alarm has been killed, update the notification updateNotification(context, (Alarm) intent.getParcelableExtra(Alarms.ALARM_INTENT_EXTRA), intent.getIntExtra(Alarms.ALARM_KILLED_TIMEOUT, -1)); return; } else if (Alarms.CANCEL_SNOOZE.equals(intent.getAction())) { Alarm alarm = null; if (intent.hasExtra(Alarms.ALARM_INTENT_EXTRA)) { // Get the alarm out of the Intent alarm = intent.getParcelableExtra(Alarms.ALARM_INTENT_EXTRA); } if (alarm != null) { Alarms.disableSnoozeAlert(context, alarm.id); Alarms.setNextAlert(context); } else { // Don't know what snoozed alarm to cancel, so cancel them all. This // shouldn't happen Log.wtf("Unable to parse Alarm from intent."); Alarms.saveSnoozeAlert(context, Alarm.INVALID_ID, -1); } // Inform any active UI that alarm snooze was cancelled context.sendBroadcast(new Intent(Alarms.ALARM_SNOOZE_CANCELLED)); return; } else if (!Alarms.ALARM_ALERT_ACTION.equals(intent.getAction())) { // Unknown intent, bail. return; } Alarm alarm = null; // Grab the alarm from the intent. Since the remote AlarmManagerService // fills in the Intent to add some extra data, it must unparcel the // Alarm object. It throws a ClassNotFoundException when unparcelling. // To avoid this, do the marshalling ourselves. final byte[] data = intent.getByteArrayExtra(Alarms.ALARM_RAW_DATA); if (data != null) { Parcel in = Parcel.obtain(); in.unmarshall(data, 0, data.length); in.setDataPosition(0); alarm = Alarm.CREATOR.createFromParcel(in); } if (alarm == null) { Log.wtf("Failed to parse the alarm from the intent"); // Make sure we set the next alert if needed. Alarms.setNextAlert(context); return; } // Disable the snooze alert if this alarm is the snooze. Alarms.disableSnoozeAlert(context, alarm.id); // Disable this alarm if it does not repeat. if (!alarm.daysOfWeek.isRepeating()) { Alarms.enableAlarm(context, alarm.id, false); } else { // Enable the next alert if there is one. The above call to // enableAlarm will call setNextAlert so avoid calling it twice. Alarms.setNextAlert(context); } // Intentionally verbose: always log the alarm time to provide useful // information in bug reports. long now = System.currentTimeMillis(); long alarmTime = alarm.calculateAlarmTime(); Log.v("Received alarm set for id=" + alarm.id + " " + Log.formatTime(alarmTime) + " " + alarm.label); // Always verbose to track down time change problems. if (now > alarmTime + STALE_WINDOW) { Log.v("Ignoring stale alarm"); return; } // Maintain a cpu wake lock until the AlarmAlert and AlarmKlaxon can // pick it up. AlarmAlertWakeLock.acquireCpuWakeLock(context); /* Close dialogs and window shade */ Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); context.sendBroadcast(closeDialogs); // Decide which activity to start based on the state of the keyguard. Class c = AlarmAlertFullScreen.class; /* KeyguardManager km = (KeyguardManager) context.getSystemService( Context.KEYGUARD_SERVICE); if (km.inKeyguardRestrictedInputMode()) { // Use the full screen activity for security. c = AlarmAlertFullScreen.class; } */ // Play the alarm alert and vibrate the device. Intent playAlarm = new Intent(Alarms.ALARM_ALERT_ACTION); playAlarm.setClass(context,AlarmKlaxon.class); playAlarm.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); context.startService(playAlarm); // Trigger a notification that, when clicked, will show the alarm alert // dialog. No need to check for fullscreen since this will always be // launched from a user action. // NEW: Embed the full-screen UI here. The notification manager will // take care of displaying it if it's OK to do so. Intent alarmAlert = new Intent(context, c); alarmAlert.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); alarmAlert.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); // Make sure to use FLAG_CANCEL_CURRENT or the notification manager will just // use the older intent if it has the same alarm.id PendingIntent pendingIntent = PendingIntent.getActivity(context, (int)alarm.id, alarmAlert, PendingIntent.FLAG_UPDATE_CURRENT); // These two notifications will be used for the action buttons on the notification. Intent snoozeIntent = new Intent(Alarms.ALARM_SNOOZE_ACTION); snoozeIntent.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); PendingIntent pendingSnooze = PendingIntent.getBroadcast(context, (int)alarm.id, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent dismissIntent = new Intent(Alarms.ALARM_DISMISS_ACTION); dismissIntent.putExtra(Alarms.ALARM_INTENT_EXTRA, alarm); PendingIntent pendingDismiss = PendingIntent.getBroadcast(context, (int)alarm.id, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(alarmTime); String alarmTimeLabel = Alarms.formatTime(context, cal); // Use the alarm's label or the default label main text of the notification. String label = alarm.getLabelOrDefault(context); Notification n = new Notification.Builder(context) .setContentTitle(label) .setContentText(alarmTimeLabel) .setSmallIcon(R.drawable.stat_notify_alarm) .setOngoing(true) .setAutoCancel(false) .setPriority(Notification.PRIORITY_MAX) .setDefaults(Notification.DEFAULT_LIGHTS) .setWhen(0) .addAction(R.drawable.stat_notify_alarm, context.getResources().getString(R.string.alarm_alert_snooze_text), pendingSnooze) .addAction(android.R.drawable.ic_menu_close_clear_cancel, context.getResources().getString(R.string.alarm_alert_dismiss_text), pendingDismiss) .build(); n.contentIntent = pendingIntent; n.fullScreenIntent = pendingIntent; // Send the notification using the alarm id to easily identify the // correct notification. NotificationManager nm = getNotificationManager(context); nm.cancel((int)alarm.id); nm.notify((int)alarm.id, n); }
diff --git a/src/main/java/de/javadesign/cdi/extension/spring/SpringBeanVetoExtension.java b/src/main/java/de/javadesign/cdi/extension/spring/SpringBeanVetoExtension.java index b5ef05b..ce0deff 100644 --- a/src/main/java/de/javadesign/cdi/extension/spring/SpringBeanVetoExtension.java +++ b/src/main/java/de/javadesign/cdi/extension/spring/SpringBeanVetoExtension.java @@ -1,99 +1,99 @@ package de.javadesign.cdi.extension.spring; import de.javadesign.cdi.extension.spring.context.ApplicationContextProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.web.context.ContextLoader; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.ProcessAnnotatedType; import java.text.MessageFormat; /** * This CDI Extension observes ProcessAnnotatedType events fired for every found bean during bean * discovery phase to prevent Spring Beans from being deployed again if found by the CDI XML or * class path scanner. * */ public class SpringBeanVetoExtension implements Extension { private static final Logger LOG = LoggerFactory.getLogger("de.javadesign.cdi.extension"); private boolean applicationContextFound = false; private boolean initialized = false; private ConfigurableListableBeanFactory beanFactory; public SpringBeanVetoExtension() { LOG.info(MessageFormat.format("{0} created.", this.getClass().getSimpleName())); } public void vetoSpringBeans(@Observes ProcessAnnotatedType event) { if (!initialized) { init(); } if (!applicationContextFound) { return; } if (beanForClassExists(event.getAnnotatedType().getJavaClass())) { // Do not deploy this class to the CDI context. event.veto(); if (LOG.isDebugEnabled()) { LOG.debug("Vetoing " + event.getAnnotatedType().getJavaClass().getCanonicalName()); } } } public void init() { initialized = true; AbstractApplicationContext applicationContext = (AbstractApplicationContext) ContextLoader .getCurrentWebApplicationContext(); if (applicationContext==null) { LOG.warn("No Web Spring-ApplicationContext found, try to resolve via application context provider."); applicationContext = (AbstractApplicationContext) ApplicationContextProvider.getApplicationContext(); } if (null != applicationContext) { LOG.info("ApplicationContext found."); applicationContextFound = true; beanFactory = applicationContext.getBeanFactory(); } else { LOG.warn("No Spring-ApplicationContext found."); } } /** * Uses the Spring BeanFactory to see if there is any Spring Bean matching * the given Class and returns true in the case such a bean is found and * false otherwise. * * @param clazz The Class currently observed by the CDI container. * @return True if there is a Spring Bean matching the given Class, false otherwise */ private boolean beanForClassExists(Class<?> clazz) { // Lookup if (0 != beanFactory.getBeanNamesForType(clazz).length) { return true; } // Workaround if interfaces in combination with component scanning is used. // Spring framework automatically detects interface and implementation pairs // but only returns bean names for interface types then. // We loop all known bean definitions to find out if the given class is // a spring bean. String[] names = beanFactory.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = beanFactory.getBeanDefinition(name); - if (definition.getBeanClassName().equals(clazz.getCanonicalName())) { + if (definition.getBeanClassName()!=null && definition.getBeanClassName().equals(clazz.getCanonicalName())) { return true; } } return false; } }
true
true
private boolean beanForClassExists(Class<?> clazz) { // Lookup if (0 != beanFactory.getBeanNamesForType(clazz).length) { return true; } // Workaround if interfaces in combination with component scanning is used. // Spring framework automatically detects interface and implementation pairs // but only returns bean names for interface types then. // We loop all known bean definitions to find out if the given class is // a spring bean. String[] names = beanFactory.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = beanFactory.getBeanDefinition(name); if (definition.getBeanClassName().equals(clazz.getCanonicalName())) { return true; } } return false; }
private boolean beanForClassExists(Class<?> clazz) { // Lookup if (0 != beanFactory.getBeanNamesForType(clazz).length) { return true; } // Workaround if interfaces in combination with component scanning is used. // Spring framework automatically detects interface and implementation pairs // but only returns bean names for interface types then. // We loop all known bean definitions to find out if the given class is // a spring bean. String[] names = beanFactory.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = beanFactory.getBeanDefinition(name); if (definition.getBeanClassName()!=null && definition.getBeanClassName().equals(clazz.getCanonicalName())) { return true; } } return false; }
diff --git a/src/net/java/sip/communicator/impl/gui/main/login/SecurityAuthorityImpl.java b/src/net/java/sip/communicator/impl/gui/main/login/SecurityAuthorityImpl.java index b8983f03d..97f497cef 100644 --- a/src/net/java/sip/communicator/impl/gui/main/login/SecurityAuthorityImpl.java +++ b/src/net/java/sip/communicator/impl/gui/main/login/SecurityAuthorityImpl.java @@ -1,131 +1,135 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.main.login; import net.java.sip.communicator.impl.gui.i18n.*; import net.java.sip.communicator.impl.gui.main.*; import net.java.sip.communicator.service.protocol.*; /** * The <tt>SecurityAuthorityImpl</tt> is an implementation of the * <tt>SecurityAuthority</tt> interface. * * @author Yana Stamcheva */ public class SecurityAuthorityImpl implements SecurityAuthority { private MainFrame mainFrame; private ProtocolProviderService protocolProvider; private boolean isUserNameEditable = false; /** * Creates an instance of <tt>SecurityAuthorityImpl</tt>. * @param mainFrame The parent window of the <tt>AuthenticationWIndow</tt> * created in this class. * @param protocolProvider The <tt>ProtocolProviderService</tt> for this * <tt>SecurityAuthority</tt>. */ public SecurityAuthorityImpl(MainFrame mainFrame, ProtocolProviderService protocolProvider) { this.mainFrame = mainFrame; this.protocolProvider = protocolProvider; } /** * Implements the <code>SecurityAuthority.obtainCredentials</code> method. * Creates and show an <tt>AuthenticationWindow</tt>, where user could enter * its password. * @param realm The realm that the credentials are needed for. * @param userCredentials the values to propose the user by default * @param reasonCode indicates the reason for which we're obtaining the * credentials. * @return The credentials associated with the specified realm or null if * none could be obtained. */ public UserCredentials obtainCredentials( String realm, UserCredentials userCredentials, int reasonCode) { String errorMessage = null; if (reasonCode == WRONG_PASSWORD) { errorMessage - = Messages.getI18NString("authenticationFailed").getText(); + = Messages.getI18NString("authenticationFailed", + new String[]{ userCredentials.getUserName(), + realm}).getText(); } else if (reasonCode == WRONG_USERNAME) { errorMessage - = Messages.getI18NString("authenticationFailed").getText(); + = Messages.getI18NString("authenticationFailed", + new String[]{ userCredentials.getUserName(), + realm}).getText(); } AuthenticationWindow loginWindow = null; if (errorMessage == null) loginWindow = new AuthenticationWindow( mainFrame, protocolProvider, realm, userCredentials, isUserNameEditable); else loginWindow = new AuthenticationWindow( mainFrame, protocolProvider, realm, userCredentials, isUserNameEditable, errorMessage); loginWindow.setVisible(true); return userCredentials; } /** * Implements the <code>SecurityAuthority.obtainCredentials</code> method. * Creates and show an <tt>AuthenticationWindow</tt>, where user could enter * its password. * @param realm The realm that the credentials are needed for. * @param userCredentials the values to propose the user by default * @return The credentials associated with the specified realm or null if * none could be obtained. */ public UserCredentials obtainCredentials( String realm, UserCredentials userCredentials) { return this.obtainCredentials(realm, userCredentials, SecurityAuthority.AUTHENTICATION_REQUIRED); } /** * Sets the userNameEditable property, which indicates if the user name * could be changed by user or not. * * @param isUserNameEditable indicates if the user name could be changed by * user */ public void setUserNameEditable(boolean isUserNameEditable) { this.isUserNameEditable = isUserNameEditable; } /** * Indicates if the user name is currently editable, i.e. could be changed * by user or not. * * @return <code>true</code> if the user name could be changed, * <code>false</code> - otherwise. */ public boolean isUserNameEditable() { return isUserNameEditable; } }
false
true
public UserCredentials obtainCredentials( String realm, UserCredentials userCredentials, int reasonCode) { String errorMessage = null; if (reasonCode == WRONG_PASSWORD) { errorMessage = Messages.getI18NString("authenticationFailed").getText(); } else if (reasonCode == WRONG_USERNAME) { errorMessage = Messages.getI18NString("authenticationFailed").getText(); } AuthenticationWindow loginWindow = null; if (errorMessage == null) loginWindow = new AuthenticationWindow( mainFrame, protocolProvider, realm, userCredentials, isUserNameEditable); else loginWindow = new AuthenticationWindow( mainFrame, protocolProvider, realm, userCredentials, isUserNameEditable, errorMessage); loginWindow.setVisible(true); return userCredentials; }
public UserCredentials obtainCredentials( String realm, UserCredentials userCredentials, int reasonCode) { String errorMessage = null; if (reasonCode == WRONG_PASSWORD) { errorMessage = Messages.getI18NString("authenticationFailed", new String[]{ userCredentials.getUserName(), realm}).getText(); } else if (reasonCode == WRONG_USERNAME) { errorMessage = Messages.getI18NString("authenticationFailed", new String[]{ userCredentials.getUserName(), realm}).getText(); } AuthenticationWindow loginWindow = null; if (errorMessage == null) loginWindow = new AuthenticationWindow( mainFrame, protocolProvider, realm, userCredentials, isUserNameEditable); else loginWindow = new AuthenticationWindow( mainFrame, protocolProvider, realm, userCredentials, isUserNameEditable, errorMessage); loginWindow.setVisible(true); return userCredentials; }
diff --git a/src/java-server-framework/org/xins/server/APIManager.java b/src/java-server-framework/org/xins/server/APIManager.java index 7dc40691b..e4482cbdd 100644 --- a/src/java-server-framework/org/xins/server/APIManager.java +++ b/src/java-server-framework/org/xins/server/APIManager.java @@ -1,265 +1,266 @@ /* * $Id$ * * Copyright 2003-2006 Wanadoo Nederland B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.server; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; import org.xins.common.Utils; import org.xins.common.collections.PropertyReader; import org.xins.common.collections.PropertyReaderConverter; import org.xins.common.collections.PropertyReaderUtils; import org.xins.common.text.DateConverter; import org.xins.common.xml.Element; /** * Management bean for the API. * * @version $Revision$ $Date$ * @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>) * * @since XINS 1.5.0 */ public final class APIManager implements APIManagerMBean { //------------------------------------------------------------------------- // Constructors //------------------------------------------------------------------------- APIManager(API api) { _api = api; try { _ip = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException uhex) { Log.log_3250(uhex); _ip = "127.0.0.1"; } } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- /** * The API, never <code>null</code> */ private final API _api; /** * The IP address runing this class, never <code>null</code>. */ private String _ip; //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- /** * Gets the version of the API. * * @return * the version of the API running. * * @throws IOException * if the connection to the MBean fails. */ public String getAPIVersion() throws IOException { return _api.getBootstrapProperties().get(API.API_VERSION_PROPERTY); } /** * Gets the version of XINS which is running this API. * * @return * the version of XINS running the API. * * @throws IOException * if the connection to the MBean fails. */ public String getXINSVersion() throws IOException { return Library.getVersion(); } /** * Gets the name of the API. * * @return * the name the API. * * @throws IOException * if the connection to the MBean fails. */ public String getAPIName() throws IOException { return _api.getName(); } /** * Gets the bootstrap properties. * * @return * the bootstrap properties for this API. * * @throws IOException * if the connection to the MBean fails. */ public CompositeDataSupport getBootstrapProperties() throws IOException { Properties bootstrapProps = PropertyReaderConverter.toProperties(_api.getBootstrapProperties()); return propertiesToCompositeData(bootstrapProps); } /** * Gets the runtime properties. * * @return * the runtime properties for this API. * * @throws IOException * if the connection to the MBean fails. */ public CompositeDataSupport getRuntimeProperties() throws IOException { Properties runtimeProps = PropertyReaderConverter.toProperties(_api.getRuntimeProperties()); return propertiesToCompositeData(runtimeProps); } /** * Gets the time at which the API was started. * * @return * the time at which the API was started in the form YYYYMMDDThhmmssSSS+TZ. * * @throws IOException * if the connection to the MBean fails. */ public String getStartupTime() throws IOException { return DateConverter.toDateString(_api.getStartupTimestamp()); } /** * Gets the list of the API functions. * * @return * the list of the API function names. * * @throws IOException * if the connection to the MBean fails. */ public String[] getFunctionNames() throws IOException { List functions = _api.getFunctionList(); String[] functionNames = new String[functions.size()]; for (int i = 0; i < functions.size(); i++) { Function nextFunction = (Function) functions.get(i); functionNames[i] = nextFunction.getName(); } return functionNames; } /** * Gets the statistics of the functions. * * @return * the statistics of the functions. * * @throws IOException * if the connection to the MBean fails. */ public TabularDataSupport getStatistics() throws IOException { - String[] statsNames = {"count", "error code", "average"}; - OpenType[] statsTypes = {SimpleType.STRING, SimpleType.STRING, SimpleType.STRING}; + String[] statsNames = {"function", "count", "error code", "average"}; + OpenType[] statsTypes = {SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.STRING}; try { CompositeType statType = new CompositeType("Statistic", "A statistic of a function", statsNames, statsNames, statsTypes); TabularType tabType = new TabularType("Function statistics", - "Statistics of the functions", statType, getFunctionNames()); + "Statistics of the functions", statType, statsNames); TabularDataSupport tabularData = new TabularDataSupport(tabType); Iterator itFunctions = _api.getFunctionList().iterator(); while (itFunctions.hasNext()) { Function nextFunction = (Function) itFunctions.next(); Element success = nextFunction.getStatistics().getSuccessfulElement(); HashMap statMap = new HashMap(); + statMap.put("function", nextFunction.getName()); statMap.put("count", success.getAttribute("count")); statMap.put("error code", ""); statMap.put("average", success.getAttribute("average")); CompositeDataSupport statData = new CompositeDataSupport(statType, statMap); tabularData.put(statData); } return tabularData; } catch (Exception ex) { ex.printStackTrace(); return null; } } /** * Executes the _NoOp meta function. * * @throws IOException * if the connection to the MBean fails. */ public void noOp() throws IOException, NoSuchFunctionException, AccessDeniedException { FunctionRequest noOpRequest = new FunctionRequest("_NoOp", PropertyReaderUtils.EMPTY_PROPERTY_READER, null); _api.handleCall(System.currentTimeMillis(), noOpRequest, _ip); } /** * Reloads the runtime properties if the file has changed. * * @throws IOException * if the connection to the MBean fails. */ public void reloadProperties() throws IOException, NoSuchFunctionException, AccessDeniedException { FunctionRequest reloadPropertiesRequest = new FunctionRequest("_ReloadProperties", PropertyReaderUtils.EMPTY_PROPERTY_READER, null); _api.handleCall(System.currentTimeMillis(), reloadPropertiesRequest, _ip); } /** * Utility method to convert a {@link Properties} to a {@link CompositeDataSupport} * * @param properties * the properties to represent to the JMX agent, cannot be <code>null</code>. * * @return * the {@link CompositeDataSupport} containng the properties, or <code>null</code> * if an error occured. */ private CompositeDataSupport propertiesToCompositeData(Properties properties) { try { //String[] itemNames = {"key", "value"}; String[] keys = (String[]) properties.keySet().toArray(new String[0]); OpenType[] itemTypes = new OpenType[keys.length]; for (int i = 0; i < itemTypes.length; i++) { itemTypes[i] = SimpleType.STRING; } CompositeType propsType = new CompositeType("Properties type", "properties", keys, keys, itemTypes); //TabularType tabType = new TabularType("bootstrapProperties", "bootstrap properties", propsType, keys); //TabularDataSupport tabSupport = new TabularDataSupport(tabType); CompositeDataSupport propsData = new CompositeDataSupport(propsType, properties); //tabSupport.putAll(bootstrapProps); //tabSupport.put(propsData); //return tabSupport; return propsData; } catch (Exception ex) { ex.printStackTrace(); return null; } } }
false
true
public TabularDataSupport getStatistics() throws IOException { String[] statsNames = {"count", "error code", "average"}; OpenType[] statsTypes = {SimpleType.STRING, SimpleType.STRING, SimpleType.STRING}; try { CompositeType statType = new CompositeType("Statistic", "A statistic of a function", statsNames, statsNames, statsTypes); TabularType tabType = new TabularType("Function statistics", "Statistics of the functions", statType, getFunctionNames()); TabularDataSupport tabularData = new TabularDataSupport(tabType); Iterator itFunctions = _api.getFunctionList().iterator(); while (itFunctions.hasNext()) { Function nextFunction = (Function) itFunctions.next(); Element success = nextFunction.getStatistics().getSuccessfulElement(); HashMap statMap = new HashMap(); statMap.put("count", success.getAttribute("count")); statMap.put("error code", ""); statMap.put("average", success.getAttribute("average")); CompositeDataSupport statData = new CompositeDataSupport(statType, statMap); tabularData.put(statData); } return tabularData; } catch (Exception ex) { ex.printStackTrace(); return null; } }
public TabularDataSupport getStatistics() throws IOException { String[] statsNames = {"function", "count", "error code", "average"}; OpenType[] statsTypes = {SimpleType.STRING, SimpleType.STRING, SimpleType.STRING, SimpleType.STRING}; try { CompositeType statType = new CompositeType("Statistic", "A statistic of a function", statsNames, statsNames, statsTypes); TabularType tabType = new TabularType("Function statistics", "Statistics of the functions", statType, statsNames); TabularDataSupport tabularData = new TabularDataSupport(tabType); Iterator itFunctions = _api.getFunctionList().iterator(); while (itFunctions.hasNext()) { Function nextFunction = (Function) itFunctions.next(); Element success = nextFunction.getStatistics().getSuccessfulElement(); HashMap statMap = new HashMap(); statMap.put("function", nextFunction.getName()); statMap.put("count", success.getAttribute("count")); statMap.put("error code", ""); statMap.put("average", success.getAttribute("average")); CompositeDataSupport statData = new CompositeDataSupport(statType, statMap); tabularData.put(statData); } return tabularData; } catch (Exception ex) { ex.printStackTrace(); return null; } }
diff --git a/src/com/android/contacts/vcard/ExportProcessor.java b/src/com/android/contacts/vcard/ExportProcessor.java index 42a71b1b2..4bd4ed98d 100644 --- a/src/com/android/contacts/vcard/ExportProcessor.java +++ b/src/com/android/contacts/vcard/ExportProcessor.java @@ -1,273 +1,273 @@ /* * 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.contacts.vcard; import com.android.contacts.R; import com.android.contacts.activities.ContactBrowserActivity; import com.android.vcard.VCardComposer; import com.android.vcard.VCardConfig; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.RawContactsEntity; import android.text.TextUtils; import android.util.Log; import android.widget.RemoteViews; import java.io.FileNotFoundException; import java.io.OutputStream; /** * Class for processing one export request from a user. Dropped after exporting requested Uri(s). * {@link VCardService} will create another object when there is another export request. */ public class ExportProcessor extends ProcessorBase { private static final String LOG_TAG = "VCardExport"; private static final boolean DEBUG = VCardService.DEBUG; private final VCardService mService; private final ContentResolver mResolver; private final NotificationManager mNotificationManager; private final ExportRequest mExportRequest; private final int mJobId; private volatile boolean mCanceled; private volatile boolean mDone; public ExportProcessor(VCardService service, ExportRequest exportRequest, int jobId) { mService = service; mResolver = service.getContentResolver(); mNotificationManager = (NotificationManager)mService.getSystemService(Context.NOTIFICATION_SERVICE); mExportRequest = exportRequest; mJobId = jobId; } @Override public final int getType() { return VCardService.TYPE_EXPORT; } @Override public void run() { // ExecutorService ignores RuntimeException, so we need to show it here. try { runInternal(); if (isCancelled()) { doCancelNotification(); } } catch (OutOfMemoryError e) { Log.e(LOG_TAG, "OutOfMemoryError thrown during import", e); throw e; } catch (RuntimeException e) { Log.e(LOG_TAG, "RuntimeException thrown during export", e); throw e; } finally { synchronized (this) { mDone = true; } } } private void runInternal() { if (DEBUG) Log.d(LOG_TAG, String.format("vCard export (id: %d) has started.", mJobId)); final ExportRequest request = mExportRequest; VCardComposer composer = null; boolean successful = false; try { if (isCancelled()) { Log.i(LOG_TAG, "Export request is cancelled before handling the request"); return; } final Uri uri = request.destUri; final OutputStream outputStream; try { outputStream = mResolver.openOutputStream(uri); } catch (FileNotFoundException e) { Log.w(LOG_TAG, "FileNotFoundException thrown", e); // Need concise title. final String errorReason = mService.getString(R.string.fail_reason_could_not_open_file, uri, e.getMessage()); doFinishNotification(errorReason, null); return; } final String exportType = request.exportType; final int vcardType; if (TextUtils.isEmpty(exportType)) { vcardType = VCardConfig.getVCardTypeFromString( mService.getString(R.string.config_export_vcard_type)); } else { vcardType = VCardConfig.getVCardTypeFromString(exportType); } composer = new VCardComposer(mService, vcardType, true); // for test // int vcardType = (VCardConfig.VCARD_TYPE_V21_GENERIC | // VCardConfig.FLAG_USE_QP_TO_PRIMARY_PROPERTIES); // composer = new VCardComposer(ExportVCardActivity.this, vcardType, true); composer.addHandler(composer.new HandlerForOutputStream(outputStream)); final Uri contentUriForRawContactsEntity = RawContactsEntity.CONTENT_URI.buildUpon() .appendQueryParameter(RawContactsEntity.FOR_EXPORT_ONLY, "1") .build(); // TODO: should provide better selection. if (!composer.init(Contacts.CONTENT_URI, new String[] {Contacts._ID}, null, null, null, contentUriForRawContactsEntity)) { final String errorReason = composer.getErrorReason(); Log.e(LOG_TAG, "initialization of vCard composer failed: " + errorReason); final String translatedErrorReason = translateComposerError(errorReason); final String title = mService.getString(R.string.fail_reason_could_not_initialize_exporter, translatedErrorReason); doFinishNotification(title, null); return; } final int total = composer.getCount(); if (total == 0) { final String title = mService.getString(R.string.fail_reason_no_exportable_contact); doFinishNotification(title, null); return; } int current = 1; // 1-origin while (!composer.isAfterLast()) { if (isCancelled()) { Log.i(LOG_TAG, "Export request is cancelled during composing vCard"); return; } - if (!composer.createOneEntry()) { + if (!composer.createOneEntryLegacy()) { final String errorReason = composer.getErrorReason(); Log.e(LOG_TAG, "Failed to read a contact: " + errorReason); final String translatedErrorReason = translateComposerError(errorReason); final String title = mService.getString(R.string.fail_reason_error_occurred_during_export, translatedErrorReason); doFinishNotification(title, null); return; } // vCard export is quite fast (compared to import), and frequent notifications // bother notification bar too much. if (current % 100 == 1) { doProgressNotification(uri, total, current); } current++; } Log.i(LOG_TAG, "Successfully finished exporting vCard " + request.destUri); if (DEBUG) { Log.d(LOG_TAG, "Ask MediaScanner to scan the file: " + request.destUri.getPath()); } mService.updateMediaScanner(request.destUri.getPath()); successful = true; final String filename = uri.getLastPathSegment(); final String title = mService.getString(R.string.exporting_vcard_finished_title, filename); doFinishNotification(title, null); } finally { if (composer != null) { composer.terminate(); } mService.handleFinishExportNotification(mJobId, successful); } } private String translateComposerError(String errorMessage) { final Resources resources = mService.getResources(); if (VCardComposer.FAILURE_REASON_FAILED_TO_GET_DATABASE_INFO.equals(errorMessage)) { return resources.getString(R.string.composer_failed_to_get_database_infomation); } else if (VCardComposer.FAILURE_REASON_NO_ENTRY.equals(errorMessage)) { return resources.getString(R.string.composer_has_no_exportable_contact); } else if (VCardComposer.FAILURE_REASON_NOT_INITIALIZED.equals(errorMessage)) { return resources.getString(R.string.composer_not_initialized); } else { return errorMessage; } } private void doProgressNotification(Uri uri, int totalCount, int currentCount) { final String displayName = uri.getLastPathSegment(); final String description = mService.getString(R.string.exporting_contact_list_message, displayName); final String tickerText = mService.getString(R.string.exporting_contact_list_title); final Notification notification = VCardService.constructProgressNotification(mService, VCardService.TYPE_EXPORT, description, tickerText, mJobId, displayName, totalCount, currentCount); mNotificationManager.notify(mJobId, notification); } private void doCancelNotification() { if (DEBUG) Log.d(LOG_TAG, "send cancel notification"); final String description = mService.getString(R.string.exporting_vcard_canceled_title, mExportRequest.destUri.getLastPathSegment()); final Notification notification = VCardService.constructCancelNotification(mService, description); mNotificationManager.notify(mJobId, notification); } private void doFinishNotification(final String title, final String description) { if (DEBUG) Log.d(LOG_TAG, "send finish notification: " + title + ", " + description); final Intent intent = new Intent(mService, ContactBrowserActivity.class); final Notification notification = VCardService.constructFinishNotification(mService, title, description, intent); mNotificationManager.notify(mJobId, notification); } @Override public synchronized boolean cancel(boolean mayInterruptIfRunning) { if (DEBUG) Log.d(LOG_TAG, "received cancel request"); if (mDone || mCanceled) { return false; } mCanceled = true; return true; } @Override public synchronized boolean isCancelled() { return mCanceled; } @Override public synchronized boolean isDone() { return mDone; } public ExportRequest getRequest() { return mExportRequest; } }
true
true
private void runInternal() { if (DEBUG) Log.d(LOG_TAG, String.format("vCard export (id: %d) has started.", mJobId)); final ExportRequest request = mExportRequest; VCardComposer composer = null; boolean successful = false; try { if (isCancelled()) { Log.i(LOG_TAG, "Export request is cancelled before handling the request"); return; } final Uri uri = request.destUri; final OutputStream outputStream; try { outputStream = mResolver.openOutputStream(uri); } catch (FileNotFoundException e) { Log.w(LOG_TAG, "FileNotFoundException thrown", e); // Need concise title. final String errorReason = mService.getString(R.string.fail_reason_could_not_open_file, uri, e.getMessage()); doFinishNotification(errorReason, null); return; } final String exportType = request.exportType; final int vcardType; if (TextUtils.isEmpty(exportType)) { vcardType = VCardConfig.getVCardTypeFromString( mService.getString(R.string.config_export_vcard_type)); } else { vcardType = VCardConfig.getVCardTypeFromString(exportType); } composer = new VCardComposer(mService, vcardType, true); // for test // int vcardType = (VCardConfig.VCARD_TYPE_V21_GENERIC | // VCardConfig.FLAG_USE_QP_TO_PRIMARY_PROPERTIES); // composer = new VCardComposer(ExportVCardActivity.this, vcardType, true); composer.addHandler(composer.new HandlerForOutputStream(outputStream)); final Uri contentUriForRawContactsEntity = RawContactsEntity.CONTENT_URI.buildUpon() .appendQueryParameter(RawContactsEntity.FOR_EXPORT_ONLY, "1") .build(); // TODO: should provide better selection. if (!composer.init(Contacts.CONTENT_URI, new String[] {Contacts._ID}, null, null, null, contentUriForRawContactsEntity)) { final String errorReason = composer.getErrorReason(); Log.e(LOG_TAG, "initialization of vCard composer failed: " + errorReason); final String translatedErrorReason = translateComposerError(errorReason); final String title = mService.getString(R.string.fail_reason_could_not_initialize_exporter, translatedErrorReason); doFinishNotification(title, null); return; } final int total = composer.getCount(); if (total == 0) { final String title = mService.getString(R.string.fail_reason_no_exportable_contact); doFinishNotification(title, null); return; } int current = 1; // 1-origin while (!composer.isAfterLast()) { if (isCancelled()) { Log.i(LOG_TAG, "Export request is cancelled during composing vCard"); return; } if (!composer.createOneEntry()) { final String errorReason = composer.getErrorReason(); Log.e(LOG_TAG, "Failed to read a contact: " + errorReason); final String translatedErrorReason = translateComposerError(errorReason); final String title = mService.getString(R.string.fail_reason_error_occurred_during_export, translatedErrorReason); doFinishNotification(title, null); return; } // vCard export is quite fast (compared to import), and frequent notifications // bother notification bar too much. if (current % 100 == 1) { doProgressNotification(uri, total, current); } current++; } Log.i(LOG_TAG, "Successfully finished exporting vCard " + request.destUri); if (DEBUG) { Log.d(LOG_TAG, "Ask MediaScanner to scan the file: " + request.destUri.getPath()); } mService.updateMediaScanner(request.destUri.getPath()); successful = true; final String filename = uri.getLastPathSegment(); final String title = mService.getString(R.string.exporting_vcard_finished_title, filename); doFinishNotification(title, null); } finally { if (composer != null) { composer.terminate(); } mService.handleFinishExportNotification(mJobId, successful); } }
private void runInternal() { if (DEBUG) Log.d(LOG_TAG, String.format("vCard export (id: %d) has started.", mJobId)); final ExportRequest request = mExportRequest; VCardComposer composer = null; boolean successful = false; try { if (isCancelled()) { Log.i(LOG_TAG, "Export request is cancelled before handling the request"); return; } final Uri uri = request.destUri; final OutputStream outputStream; try { outputStream = mResolver.openOutputStream(uri); } catch (FileNotFoundException e) { Log.w(LOG_TAG, "FileNotFoundException thrown", e); // Need concise title. final String errorReason = mService.getString(R.string.fail_reason_could_not_open_file, uri, e.getMessage()); doFinishNotification(errorReason, null); return; } final String exportType = request.exportType; final int vcardType; if (TextUtils.isEmpty(exportType)) { vcardType = VCardConfig.getVCardTypeFromString( mService.getString(R.string.config_export_vcard_type)); } else { vcardType = VCardConfig.getVCardTypeFromString(exportType); } composer = new VCardComposer(mService, vcardType, true); // for test // int vcardType = (VCardConfig.VCARD_TYPE_V21_GENERIC | // VCardConfig.FLAG_USE_QP_TO_PRIMARY_PROPERTIES); // composer = new VCardComposer(ExportVCardActivity.this, vcardType, true); composer.addHandler(composer.new HandlerForOutputStream(outputStream)); final Uri contentUriForRawContactsEntity = RawContactsEntity.CONTENT_URI.buildUpon() .appendQueryParameter(RawContactsEntity.FOR_EXPORT_ONLY, "1") .build(); // TODO: should provide better selection. if (!composer.init(Contacts.CONTENT_URI, new String[] {Contacts._ID}, null, null, null, contentUriForRawContactsEntity)) { final String errorReason = composer.getErrorReason(); Log.e(LOG_TAG, "initialization of vCard composer failed: " + errorReason); final String translatedErrorReason = translateComposerError(errorReason); final String title = mService.getString(R.string.fail_reason_could_not_initialize_exporter, translatedErrorReason); doFinishNotification(title, null); return; } final int total = composer.getCount(); if (total == 0) { final String title = mService.getString(R.string.fail_reason_no_exportable_contact); doFinishNotification(title, null); return; } int current = 1; // 1-origin while (!composer.isAfterLast()) { if (isCancelled()) { Log.i(LOG_TAG, "Export request is cancelled during composing vCard"); return; } if (!composer.createOneEntryLegacy()) { final String errorReason = composer.getErrorReason(); Log.e(LOG_TAG, "Failed to read a contact: " + errorReason); final String translatedErrorReason = translateComposerError(errorReason); final String title = mService.getString(R.string.fail_reason_error_occurred_during_export, translatedErrorReason); doFinishNotification(title, null); return; } // vCard export is quite fast (compared to import), and frequent notifications // bother notification bar too much. if (current % 100 == 1) { doProgressNotification(uri, total, current); } current++; } Log.i(LOG_TAG, "Successfully finished exporting vCard " + request.destUri); if (DEBUG) { Log.d(LOG_TAG, "Ask MediaScanner to scan the file: " + request.destUri.getPath()); } mService.updateMediaScanner(request.destUri.getPath()); successful = true; final String filename = uri.getLastPathSegment(); final String title = mService.getString(R.string.exporting_vcard_finished_title, filename); doFinishNotification(title, null); } finally { if (composer != null) { composer.terminate(); } mService.handleFinishExportNotification(mJobId, successful); } }
diff --git a/src/main/java/com/khs/sherpa/processor/RestfulRequestProcessor.java b/src/main/java/com/khs/sherpa/processor/RestfulRequestProcessor.java index dff5f00..9551b28 100644 --- a/src/main/java/com/khs/sherpa/processor/RestfulRequestProcessor.java +++ b/src/main/java/com/khs/sherpa/processor/RestfulRequestProcessor.java @@ -1,117 +1,117 @@ package com.khs.sherpa.processor; /* * Copyright 2012 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. */ import java.lang.reflect.Method; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.reflections.ReflectionUtils; import org.reflections.Reflections; import com.google.common.base.Predicates; import com.khs.sherpa.annotation.Action; import com.khs.sherpa.annotation.Endpoint; import com.khs.sherpa.context.ApplicationContext; import com.khs.sherpa.exception.SherpaEndpointNotFoundException; import com.khs.sherpa.util.MethodUtil; import com.khs.sherpa.util.SherpaPredicates; import com.khs.sherpa.util.UrlUtil; public class RestfulRequestProcessor implements RequestProcessor { private ApplicationContext applicationContext; private Method method; private String path; public RestfulRequestProcessor() { } public RestfulRequestProcessor(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public String getEndpoint(HttpServletRequest request) { Map<String, Object> map = applicationContext.getEndpointTypes(); Collection<Method> methods = new HashSet<Method>(); for(Entry<String, Object> entry: map.entrySet()) { Collection<Method> m = Reflections.getAllMethods(entry.getValue().getClass(), Predicates.and( ReflectionUtils.withAnnotation(Action.class), SherpaPredicates.withActionMappingPattern(UrlUtil.getPath(request)) ) ); methods.addAll(m); } method = MethodUtil.validateHttpMethods(methods.toArray(new Method[] {}), request.getMethod()); - Class<?> type = method.getDeclaringClass(); if(method != null) { + Class<?> type = method.getDeclaringClass(); if(type.isAnnotationPresent(Endpoint.class)) { if(StringUtils.isNotEmpty(type.getAnnotation(Endpoint.class).value())) { return type.getAnnotation(Endpoint.class).value(); } } return type.getSimpleName(); } throw new SherpaEndpointNotFoundException("no endpoint for url [" + UrlUtil.getPath(request) + "]"); } public String getAction(HttpServletRequest request) { final Pattern pattern = Pattern.compile("\\{\\d?\\w+\\}"); Matcher matcher = null; if(method.isAnnotationPresent(Action.class)) { for(String url: method.getAnnotation(Action.class).mapping()) { matcher = pattern.matcher(url); if(Pattern.matches(matcher.replaceAll("[^/]*"), UrlUtil.getPath(request))) { path = url; } } } return MethodUtil.getMethodName(method); } public String getParmeter(HttpServletRequest request, String value) { String currentUrl = UrlUtil.getPath(request); Pattern pattern = Pattern.compile("(\\{\\w+\\})"); Matcher matcher = pattern.matcher(path); int cnt = 0; while(matcher.find()) { if(matcher.group().equals("{"+value+"}")) { String matcherText = matcher.replaceAll("([^/]*)"); pattern = Pattern.compile(matcherText); matcher = pattern.matcher(currentUrl); matcher.find(); return matcher.group(cnt+1); } cnt++; } return null; } public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }
false
true
public String getEndpoint(HttpServletRequest request) { Map<String, Object> map = applicationContext.getEndpointTypes(); Collection<Method> methods = new HashSet<Method>(); for(Entry<String, Object> entry: map.entrySet()) { Collection<Method> m = Reflections.getAllMethods(entry.getValue().getClass(), Predicates.and( ReflectionUtils.withAnnotation(Action.class), SherpaPredicates.withActionMappingPattern(UrlUtil.getPath(request)) ) ); methods.addAll(m); } method = MethodUtil.validateHttpMethods(methods.toArray(new Method[] {}), request.getMethod()); Class<?> type = method.getDeclaringClass(); if(method != null) { if(type.isAnnotationPresent(Endpoint.class)) { if(StringUtils.isNotEmpty(type.getAnnotation(Endpoint.class).value())) { return type.getAnnotation(Endpoint.class).value(); } } return type.getSimpleName(); } throw new SherpaEndpointNotFoundException("no endpoint for url [" + UrlUtil.getPath(request) + "]"); }
public String getEndpoint(HttpServletRequest request) { Map<String, Object> map = applicationContext.getEndpointTypes(); Collection<Method> methods = new HashSet<Method>(); for(Entry<String, Object> entry: map.entrySet()) { Collection<Method> m = Reflections.getAllMethods(entry.getValue().getClass(), Predicates.and( ReflectionUtils.withAnnotation(Action.class), SherpaPredicates.withActionMappingPattern(UrlUtil.getPath(request)) ) ); methods.addAll(m); } method = MethodUtil.validateHttpMethods(methods.toArray(new Method[] {}), request.getMethod()); if(method != null) { Class<?> type = method.getDeclaringClass(); if(type.isAnnotationPresent(Endpoint.class)) { if(StringUtils.isNotEmpty(type.getAnnotation(Endpoint.class).value())) { return type.getAnnotation(Endpoint.class).value(); } } return type.getSimpleName(); } throw new SherpaEndpointNotFoundException("no endpoint for url [" + UrlUtil.getPath(request) + "]"); }
diff --git a/ghana-national-xforms/src/main/java/org/motechproject/ghana/national/handlers/PatientRegistrationFormHandler.java b/ghana-national-xforms/src/main/java/org/motechproject/ghana/national/handlers/PatientRegistrationFormHandler.java index b986e616..e1bb8e9b 100644 --- a/ghana-national-xforms/src/main/java/org/motechproject/ghana/national/handlers/PatientRegistrationFormHandler.java +++ b/ghana-national-xforms/src/main/java/org/motechproject/ghana/national/handlers/PatientRegistrationFormHandler.java @@ -1,138 +1,138 @@ package org.motechproject.ghana.national.handlers; import org.motechproject.ghana.national.bean.RegisterClientForm; import org.motechproject.ghana.national.domain.*; import org.motechproject.ghana.national.domain.mobilemidwife.MobileMidwifeEnrollment; import org.motechproject.ghana.national.repository.SMSGateway; import org.motechproject.ghana.national.service.CareService; import org.motechproject.ghana.national.service.FacilityService; import org.motechproject.ghana.national.service.MobileMidwifeService; import org.motechproject.ghana.national.service.PatientService; import org.motechproject.ghana.national.tools.Utility; import org.motechproject.ghana.national.vo.ANCVO; import org.motechproject.ghana.national.vo.CwcVO; import org.motechproject.mobileforms.api.callbacks.FormPublishHandler; import org.motechproject.model.MotechEvent; import org.motechproject.mrs.model.Attribute; import org.motechproject.mrs.model.MRSFacility; import org.motechproject.mrs.model.MRSPatient; import org.motechproject.mrs.model.MRSPerson; import org.motechproject.openmrs.advice.ApiSession; import org.motechproject.openmrs.advice.LoginAsAdmin; import org.motechproject.server.event.annotations.MotechListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import static org.motechproject.ghana.national.domain.SmsTemplateKeys.REGISTER_SUCCESS_SMS_KEY; @Component public class PatientRegistrationFormHandler implements FormPublishHandler { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired private PatientService patientService; @Autowired private CareService careService; @Autowired private MobileMidwifeService mobileMidwifeService; @Autowired private FacilityService facilityService; @Autowired private SMSGateway smsGateway; @Override @MotechListener(subjects = "form.validation.successful.NurseDataEntry.registerPatient") @LoginAsAdmin @ApiSession public void handleFormEvent(MotechEvent event) { try { RegisterClientForm registerClientForm = (RegisterClientForm) event.getParameters().get(Constants.FORM_BEAN); MRSPerson mrsPerson = new MRSPerson(). firstName(registerClientForm.getFirstName()). middleName(registerClientForm.getMiddleName()). lastName(registerClientForm.getLastName()). dateOfBirth(registerClientForm.getDateOfBirth()). birthDateEstimated(registerClientForm.getEstimatedBirthDate()). gender(registerClientForm.getSex()). address(registerClientForm.getAddress()). attributes(getPatientAttributes(registerClientForm)); String facilityId = facilityService.getFacilityByMotechId(registerClientForm.getFacilityId()).mrsFacilityId(); MRSPatient mrsPatient = new MRSPatient(registerClientForm.getMotechId(), mrsPerson, new MRSFacility(facilityId)); Patient patient = new Patient(mrsPatient, registerClientForm.getMotherMotechId()); final Patient savedPatient = patientService.registerPatient(patient, registerClientForm.getStaffId()); registerForMobileMidwifeProgram(registerClientForm, savedPatient.getMotechId()); registerForCWC(registerClientForm, facilityId, savedPatient.getMotechId()); registerForANC(registerClientForm, facilityId, savedPatient.getMotechId()); if (registerClientForm.getSender() != null) { smsGateway.dispatchSMS(REGISTER_SUCCESS_SMS_KEY, - new SMSTemplate().fillPatientDetails(patient).getRuntimeVariables(), registerClientForm.getSender()); + new SMSTemplate().fillPatientDetails(savedPatient).getRuntimeVariables(), registerClientForm.getSender()); } } catch (Exception e) { log.error("Exception while saving patient", e); } } private void registerForMobileMidwifeProgram(RegisterClientForm registerClientForm, String patientMotechId) { if (registerClientForm.isEnrolledForMobileMidwifeProgram()) { MobileMidwifeEnrollment mobileMidwifeEnrollment = registerClientForm.createMobileMidwifeEnrollment(patientMotechId); mobileMidwifeEnrollment.setFacilityId(registerClientForm.getFacilityId()); mobileMidwifeService.register(mobileMidwifeEnrollment); } } private void registerForANC(RegisterClientForm registerClientForm, String facilityId, String patientMotechId) { if (PatientType.PREGNANT_MOTHER.equals(registerClientForm.getRegistrantType())) { ANCVO ancVO = new ANCVO(registerClientForm.getStaffId(), facilityId, patientMotechId, registerClientForm.getDate() , RegistrationToday.TODAY, registerClientForm.getAncRegNumber(), registerClientForm.getExpDeliveryDate(), registerClientForm.getHeight(), registerClientForm.getGravida(), registerClientForm.getParity(), registerClientForm.getAddHistory(), registerClientForm.getDeliveryDateConfirmed(), registerClientForm.getAncCareHistories(), registerClientForm.getLastIPT(), registerClientForm.getLastTT(), registerClientForm.getLastIPTDate(), registerClientForm.getLastTTDate(), registerClientForm.getAddHistory()); careService.enroll(ancVO); } } private void registerForCWC(RegisterClientForm registerClientForm, String facilityId, String patientMotechId) { if (registerClientForm.getRegistrantType().equals(PatientType.CHILD_UNDER_FIVE)) { CwcVO cwcVO = new CwcVO(registerClientForm.getStaffId(), facilityId, registerClientForm.getDate(), patientMotechId, registerClientForm.getCWCCareHistories(), registerClientForm.getBcgDate(), registerClientForm.getLastVitaminADate(), registerClientForm.getMeaslesDate(), registerClientForm.getYellowFeverDate(), registerClientForm.getLastPentaDate(), registerClientForm.getLastPenta(), registerClientForm.getLastOPVDate(), registerClientForm.getLastOPV(), registerClientForm.getLastIPTiDate(), registerClientForm.getLastIPTi(), registerClientForm.getCwcRegNumber(), registerClientForm.getAddHistory()); careService.enroll(cwcVO); } } private List<Attribute> getPatientAttributes (RegisterClientForm registerClientForm) { List<Attribute> attributes = new ArrayList<Attribute>(); attributes.add(new Attribute(PatientAttributes.PHONE_NUMBER.getAttribute(), registerClientForm.getPhoneNumber())); Date nhisExpirationDate = registerClientForm.getNhisExpires(); if (nhisExpirationDate != null) { attributes.add(new Attribute(PatientAttributes.NHIS_EXPIRY_DATE.getAttribute(), new SimpleDateFormat(Constants.PATTERN_YYYY_MM_DD).format(nhisExpirationDate))); } attributes.add(new Attribute(PatientAttributes.NHIS_NUMBER.getAttribute(), registerClientForm.getNhis())); attributes.add(new Attribute(PatientAttributes.INSURED.getAttribute(), Utility.safeToString(registerClientForm.getInsured()))); return attributes; } }
true
true
public void handleFormEvent(MotechEvent event) { try { RegisterClientForm registerClientForm = (RegisterClientForm) event.getParameters().get(Constants.FORM_BEAN); MRSPerson mrsPerson = new MRSPerson(). firstName(registerClientForm.getFirstName()). middleName(registerClientForm.getMiddleName()). lastName(registerClientForm.getLastName()). dateOfBirth(registerClientForm.getDateOfBirth()). birthDateEstimated(registerClientForm.getEstimatedBirthDate()). gender(registerClientForm.getSex()). address(registerClientForm.getAddress()). attributes(getPatientAttributes(registerClientForm)); String facilityId = facilityService.getFacilityByMotechId(registerClientForm.getFacilityId()).mrsFacilityId(); MRSPatient mrsPatient = new MRSPatient(registerClientForm.getMotechId(), mrsPerson, new MRSFacility(facilityId)); Patient patient = new Patient(mrsPatient, registerClientForm.getMotherMotechId()); final Patient savedPatient = patientService.registerPatient(patient, registerClientForm.getStaffId()); registerForMobileMidwifeProgram(registerClientForm, savedPatient.getMotechId()); registerForCWC(registerClientForm, facilityId, savedPatient.getMotechId()); registerForANC(registerClientForm, facilityId, savedPatient.getMotechId()); if (registerClientForm.getSender() != null) { smsGateway.dispatchSMS(REGISTER_SUCCESS_SMS_KEY, new SMSTemplate().fillPatientDetails(patient).getRuntimeVariables(), registerClientForm.getSender()); } } catch (Exception e) { log.error("Exception while saving patient", e); } }
public void handleFormEvent(MotechEvent event) { try { RegisterClientForm registerClientForm = (RegisterClientForm) event.getParameters().get(Constants.FORM_BEAN); MRSPerson mrsPerson = new MRSPerson(). firstName(registerClientForm.getFirstName()). middleName(registerClientForm.getMiddleName()). lastName(registerClientForm.getLastName()). dateOfBirth(registerClientForm.getDateOfBirth()). birthDateEstimated(registerClientForm.getEstimatedBirthDate()). gender(registerClientForm.getSex()). address(registerClientForm.getAddress()). attributes(getPatientAttributes(registerClientForm)); String facilityId = facilityService.getFacilityByMotechId(registerClientForm.getFacilityId()).mrsFacilityId(); MRSPatient mrsPatient = new MRSPatient(registerClientForm.getMotechId(), mrsPerson, new MRSFacility(facilityId)); Patient patient = new Patient(mrsPatient, registerClientForm.getMotherMotechId()); final Patient savedPatient = patientService.registerPatient(patient, registerClientForm.getStaffId()); registerForMobileMidwifeProgram(registerClientForm, savedPatient.getMotechId()); registerForCWC(registerClientForm, facilityId, savedPatient.getMotechId()); registerForANC(registerClientForm, facilityId, savedPatient.getMotechId()); if (registerClientForm.getSender() != null) { smsGateway.dispatchSMS(REGISTER_SUCCESS_SMS_KEY, new SMSTemplate().fillPatientDetails(savedPatient).getRuntimeVariables(), registerClientForm.getSender()); } } catch (Exception e) { log.error("Exception while saving patient", e); } }
diff --git a/nimbits_gae/src/main/java/com/nimbits/server/api/impl/VersionApi.java b/nimbits_gae/src/main/java/com/nimbits/server/api/impl/VersionApi.java index f8ad13b9..3ae7ef6b 100644 --- a/nimbits_gae/src/main/java/com/nimbits/server/api/impl/VersionApi.java +++ b/nimbits_gae/src/main/java/com/nimbits/server/api/impl/VersionApi.java @@ -1,46 +1,46 @@ /* * Copyright (c) 2013 Nimbits 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 expressed or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.nimbits.server.api.impl; import com.nimbits.client.enums.SettingType; import com.nimbits.server.api.ApiBase; import com.nimbits.server.api.ValueApi; import com.nimbits.server.transaction.settings.SettingServiceFactory; 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.logging.Logger; /** * Author: Benjamin Sautner * Date: 1/13/13 * Time: 1:13 PM */ public class VersionApi extends ApiBase { final Logger log = Logger.getLogger(ValueApi.class.getName()); @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); - super.setup(req, resp); + super.setup(resp); out.print(SettingServiceFactory.getServiceInstance(engine).getSetting(SettingType.version)); out.close(); } }
true
true
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); super.setup(req, resp); out.print(SettingServiceFactory.getServiceInstance(engine).getSetting(SettingType.version)); out.close(); }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); super.setup(resp); out.print(SettingServiceFactory.getServiceInstance(engine).getSetting(SettingType.version)); out.close(); }
diff --git a/src/main/java/org/bitstrings/maven/plugins/splasher/DrawImagesFromText.java b/src/main/java/org/bitstrings/maven/plugins/splasher/DrawImagesFromText.java index 7803a68..113b111 100644 --- a/src/main/java/org/bitstrings/maven/plugins/splasher/DrawImagesFromText.java +++ b/src/main/java/org/bitstrings/maven/plugins/splasher/DrawImagesFromText.java @@ -1,101 +1,101 @@ package org.bitstrings.maven.plugins.splasher; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.bitstrings.maven.plugins.splasher.FlowLayout.Alignment; public class DrawImagesFromText extends Drawable { // - parameters --[ private String text; private String imageNamePrefix; private int padding; private Alignment alignment = Alignment.HORIZONTAL; // ]-- protected FlowLayout drawImagesFromText; public String getText() { return text; } public String getImageNamePrefix() { return imageNamePrefix; } public int getPadding() { return padding; } public Alignment getAlignment() { return alignment; } @Override public void init( Graphics2D g ) throws MojoExecutionException { - final FlowLayout flowLayout = new FlowLayout(); + drawImagesFromText = new FlowLayout(); - flowLayout.setDrawingContext( dwContext ); - flowLayout.setPosition( getPosition() ); - flowLayout.setAlignment( alignment ); - flowLayout.setPadding( padding ); + drawImagesFromText.setDrawingContext( dwContext ); + drawImagesFromText.setPosition( getPosition() ); + drawImagesFromText.setAlignment( alignment ); + drawImagesFromText.setPadding( padding ); final List<Drawable> drawables = new ArrayList<Drawable>(); for ( int i = 0; i < text.length(); i++ ) { DrawImage drawImage = new DrawImage(); drawImage.setImageName( imageNamePrefix + text.charAt( i ) ); drawables.add( drawImage ); } - flowLayout.setDraw( drawables ); + drawImagesFromText.setDraw( drawables ); super.init( g ); Graphics2D sg = (Graphics2D) g.create(); try { drawImagesFromText.init( sg ); } finally { sg.dispose(); } } @Override public void draw( Graphics2D g ) { super.draw( g ); Graphics2D sg = (Graphics2D) g.create(); try { drawImagesFromText.draw( sg ); } finally { sg.dispose(); } } }
false
true
public void init( Graphics2D g ) throws MojoExecutionException { final FlowLayout flowLayout = new FlowLayout(); flowLayout.setDrawingContext( dwContext ); flowLayout.setPosition( getPosition() ); flowLayout.setAlignment( alignment ); flowLayout.setPadding( padding ); final List<Drawable> drawables = new ArrayList<Drawable>(); for ( int i = 0; i < text.length(); i++ ) { DrawImage drawImage = new DrawImage(); drawImage.setImageName( imageNamePrefix + text.charAt( i ) ); drawables.add( drawImage ); } flowLayout.setDraw( drawables ); super.init( g ); Graphics2D sg = (Graphics2D) g.create(); try { drawImagesFromText.init( sg ); } finally { sg.dispose(); } }
public void init( Graphics2D g ) throws MojoExecutionException { drawImagesFromText = new FlowLayout(); drawImagesFromText.setDrawingContext( dwContext ); drawImagesFromText.setPosition( getPosition() ); drawImagesFromText.setAlignment( alignment ); drawImagesFromText.setPadding( padding ); final List<Drawable> drawables = new ArrayList<Drawable>(); for ( int i = 0; i < text.length(); i++ ) { DrawImage drawImage = new DrawImage(); drawImage.setImageName( imageNamePrefix + text.charAt( i ) ); drawables.add( drawImage ); } drawImagesFromText.setDraw( drawables ); super.init( g ); Graphics2D sg = (Graphics2D) g.create(); try { drawImagesFromText.init( sg ); } finally { sg.dispose(); } }
diff --git a/src/test/java/com/github/stinkbird/helpspot/private_api/TestHelpSpot.java b/src/test/java/com/github/stinkbird/helpspot/private_api/TestHelpSpot.java index 3d52cae..0b08eca 100644 --- a/src/test/java/com/github/stinkbird/helpspot/private_api/TestHelpSpot.java +++ b/src/test/java/com/github/stinkbird/helpspot/private_api/TestHelpSpot.java @@ -1,88 +1,85 @@ package com.github.stinkbird.helpspot.private_api; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyManagementException; import java.security.KeyStore; import java.util.Properties; import javax.xml.bind.JAXBException; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import com.github.stinkbird.helpspot.common.FakeSslClientSocketFactory; import com.github.stinkbird.helpspot.common.KeystoreCertSslClientSocketFactory; public class TestHelpSpot { private static final Properties properties = new Properties(); private static String helpSpotHostNameOrIPAddress; private static int portNumber; private static boolean isSecureHttp; private static boolean isUseFakeCertificate; private static String keystoreFileNameWithFullPath; private static String helpSpotAdminUsername; private static String helpSpotAdminPassword; private static boolean proceed = true; static { try { properties.load(TestHelpSpot.class.getResourceAsStream("HelpSpot.properties")); helpSpotHostNameOrIPAddress = properties.getProperty("helpSpotHostNameOrIPAddress"); portNumber = Integer.parseInt(properties.getProperty("portNumber")); isSecureHttp = Boolean.parseBoolean(properties.getProperty("isSecureHttp")); isUseFakeCertificate = Boolean.parseBoolean(properties.getProperty("isUseFakeCertificate")); keystoreFileNameWithFullPath = properties.getProperty("keystoreFileNameWithFullPath"); helpSpotAdminUsername = properties.getProperty("helpSpotAdminUsername"); helpSpotAdminPassword = properties.getProperty("helpSpotAdminPassword"); } catch (Throwable t) { t.printStackTrace(); proceed = false; } } private static ProtocolSocketFactory createProtocolSocketFactoryFromKeyStoreFile(String fullPathOfKeyStoreFile) throws IOException, KeyManagementException, GeneralSecurityException { FileInputStream fIn = new FileInputStream(fullPathOfKeyStoreFile); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(fIn, null); return new KeystoreCertSslClientSocketFactory(keystore); } public static void main(String[] args) throws IOException, GeneralSecurityException, JAXBException { if(proceed) { ProtocolSocketFactory protocolSocketFactory = null; if(isSecureHttp) { if(isUseFakeCertificate) { protocolSocketFactory = new FakeSslClientSocketFactory(); } else { - FileInputStream fIn = new FileInputStream(keystoreFileNameWithFullPath); - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(fIn, null); - protocolSocketFactory = new KeystoreCertSslClientSocketFactory(keystore); + protocolSocketFactory = createProtocolSocketFactoryFromKeyStoreFile(keystoreFileNameWithFullPath); } } com.github.stinkbird.helpspot.private_api.PrivateApiUtil privateApiUtil = com.github.stinkbird.helpspot.private_api.PrivateApiUtil.getInstanceOf( helpSpotHostNameOrIPAddress, portNumber, isSecureHttp, protocolSocketFactory, helpSpotAdminUsername, helpSpotAdminPassword ); com.github.stinkbird.helpspot.private_api.response_for.request.search.Requests allCustomerRequests = privateApiUtil.callPrivateRequestSearch("", true); System.out.println("\nRequests contains total = " + allCustomerRequests.getRequest().size() + " historical request for customer"); System.out.println("\nFirst xRequest is " + allCustomerRequests.getRequest().get(0).getXRequest() + ". \n"); } else { System.out.println(false); } } }
true
true
public static void main(String[] args) throws IOException, GeneralSecurityException, JAXBException { if(proceed) { ProtocolSocketFactory protocolSocketFactory = null; if(isSecureHttp) { if(isUseFakeCertificate) { protocolSocketFactory = new FakeSslClientSocketFactory(); } else { FileInputStream fIn = new FileInputStream(keystoreFileNameWithFullPath); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(fIn, null); protocolSocketFactory = new KeystoreCertSslClientSocketFactory(keystore); } } com.github.stinkbird.helpspot.private_api.PrivateApiUtil privateApiUtil = com.github.stinkbird.helpspot.private_api.PrivateApiUtil.getInstanceOf( helpSpotHostNameOrIPAddress, portNumber, isSecureHttp, protocolSocketFactory, helpSpotAdminUsername, helpSpotAdminPassword ); com.github.stinkbird.helpspot.private_api.response_for.request.search.Requests allCustomerRequests = privateApiUtil.callPrivateRequestSearch("", true); System.out.println("\nRequests contains total = " + allCustomerRequests.getRequest().size() + " historical request for customer"); System.out.println("\nFirst xRequest is " + allCustomerRequests.getRequest().get(0).getXRequest() + ". \n"); } else { System.out.println(false); } }
public static void main(String[] args) throws IOException, GeneralSecurityException, JAXBException { if(proceed) { ProtocolSocketFactory protocolSocketFactory = null; if(isSecureHttp) { if(isUseFakeCertificate) { protocolSocketFactory = new FakeSslClientSocketFactory(); } else { protocolSocketFactory = createProtocolSocketFactoryFromKeyStoreFile(keystoreFileNameWithFullPath); } } com.github.stinkbird.helpspot.private_api.PrivateApiUtil privateApiUtil = com.github.stinkbird.helpspot.private_api.PrivateApiUtil.getInstanceOf( helpSpotHostNameOrIPAddress, portNumber, isSecureHttp, protocolSocketFactory, helpSpotAdminUsername, helpSpotAdminPassword ); com.github.stinkbird.helpspot.private_api.response_for.request.search.Requests allCustomerRequests = privateApiUtil.callPrivateRequestSearch("", true); System.out.println("\nRequests contains total = " + allCustomerRequests.getRequest().size() + " historical request for customer"); System.out.println("\nFirst xRequest is " + allCustomerRequests.getRequest().get(0).getXRequest() + ". \n"); } else { System.out.println(false); } }
diff --git a/seng403/src/gui/LessonsTab.java b/seng403/src/gui/LessonsTab.java index db069e5..b3a815c 100644 --- a/seng403/src/gui/LessonsTab.java +++ b/seng403/src/gui/LessonsTab.java @@ -1,158 +1,157 @@ package gui; import java.awt.Color; import java.awt.EventQueue; import javax.swing.JFrame; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.RowSpec; import com.jgoodies.forms.factories.FormFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.JLabel; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.FlowLayout; public class LessonsTab { private JPanel LessonsTab; private String Selection; /** * Create the application. */ public LessonsTab() { LessonsTab = new JPanel(); initialize(); } /** * Initialize the contents of the frame. * @return */ public JPanel initialize() { LessonsTab.setBounds(100, 100, 450, 300); LessonsTab.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(44dlu;pref)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(39dlu;pref)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("8dlu:grow"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(7dlu;default):grow"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(10dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(9dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(9dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,}, new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("default:grow"), FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,})); JButton StartLessonButton = new JButton("Start Lesson"); StartLessonButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(Selection.startsWith("Chapter") || Selection.compareTo("Lessons") == 0 || Selection == null) return; else { LessonWindow NewWindow = new LessonWindow(Selection); NewWindow.OpenWindow(); } } }); LessonsTab.add(StartLessonButton, "2, 2, 3, 1"); JScrollPane PreviewPane = new JScrollPane(); LessonsTab.add(PreviewPane, "6, 2, 17, 15, fill, fill"); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); PreviewPane.setViewportView(panel); panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); String imgStr = "Lessons/LessonsPreview.png"; final ImageIcon LessonsTitle = new ImageIcon(imgStr); final JLabel LessonPreviewLabel = new JLabel("", LessonsTitle, JLabel.CENTER); panel.add(LessonPreviewLabel); JScrollPane TreePane = new JScrollPane(); LessonsTab.add(TreePane, "2, 4, 3, 13, fill, fill"); final JTree LessonsTree = new JTree(); LessonsTree.setModel(new DefaultTreeModel( new DefaultMutableTreeNode("Lessons") { { DefaultMutableTreeNode node_1; node_1 = new DefaultMutableTreeNode("Chapter 1"); node_1.add(new DefaultMutableTreeNode("Lesson 1.0")); - node_1.add(new DefaultMutableTreeNode("Lesson 1.1")); node_1.add(new DefaultMutableTreeNode("History of Lisp")); node_1.add(new DefaultMutableTreeNode("Modern Lisp")); node_1.add(new DefaultMutableTreeNode("Future of Lisp")); add(node_1); node_1 = new DefaultMutableTreeNode("Chapter 2"); node_1.add(new DefaultMutableTreeNode("Lesson 2.1")); node_1.add(new DefaultMutableTreeNode("Lesson 2.2")); node_1.add(new DefaultMutableTreeNode("Lesson 2.3")); node_1.add(new DefaultMutableTreeNode("Lesson 2.4")); add(node_1); node_1 = new DefaultMutableTreeNode("Chapter 3"); node_1.add(new DefaultMutableTreeNode("Lesson 3.1")); node_1.add(new DefaultMutableTreeNode("Lesson 3.2")); node_1.add(new DefaultMutableTreeNode("Lesson 3.3")); node_1.add(new DefaultMutableTreeNode("Lesson 3.4")); add(node_1); } } )); TreePane.setViewportView(LessonsTree); LessonsTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) LessonsTree.getLastSelectedPathComponent(); Object nodeInfo = node.getUserObject(); Selection = nodeInfo.toString(); - String imgStr = "Lessons/" + Selection + "Preview" + ".png"; + String imgStr = "Lessons/" + Selection + ".png"; final ImageIcon LessonPreview = new ImageIcon(imgStr); LessonPreviewLabel.setIcon(LessonPreview); } }); return LessonsTab; } }
false
true
public JPanel initialize() { LessonsTab.setBounds(100, 100, 450, 300); LessonsTab.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(44dlu;pref)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(39dlu;pref)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("8dlu:grow"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(7dlu;default):grow"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(10dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(9dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(9dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,}, new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("default:grow"), FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,})); JButton StartLessonButton = new JButton("Start Lesson"); StartLessonButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(Selection.startsWith("Chapter") || Selection.compareTo("Lessons") == 0 || Selection == null) return; else { LessonWindow NewWindow = new LessonWindow(Selection); NewWindow.OpenWindow(); } } }); LessonsTab.add(StartLessonButton, "2, 2, 3, 1"); JScrollPane PreviewPane = new JScrollPane(); LessonsTab.add(PreviewPane, "6, 2, 17, 15, fill, fill"); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); PreviewPane.setViewportView(panel); panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); String imgStr = "Lessons/LessonsPreview.png"; final ImageIcon LessonsTitle = new ImageIcon(imgStr); final JLabel LessonPreviewLabel = new JLabel("", LessonsTitle, JLabel.CENTER); panel.add(LessonPreviewLabel); JScrollPane TreePane = new JScrollPane(); LessonsTab.add(TreePane, "2, 4, 3, 13, fill, fill"); final JTree LessonsTree = new JTree(); LessonsTree.setModel(new DefaultTreeModel( new DefaultMutableTreeNode("Lessons") { { DefaultMutableTreeNode node_1; node_1 = new DefaultMutableTreeNode("Chapter 1"); node_1.add(new DefaultMutableTreeNode("Lesson 1.0")); node_1.add(new DefaultMutableTreeNode("Lesson 1.1")); node_1.add(new DefaultMutableTreeNode("History of Lisp")); node_1.add(new DefaultMutableTreeNode("Modern Lisp")); node_1.add(new DefaultMutableTreeNode("Future of Lisp")); add(node_1); node_1 = new DefaultMutableTreeNode("Chapter 2"); node_1.add(new DefaultMutableTreeNode("Lesson 2.1")); node_1.add(new DefaultMutableTreeNode("Lesson 2.2")); node_1.add(new DefaultMutableTreeNode("Lesson 2.3")); node_1.add(new DefaultMutableTreeNode("Lesson 2.4")); add(node_1); node_1 = new DefaultMutableTreeNode("Chapter 3"); node_1.add(new DefaultMutableTreeNode("Lesson 3.1")); node_1.add(new DefaultMutableTreeNode("Lesson 3.2")); node_1.add(new DefaultMutableTreeNode("Lesson 3.3")); node_1.add(new DefaultMutableTreeNode("Lesson 3.4")); add(node_1); } } )); TreePane.setViewportView(LessonsTree); LessonsTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) LessonsTree.getLastSelectedPathComponent(); Object nodeInfo = node.getUserObject(); Selection = nodeInfo.toString(); String imgStr = "Lessons/" + Selection + "Preview" + ".png"; final ImageIcon LessonPreview = new ImageIcon(imgStr); LessonPreviewLabel.setIcon(LessonPreview); } }); return LessonsTab; }
public JPanel initialize() { LessonsTab.setBounds(100, 100, 450, 300); LessonsTab.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(44dlu;pref)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(39dlu;pref)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("8dlu:grow"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(7dlu;default):grow"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(10dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(9dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(9dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,}, new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("default:grow"), FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,})); JButton StartLessonButton = new JButton("Start Lesson"); StartLessonButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(Selection.startsWith("Chapter") || Selection.compareTo("Lessons") == 0 || Selection == null) return; else { LessonWindow NewWindow = new LessonWindow(Selection); NewWindow.OpenWindow(); } } }); LessonsTab.add(StartLessonButton, "2, 2, 3, 1"); JScrollPane PreviewPane = new JScrollPane(); LessonsTab.add(PreviewPane, "6, 2, 17, 15, fill, fill"); JPanel panel = new JPanel(); panel.setBackground(Color.WHITE); PreviewPane.setViewportView(panel); panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); String imgStr = "Lessons/LessonsPreview.png"; final ImageIcon LessonsTitle = new ImageIcon(imgStr); final JLabel LessonPreviewLabel = new JLabel("", LessonsTitle, JLabel.CENTER); panel.add(LessonPreviewLabel); JScrollPane TreePane = new JScrollPane(); LessonsTab.add(TreePane, "2, 4, 3, 13, fill, fill"); final JTree LessonsTree = new JTree(); LessonsTree.setModel(new DefaultTreeModel( new DefaultMutableTreeNode("Lessons") { { DefaultMutableTreeNode node_1; node_1 = new DefaultMutableTreeNode("Chapter 1"); node_1.add(new DefaultMutableTreeNode("Lesson 1.0")); node_1.add(new DefaultMutableTreeNode("History of Lisp")); node_1.add(new DefaultMutableTreeNode("Modern Lisp")); node_1.add(new DefaultMutableTreeNode("Future of Lisp")); add(node_1); node_1 = new DefaultMutableTreeNode("Chapter 2"); node_1.add(new DefaultMutableTreeNode("Lesson 2.1")); node_1.add(new DefaultMutableTreeNode("Lesson 2.2")); node_1.add(new DefaultMutableTreeNode("Lesson 2.3")); node_1.add(new DefaultMutableTreeNode("Lesson 2.4")); add(node_1); node_1 = new DefaultMutableTreeNode("Chapter 3"); node_1.add(new DefaultMutableTreeNode("Lesson 3.1")); node_1.add(new DefaultMutableTreeNode("Lesson 3.2")); node_1.add(new DefaultMutableTreeNode("Lesson 3.3")); node_1.add(new DefaultMutableTreeNode("Lesson 3.4")); add(node_1); } } )); TreePane.setViewportView(LessonsTree); LessonsTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) LessonsTree.getLastSelectedPathComponent(); Object nodeInfo = node.getUserObject(); Selection = nodeInfo.toString(); String imgStr = "Lessons/" + Selection + ".png"; final ImageIcon LessonPreview = new ImageIcon(imgStr); LessonPreviewLabel.setIcon(LessonPreview); } }); return LessonsTab; }
diff --git a/src/main/java/org/jboss/as/plugin/Undeploy.java b/src/main/java/org/jboss/as/plugin/Undeploy.java index 96165e7..d926e26 100644 --- a/src/main/java/org/jboss/as/plugin/Undeploy.java +++ b/src/main/java/org/jboss/as/plugin/Undeploy.java @@ -1,78 +1,78 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.plugin; import java.io.IOException; import org.jboss.as.server.client.api.deployment.DeploymentPlan; import org.jboss.as.server.client.api.deployment.DeploymentPlanBuilder; /** * Undeploys the archived result of the project from application server. * <p> * Example Usage: {@literal * <build> * <plugins> * ... * <plugin> * <groupId>org.jboss.as.plugins</groupId> * <artifactId>jboss-as-deploy-plugin</artifactId> * <version>1.0.0-SNAPSHOT</version> * <executions> * <execution> * <phase>package</phase> * <goals> * <goal>undeploy</goal> * </goals> * </execution> * </executions> * </plugin> * ... * </plugins> * </build> * } * </p> * * @goal undeploy * * @author James R. Perkins Jr. (jrp) */ public final class Undeploy extends AbstractDeployment { @Override public DeploymentPlan createPlan(final DeploymentPlanBuilder builder) throws IOException { DeploymentPlan plan = null; if (name() == null) { plan = builder.undeploy(filename()).remove(filename()).build(); } else { - plan = builder.undeploy(filename()).remove(name()).build(); + plan = builder.undeploy(name()).remove(name()).build(); } return plan; } @Override public String goal() { return "undeploy"; } }
true
true
public DeploymentPlan createPlan(final DeploymentPlanBuilder builder) throws IOException { DeploymentPlan plan = null; if (name() == null) { plan = builder.undeploy(filename()).remove(filename()).build(); } else { plan = builder.undeploy(filename()).remove(name()).build(); } return plan; }
public DeploymentPlan createPlan(final DeploymentPlanBuilder builder) throws IOException { DeploymentPlan plan = null; if (name() == null) { plan = builder.undeploy(filename()).remove(filename()).build(); } else { plan = builder.undeploy(name()).remove(name()).build(); } return plan; }
diff --git a/src/edu/upenn/cis350/Trace2Learn/Database/DbAdapter.java b/src/edu/upenn/cis350/Trace2Learn/Database/DbAdapter.java index 87d0e60..f1ced1f 100644 --- a/src/edu/upenn/cis350/Trace2Learn/Database/DbAdapter.java +++ b/src/edu/upenn/cis350/Trace2Learn/Database/DbAdapter.java @@ -1,846 +1,858 @@ package edu.upenn.cis350.Trace2Learn.Database; import java.util.ArrayList; import java.util.List; 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.graphics.PointF; import android.util.Log; public class DbAdapter { public static final String CHAR_ROWID = "_id"; public static final String WORDS_ROWID = "_id"; public static final String CHARTAG_ROWID = "_id"; public static final String CHARTAG_TAG= "tag"; public static final String WORDTAG_ROWID = "_id"; public static final String WORDTAG_TAG= "tag"; private static final String TAG = "TagsDbAdapter"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; /** * Database creation sql statement */ private static final String DATABASE_CREATE_CHAR = "CREATE TABLE Character (_id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT);"; private static final String DATABASE_CREATE_CHARTAG = "CREATE TABLE CharacterTag (_id INTEGER, " + "tag TEXT NOT NULL, " + "FOREIGN KEY(_id) REFERENCES Character(_id));"; private static final String DATABASE_CREATE_CHAR_DETAILS = "CREATE TABLE CharacterDetails (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "CharId INTEGER, " + "Stroke INTEGER NOT NULL, " + "PointX DOUBLE NOT NULL, " + "PointY DOUBLE NOT NULL," + "OrderPoint INTEGER NOT NULL, " + "FOREIGN KEY(CharId) REFERENCES Character(_id));"; private static final String DATABASE_CREATE_WORDS = "CREATE TABLE Words (_id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT);"; private static final String DATABASE_CREATE_WORDS_DETAILS = "CREATE TABLE WordsDetails (_id INTEGER," + "CharId INTEGER," + "WordOrder INTEGER NOT NULL," + "FlagUserCreated INTEGER," + "FOREIGN KEY(CharId) REFERENCES Character(_id)," + "FOREIGN KEY(_id) REFERENCES Words(_id));"; private static final String DATABASE_CREATE_WORDSTAG = "CREATE TABLE WordsTag (_id INTEGER, " + "tag TEXT NOT NULL, " + "FOREIGN KEY(_id) REFERENCES Words(_id));"; private static final String DATABASE_CREATE_LESSONS= "CREATE TABLE Lessons (_id INTEGER PRIMARY KEY AUTOINCREMENT,"+ "name TEXT);"; private static final String DATABASE_CREATE_LESSONS_DETAILS = "CREATE TABLE LessonsDetails (" + "LessonId INTEGER, " + "WordId INTEGER," + "LessonOrder INTEGER NOT NULL, " + "FOREIGN KEY(LessonId) REFERENCES Lessons(_id)," + "FOREIGN KEY(WordId) REFERENCES Words(_id));"; private static final String DATABASE_CREATE_LESSONTAG = "CREATE TABLE LessonTag (_id INTEGER, " + "tag TEXT NOT NULL, " + "FOREIGN KEY(_id) REFERENCES Lessons(_id));"; //DB Drop Statements private static final String DATABASE_DROP_CHAR = "DROP TABLE IF EXISTS Character"; private static final String DATABASE_DROP_CHARTAG = "DROP TABLE IF EXISTS CharacterTag"; private static final String DATABASE_DROP_CHAR_DETAILS = "DROP TABLE IF EXISTS CharacterDetails"; private static final String DATABASE_DROP_WORDS = "DROP TABLE IF EXISTS Words"; private static final String DATABASE_DROP_WORDS_DETAILS = "DROP TABLE IF EXISTS WordsDetails"; private static final String DATABASE_DROP_WORDSTAG = "DROP TABLE IF EXISTS WordsTag"; private static final String DATABASE_DROP_LESSONS = "DROP TABLE IF EXISTS Lessons"; private static final String DATABASE_DROP_LESSONS_DETAILS = "DROP TABLE IF EXISTS LessonsDetails"; private static final String DATABASE_DROP_LESSONTAG= "DROP TABLE IF EXISTS LessonTag"; private static final String DATABASE_NAME = "CharTags"; private static final String CHAR_TABLE = "Character"; private static final String CHAR_DETAILS_TABLE = "CharacterDetails"; private static final String CHARTAG_TABLE = "CharacterTag"; private static final String WORDTAG_TABLE = "WordsTag"; private static final String WORDS_TABLE = "Words"; private static final String WORDS_DETAILS_TABLE = "WordsDetails"; private static final String LESSONS_TABLE = "Lessons"; private static final String LESSONS_DETAILS_TABLE = "LessonsDetails"; private static final String LESSONTAG_TABLE = "LessonTag"; private static final int DATABASE_VERSION = 3; private final Context mCtx; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE_CHAR); db.execSQL(DATABASE_CREATE_CHARTAG); db.execSQL(DATABASE_CREATE_CHAR_DETAILS); db.execSQL(DATABASE_CREATE_WORDS); db.execSQL(DATABASE_CREATE_WORDS_DETAILS); db.execSQL(DATABASE_CREATE_WORDSTAG); db.execSQL(DATABASE_CREATE_LESSONS); db.execSQL(DATABASE_CREATE_LESSONS_DETAILS); db.execSQL(DATABASE_CREATE_LESSONTAG); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL(DATABASE_DROP_CHAR); db.execSQL(DATABASE_DROP_CHARTAG); db.execSQL(DATABASE_DROP_CHAR_DETAILS); db.execSQL(DATABASE_DROP_WORDS); db.execSQL(DATABASE_DROP_WORDS_DETAILS); db.execSQL(DATABASE_DROP_WORDSTAG); db.execSQL(DATABASE_DROP_LESSONS); db.execSQL(DATABASE_DROP_LESSONS_DETAILS); db.execSQL(DATABASE_DROP_LESSONTAG); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public DbAdapter(Context ctx) { this.mCtx = ctx; } /** * Open the CharTags database. If it cannot be opened, try to create a new * instance of the database. If it cannot be created, throw an exception to * signal the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws SQLException if the database could be neither opened or created */ public DbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } /** * Create a new character tag. If the character tag is * successfully created return the new rowId for that tag, otherwise return * a -1 to indicate failure. * * @param id the row_id of the tag * @param tag the text of the tag * @return rowId or -1 if failed */ public long createWordTags(long id, String tag) { ContentValues initialValues = new ContentValues(); initialValues.put(WORDTAG_ROWID, id); initialValues.put(WORDTAG_TAG, tag); return mDb.insert(WORDTAG_TABLE, null, initialValues); } /** * Create a new lesson tag. If the lesson tag is * successfully created return the new rowId for that tag, otherwise sreturn * a -1 to indicate failure. * * @param id the row_id of the tag * @param tag the text of the tag * @return rowId or -1 if failed */ public long createLessonTags(long id, String tag) { ContentValues initialValues = new ContentValues(); initialValues.put("_id", id); initialValues.put("tag", tag); return mDb.insert(LESSONTAG_TABLE, null, initialValues); } /** * Create a new word tag. If the tag is * successfully created return the new rowId for that tag, otherwise return * a -1 to indicate failure. * * @param id the row_id of the tag * @param tag the text of the tag * @return rowId or -1 if failed */ public long createTags(long id, String tag) { ContentValues initialValues = new ContentValues(); initialValues.put(CHARTAG_ROWID, id); initialValues.put(CHARTAG_TAG, tag); return mDb.insert(CHARTAG_TABLE, null, initialValues); } /** * Delete the tag with the given rowId and tag * * @param rowId id of tag to delete * @param tag text of tag to delete * @return true if deleted, false otherwise */ public boolean deleteTag(long rowId, String tag) { return mDb.delete(CHARTAG_TABLE, CHARTAG_ROWID + "=" + rowId + " AND " + CHARTAG_TAG+"="+tag, null) > 0; } /** * Delete the word tag with the given rowId and tag * * @param rowId id of tag to delete * @param tag text of tag to delete * @return true if deleted, false otherwise */ public boolean deleteWordTag(long rowId, String tag) { return mDb.delete(WORDTAG_TABLE, WORDTAG_ROWID + "=" + rowId + " AND " + WORDTAG_TAG+"="+tag, null) > 0; } /** * Add a character to the database * @param c character to be added to the database * @return true if character is added to DB. False on error. */ public boolean addCharacter(LessonCharacter c) { mDb.beginTransaction(); //add to CHAR_TABLE ContentValues initialCharValues = new ContentValues(); initializePrivateTag(c,initialCharValues); long id = mDb.insert(CHAR_TABLE, null, initialCharValues); if(id == -1) { //if error Log.e(CHAR_TABLE, "cannot add new character to table "+CHAR_TABLE); mDb.endTransaction(); return false; } Cursor x = mDb.query(CHAR_TABLE, new String[]{CHAR_ROWID}, null, null, null, null, CHAR_ROWID+" DESC", "1"); if (x != null) { x.moveToFirst(); } c.setId(x.getInt(x.getColumnIndexOrThrow(CHAR_ROWID))); //add each stroke to CHAR_DETAILS_TABLE List<Stroke> l = c.getStrokes(); //stroke ordering int strokeNumber=0; for(Stroke s:l) { ContentValues strokeValues = new ContentValues(); strokeValues.put("CharId", id); strokeValues.put("Stroke", strokeNumber); //point ordering int pointNumber=0; for(PointF p : s.getSamplePoints()) { strokeValues.put("PointX", p.x); strokeValues.put("PointY", p.y); strokeValues.put("OrderPoint", pointNumber); long success = mDb.insert(CHAR_DETAILS_TABLE, null, strokeValues); if(success == -1) { //if error Log.e(CHAR_DETAILS_TABLE,"cannot add stroke"); mDb.endTransaction(); return false; } pointNumber++; } strokeNumber++; } //need to add character as a word so that we can add them to lessons as not part of a word ContentValues initialWordValue = new ContentValues(); initialWordValue.put("name", ""); long word_id = mDb.insert(WORDS_TABLE, null, initialWordValue); if(word_id == -1) { //if error Log.e(WORDS_TABLE, "cannot add new character to table "+WORDS_TABLE); mDb.endTransaction(); return false; } Cursor cur = mDb.query(WORDS_TABLE, new String[]{"_id"}, null, null, null, null, "_id DESC", "1"); if (cur != null) { cur.moveToFirst(); } word_id = cur.getInt(cur.getColumnIndexOrThrow("_id")); ContentValues wordValues = new ContentValues(); wordValues.put("_id", word_id); wordValues.put("CharId", id); wordValues.put("WordOrder", 0); wordValues.put("FlagUserCreated", 0); long success = mDb.insert(WORDS_DETAILS_TABLE, null, wordValues); if(success == -1) { //if error Log.e(WORDS_DETAILS_TABLE,"cannot add to table"); mDb.endTransaction(); return false; } mDb.setTransactionSuccessful(); mDb.endTransaction(); return true; } public long deleteCharacter(long id){ Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, CHAR_ROWID + "=" + id, null, null, null, null, null); if (mCursor == null) { return -2; } mCursor = mDb.query(true, WORDS_DETAILS_TABLE, new String[] {"CharId"}, "CharId =" + id +" AND FlagUserCreated=1", null, null, null, null, null); if(mCursor.getCount()>0){ //Some word is using the character return -1; } else{ mDb.delete(CHAR_TABLE, CHAR_ROWID + "=" + id, null); mDb.delete(CHAR_DETAILS_TABLE, "CharId = " + id, null); + mCursor = mDb.query(true, WORDS_DETAILS_TABLE, new String[] {WORDS_ROWID}, "CharId =" + id, null, + null, null, null, null); + mCursor.moveToFirst(); + do { + if(mCursor.getCount()==0){ + break; + } + long wordId = (mCursor.getLong(mCursor.getColumnIndexOrThrow(WORDS_ROWID))); + mDb.delete(WORDS_TABLE, WORDS_ROWID + "=" + wordId, null); + } + while(mCursor.moveToNext()); + mDb.delete(WORDS_DETAILS_TABLE, "CharId="+id, null); } return id; } /** * Get a LessonCharacter from the database * @param id id of the LessonCharacter * @return The LessonCharacter if id exists, null otherwise. */ public LessonCharacter getCharacterById(long id) { Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, CHAR_ROWID + "=" + id, null, null, null, null, null); LessonCharacter c = new LessonCharacter(); //if the character doesn't exists if (mCursor == null) { return null; } //grab its details (step one might not be necessary and might cause slow downs // but it is for data consistency. mCursor = mDb.query(true, CHAR_DETAILS_TABLE, new String[] {"CharId", "Stroke","PointX","PointY"}, "CharId = "+ id, null, null, null, "Stroke ASC, OrderPoint ASC", null); mCursor.moveToFirst(); Stroke s = new Stroke(); int strokeNumber = mCursor.getInt(mCursor.getColumnIndexOrThrow("Stroke")); do { if(mCursor.getCount()==0){ c.addStroke(s); break; } if(strokeNumber != mCursor.getInt(mCursor.getColumnIndexOrThrow("Stroke"))) { c.addStroke(s); strokeNumber = mCursor.getInt(mCursor.getColumnIndexOrThrow("Stroke")); s = new Stroke(); } s.addPoint(mCursor.getFloat(mCursor.getColumnIndexOrThrow("PointX")), mCursor.getFloat(mCursor.getColumnIndexOrThrow("PointY"))); } while(mCursor.moveToNext()); c.addStroke(s); c.setId(id); mCursor = mDb.query(true, CHAR_TABLE, new String[] {"name"}, CHAR_ROWID + " = "+ id, null, null, null, null, null); mCursor.moveToFirst(); String privateTag = mCursor.getString(mCursor.getColumnIndexOrThrow("name")); c.setPrivateTag(privateTag); return c; } /** * Get a LessonCharacter from the database * @param id id of the LessonCharacter * @return The LessonCharacter if id exists, null otherwise. */ public LessonWord getWordById(long id) { Cursor mCursor = mDb.query(true, WORDS_TABLE, new String[] {WORDS_ROWID}, WORDS_ROWID + "=" + id, null, null, null, null, null); LessonWord w = new LessonWord(); //if the character doesn't exists if (mCursor == null) { return null; } //grab its details (step one might not be necessary and might cause slow downs // but it is for data consistency. mCursor = mDb.query(true, WORDS_DETAILS_TABLE, new String[] {WORDS_ROWID, "CharId", "WordOrder"}, WORDS_ROWID + "=" + id, null, null, null, "WordOrder ASC", null); mCursor.moveToFirst(); Stroke s = new Stroke(); do { if(mCursor.getCount()==0){ break; } long charId = mCursor.getLong(mCursor.getColumnIndexOrThrow("CharId")); Log.i("LOAD", "Char: " + charId); w.addCharacter(charId); } while(mCursor.moveToNext()); w.setId(id); w.setDatabase(this); return w; } /** * Add a word to the database * @param w word to be added to the database * @return true if word is added to DB. False on error. */ public boolean addWord(LessonWord w) { mDb.beginTransaction(); //add to WORDS_TABLE ContentValues initialWordsValues = new ContentValues(); initializePrivateTag(w, initialWordsValues); long id = mDb.insert(WORDS_TABLE, null, initialWordsValues); if(id == -1) { //if error Log.e(WORDS_TABLE, "cannot add new character to table "+WORDS_TABLE); mDb.endTransaction(); return false; } Cursor x = mDb.query(WORDS_TABLE, new String[]{"_id"}, null, null, null, null, "_id DESC", "1"); if (x != null) { x.moveToFirst(); } w.setId(x.getInt(x.getColumnIndexOrThrow("_id"))); //add each character to WORDS_DETAILS_TABLE List<Long> l = w.getCharacterIds(); //character ordering int charNumber=0; for(Long c:l) { ContentValues characterValues = new ContentValues(); characterValues.put("_id", id); characterValues.put("CharId", c.intValue()); characterValues.put("WordOrder", charNumber); characterValues.put("FlagUserCreated", 1); long success = mDb.insert(WORDS_DETAILS_TABLE, null, characterValues); if(success == -1) { //if error Log.e(WORDS_DETAILS_TABLE,"cannot add to table"); mDb.endTransaction(); return false; } charNumber++; } mDb.setTransactionSuccessful(); mDb.endTransaction(); return true; } /** * Return a List of tags that matches the given character's charId * * @param charId id of character whose tags we want to retrieve * @return List of tags * @throws SQLException if character could not be found/retrieved */ public List<String> getTags(long charId) throws SQLException { Cursor mCursor = mDb.query(true, CHARTAG_TABLE, new String[] {CHARTAG_TAG}, CHARTAG_ROWID + "=" + charId, null, null, null, CHARTAG_TAG+" ASC", null); List<String> tags = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } tags.add(mCursor.getString(mCursor.getColumnIndexOrThrow(CHARTAG_TAG))); } while(mCursor.moveToNext()); return tags; } /** * Return a Cursor positioned at the character that matches the given tag * * @param tag text of tag to match * @return Cursor positioned to matching character, if found * @throws SQLException if character could not be found/retrieved */ public Cursor getChars(String tag) throws SQLException { Cursor mCursor = mDb.query(true, CHARTAG_TABLE, new String[] {CHARTAG_ROWID}, CHARTAG_TAG + "='" + tag+"'", null, null, null, CHARTAG_ROWID + " ASC", null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return a List of tags that matches the given Lesson's id * * @param lessonId id of lesson whose tags we want to retrieve * @return List of tags * @throws SQLException if lesson could not be found/retrieved */ public List<String> getLessonTags(long lessonId) throws SQLException { Cursor mCursor = mDb.query(true, LESSONTAG_TABLE, new String[] {"tag"}, "_id" + "=" + lessonId, null, null, null, "tag"+" ASC", null); List<String> tags = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } tags.add(mCursor.getString(mCursor.getColumnIndexOrThrow("tag"))); } while(mCursor.moveToNext()); return tags; } /** * Return a List of tags that matches the given word's wordId * * @param wordId id of word whose tags we want to retrieve * @return List of tags * @throws SQLException if word could not be found/retrieved */ public List<String> getWordTags(long wordId) throws SQLException { Cursor mCursor = mDb.query(true, WORDTAG_TABLE, new String[] {WORDTAG_TAG}, WORDTAG_ROWID + "=" + wordId, null, null, null, WORDTAG_TAG+" ASC", null); List<String> tags = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } tags.add(mCursor.getString(mCursor.getColumnIndexOrThrow(WORDTAG_TAG))); } while(mCursor.moveToNext()); return tags; } /** * Return a Cursor positioned at the word that matches the given tag * * @param tag text of tag to match * @return Cursor positioned to matching word, if found * @throws SQLException if word could not be found/retrieved */ public Cursor getWords(String tag) throws SQLException { Cursor mCursor = mDb.query(true, WORDTAG_TABLE, new String[] {WORDTAG_ROWID}, WORDTAG_TAG + "='" + tag+"'", null, null, null, WORDTAG_ROWID + " ASC", null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return a list of char ids from the database * @return ids list of all char ids */ public List<Long> getAllCharIds(){ Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, null, null, null, null, CHAR_ROWID+" ASC", null); List<Long> ids = new ArrayList<Long>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } ids.add(mCursor.getLong(mCursor.getColumnIndexOrThrow(CHAR_ROWID))); } while(mCursor.moveToNext()); return ids; } /** * Return a Cursor positioned at all characters * @return Cursor positioned to characters */ public Cursor getAllCharIdsCursor(){ Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, null, null, null, null, CHAR_ROWID+" ASC", null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Updates a private tag for a character. * * @param id row id for a character * @param tag the text of the tag to add * @return number of rows that were affected, 0 on no rows affected */ public long updatePrivateTag(long id, String tag){ ContentValues initialValues = new ContentValues(); initialValues.put(CHAR_ROWID, id); initialValues.put("name", tag); Log.e("Adding Private Tag",tag); return mDb.update(CHAR_TABLE, initialValues, CHAR_ROWID+"="+id,null); } /** * Updates a private tag for a word. Returns row id on * * @param id row id for a word * @param tag the text of the tag to add * @return number of rows that were affected, 0 on no rows affected */ public long updatePrivateWordTag(long id, String tag){ ContentValues initialValues = new ContentValues(); //initialValues.put(CHAR_ROWID, id); initialValues.put("name", tag); return mDb.update(WORDS_TABLE, initialValues, "_id="+id,null); } /** * Return a list of word ids from the database * @return ids list of all word ids */ public List<Long> getAllWordIds() { Cursor mCursor = mDb.query(true, WORDS_TABLE, new String[] {WORDS_ROWID}, null, null, null, null, WORDS_ROWID+" ASC", null); List<Long> ids = new ArrayList<Long>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } ids.add(mCursor.getLong(mCursor.getColumnIndexOrThrow(WORDS_ROWID))); } while(mCursor.moveToNext()); return ids; } public List<String> getAllLessonNames(){ Cursor mCursor = mDb.query(true, LESSONS_TABLE, new String[] {"name"}, null, null, null, null, "name ASC", null); List<String> names = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } names.add(mCursor.getString((mCursor.getColumnIndexOrThrow("name")))); } while(mCursor.moveToNext()); return names; } public long addWordToLesson(String lessonName, long wordId){ mDb.beginTransaction(); Cursor x = mDb.query(LESSONS_TABLE, new String[]{"_id"}, "name='"+lessonName+"'", null, null, null, null, null); if (x != null) { x.moveToFirst(); } else{ return -1; } int lessonId = x.getInt(x.getColumnIndexOrThrow("_id")); x = mDb.query(LESSONS_DETAILS_TABLE, new String[]{"LessonOrder"}, null, null, null, null, "LessonOrder DESC", "1"); if (x != null) { x.moveToFirst(); } else{ return -1; } int lessonOrder = x.getInt(x.getColumnIndexOrThrow("LessonOrder")); ContentValues values = new ContentValues(); values.put("LessonId", lessonId); values.put("WordId", wordId); values.put("LessonOrder",lessonOrder); long ret = mDb.insert(LESSONS_DETAILS_TABLE, null, values); mDb.setTransactionSuccessful(); mDb.endTransaction(); return ret; } /** * Add a Lesson to the database * @param les lesson to be added to the database * @return true if lesson is added to DB. False on error. */ public boolean addLesson(Lesson les) { mDb.beginTransaction(); //add to WORDS_TABLE ContentValues initialLessonValues = new ContentValues(); initializePrivateTag(les,initialLessonValues); long id = mDb.insert(LESSONS_TABLE, null, initialLessonValues); if(id == -1) { //if error Log.e(LESSONS_TABLE, "cannot add new character to table "+LESSONS_TABLE); mDb.endTransaction(); return false; } Cursor x = mDb.query(LESSONS_TABLE, new String[]{"_id"}, null, null, null, null, "_id DESC", "1"); if (x != null) { x.moveToFirst(); } les.setId(x.getInt(x.getColumnIndexOrThrow("_id"))); //add each word to LESSONS_DETAILS_TABLE List<Long> l = les.getWordIds(); //word ordering int wordNumber=0; for(Long wordId:l) { ContentValues lessonValues = new ContentValues(); lessonValues.put("LessonId", id); lessonValues.put("WordId", wordId); lessonValues.put("LessonOrder", wordNumber); long success = mDb.insert(LESSONS_DETAILS_TABLE, null, lessonValues); if(success == -1) { //if error Log.e(LESSONS_DETAILS_TABLE,"cannot add to table"); mDb.endTransaction(); return false; } wordNumber++; } mDb.setTransactionSuccessful(); mDb.endTransaction(); return true; } /** * Initializes a private tag * * @param i the LessonItem * @param v ContentValues */ private void initializePrivateTag(LessonItem i, ContentValues v) { if(i.getPrivateTag()!=null) v.put("name",i.getPrivateTag()); else v.put("name",""); } }
true
true
public boolean addCharacter(LessonCharacter c) { mDb.beginTransaction(); //add to CHAR_TABLE ContentValues initialCharValues = new ContentValues(); initializePrivateTag(c,initialCharValues); long id = mDb.insert(CHAR_TABLE, null, initialCharValues); if(id == -1) { //if error Log.e(CHAR_TABLE, "cannot add new character to table "+CHAR_TABLE); mDb.endTransaction(); return false; } Cursor x = mDb.query(CHAR_TABLE, new String[]{CHAR_ROWID}, null, null, null, null, CHAR_ROWID+" DESC", "1"); if (x != null) { x.moveToFirst(); } c.setId(x.getInt(x.getColumnIndexOrThrow(CHAR_ROWID))); //add each stroke to CHAR_DETAILS_TABLE List<Stroke> l = c.getStrokes(); //stroke ordering int strokeNumber=0; for(Stroke s:l) { ContentValues strokeValues = new ContentValues(); strokeValues.put("CharId", id); strokeValues.put("Stroke", strokeNumber); //point ordering int pointNumber=0; for(PointF p : s.getSamplePoints()) { strokeValues.put("PointX", p.x); strokeValues.put("PointY", p.y); strokeValues.put("OrderPoint", pointNumber); long success = mDb.insert(CHAR_DETAILS_TABLE, null, strokeValues); if(success == -1) { //if error Log.e(CHAR_DETAILS_TABLE,"cannot add stroke"); mDb.endTransaction(); return false; } pointNumber++; } strokeNumber++; } //need to add character as a word so that we can add them to lessons as not part of a word ContentValues initialWordValue = new ContentValues(); initialWordValue.put("name", ""); long word_id = mDb.insert(WORDS_TABLE, null, initialWordValue); if(word_id == -1) { //if error Log.e(WORDS_TABLE, "cannot add new character to table "+WORDS_TABLE); mDb.endTransaction(); return false; } Cursor cur = mDb.query(WORDS_TABLE, new String[]{"_id"}, null, null, null, null, "_id DESC", "1"); if (cur != null) { cur.moveToFirst(); } word_id = cur.getInt(cur.getColumnIndexOrThrow("_id")); ContentValues wordValues = new ContentValues(); wordValues.put("_id", word_id); wordValues.put("CharId", id); wordValues.put("WordOrder", 0); wordValues.put("FlagUserCreated", 0); long success = mDb.insert(WORDS_DETAILS_TABLE, null, wordValues); if(success == -1) { //if error Log.e(WORDS_DETAILS_TABLE,"cannot add to table"); mDb.endTransaction(); return false; } mDb.setTransactionSuccessful(); mDb.endTransaction(); return true; } public long deleteCharacter(long id){ Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, CHAR_ROWID + "=" + id, null, null, null, null, null); if (mCursor == null) { return -2; } mCursor = mDb.query(true, WORDS_DETAILS_TABLE, new String[] {"CharId"}, "CharId =" + id +" AND FlagUserCreated=1", null, null, null, null, null); if(mCursor.getCount()>0){ //Some word is using the character return -1; } else{ mDb.delete(CHAR_TABLE, CHAR_ROWID + "=" + id, null); mDb.delete(CHAR_DETAILS_TABLE, "CharId = " + id, null); } return id; } /** * Get a LessonCharacter from the database * @param id id of the LessonCharacter * @return The LessonCharacter if id exists, null otherwise. */ public LessonCharacter getCharacterById(long id) { Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, CHAR_ROWID + "=" + id, null, null, null, null, null); LessonCharacter c = new LessonCharacter(); //if the character doesn't exists if (mCursor == null) { return null; } //grab its details (step one might not be necessary and might cause slow downs // but it is for data consistency. mCursor = mDb.query(true, CHAR_DETAILS_TABLE, new String[] {"CharId", "Stroke","PointX","PointY"}, "CharId = "+ id, null, null, null, "Stroke ASC, OrderPoint ASC", null); mCursor.moveToFirst(); Stroke s = new Stroke(); int strokeNumber = mCursor.getInt(mCursor.getColumnIndexOrThrow("Stroke")); do { if(mCursor.getCount()==0){ c.addStroke(s); break; } if(strokeNumber != mCursor.getInt(mCursor.getColumnIndexOrThrow("Stroke"))) { c.addStroke(s); strokeNumber = mCursor.getInt(mCursor.getColumnIndexOrThrow("Stroke")); s = new Stroke(); } s.addPoint(mCursor.getFloat(mCursor.getColumnIndexOrThrow("PointX")), mCursor.getFloat(mCursor.getColumnIndexOrThrow("PointY"))); } while(mCursor.moveToNext()); c.addStroke(s); c.setId(id); mCursor = mDb.query(true, CHAR_TABLE, new String[] {"name"}, CHAR_ROWID + " = "+ id, null, null, null, null, null); mCursor.moveToFirst(); String privateTag = mCursor.getString(mCursor.getColumnIndexOrThrow("name")); c.setPrivateTag(privateTag); return c; } /** * Get a LessonCharacter from the database * @param id id of the LessonCharacter * @return The LessonCharacter if id exists, null otherwise. */ public LessonWord getWordById(long id) { Cursor mCursor = mDb.query(true, WORDS_TABLE, new String[] {WORDS_ROWID}, WORDS_ROWID + "=" + id, null, null, null, null, null); LessonWord w = new LessonWord(); //if the character doesn't exists if (mCursor == null) { return null; } //grab its details (step one might not be necessary and might cause slow downs // but it is for data consistency. mCursor = mDb.query(true, WORDS_DETAILS_TABLE, new String[] {WORDS_ROWID, "CharId", "WordOrder"}, WORDS_ROWID + "=" + id, null, null, null, "WordOrder ASC", null); mCursor.moveToFirst(); Stroke s = new Stroke(); do { if(mCursor.getCount()==0){ break; } long charId = mCursor.getLong(mCursor.getColumnIndexOrThrow("CharId")); Log.i("LOAD", "Char: " + charId); w.addCharacter(charId); } while(mCursor.moveToNext()); w.setId(id); w.setDatabase(this); return w; } /** * Add a word to the database * @param w word to be added to the database * @return true if word is added to DB. False on error. */ public boolean addWord(LessonWord w) { mDb.beginTransaction(); //add to WORDS_TABLE ContentValues initialWordsValues = new ContentValues(); initializePrivateTag(w, initialWordsValues); long id = mDb.insert(WORDS_TABLE, null, initialWordsValues); if(id == -1) { //if error Log.e(WORDS_TABLE, "cannot add new character to table "+WORDS_TABLE); mDb.endTransaction(); return false; } Cursor x = mDb.query(WORDS_TABLE, new String[]{"_id"}, null, null, null, null, "_id DESC", "1"); if (x != null) { x.moveToFirst(); } w.setId(x.getInt(x.getColumnIndexOrThrow("_id"))); //add each character to WORDS_DETAILS_TABLE List<Long> l = w.getCharacterIds(); //character ordering int charNumber=0; for(Long c:l) { ContentValues characterValues = new ContentValues(); characterValues.put("_id", id); characterValues.put("CharId", c.intValue()); characterValues.put("WordOrder", charNumber); characterValues.put("FlagUserCreated", 1); long success = mDb.insert(WORDS_DETAILS_TABLE, null, characterValues); if(success == -1) { //if error Log.e(WORDS_DETAILS_TABLE,"cannot add to table"); mDb.endTransaction(); return false; } charNumber++; } mDb.setTransactionSuccessful(); mDb.endTransaction(); return true; } /** * Return a List of tags that matches the given character's charId * * @param charId id of character whose tags we want to retrieve * @return List of tags * @throws SQLException if character could not be found/retrieved */ public List<String> getTags(long charId) throws SQLException { Cursor mCursor = mDb.query(true, CHARTAG_TABLE, new String[] {CHARTAG_TAG}, CHARTAG_ROWID + "=" + charId, null, null, null, CHARTAG_TAG+" ASC", null); List<String> tags = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } tags.add(mCursor.getString(mCursor.getColumnIndexOrThrow(CHARTAG_TAG))); } while(mCursor.moveToNext()); return tags; } /** * Return a Cursor positioned at the character that matches the given tag * * @param tag text of tag to match * @return Cursor positioned to matching character, if found * @throws SQLException if character could not be found/retrieved */ public Cursor getChars(String tag) throws SQLException { Cursor mCursor = mDb.query(true, CHARTAG_TABLE, new String[] {CHARTAG_ROWID}, CHARTAG_TAG + "='" + tag+"'", null, null, null, CHARTAG_ROWID + " ASC", null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return a List of tags that matches the given Lesson's id * * @param lessonId id of lesson whose tags we want to retrieve * @return List of tags * @throws SQLException if lesson could not be found/retrieved */ public List<String> getLessonTags(long lessonId) throws SQLException { Cursor mCursor = mDb.query(true, LESSONTAG_TABLE, new String[] {"tag"}, "_id" + "=" + lessonId, null, null, null, "tag"+" ASC", null); List<String> tags = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } tags.add(mCursor.getString(mCursor.getColumnIndexOrThrow("tag"))); } while(mCursor.moveToNext()); return tags; } /** * Return a List of tags that matches the given word's wordId * * @param wordId id of word whose tags we want to retrieve * @return List of tags * @throws SQLException if word could not be found/retrieved */ public List<String> getWordTags(long wordId) throws SQLException { Cursor mCursor = mDb.query(true, WORDTAG_TABLE, new String[] {WORDTAG_TAG}, WORDTAG_ROWID + "=" + wordId, null, null, null, WORDTAG_TAG+" ASC", null); List<String> tags = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } tags.add(mCursor.getString(mCursor.getColumnIndexOrThrow(WORDTAG_TAG))); } while(mCursor.moveToNext()); return tags; } /** * Return a Cursor positioned at the word that matches the given tag * * @param tag text of tag to match * @return Cursor positioned to matching word, if found * @throws SQLException if word could not be found/retrieved */ public Cursor getWords(String tag) throws SQLException { Cursor mCursor = mDb.query(true, WORDTAG_TABLE, new String[] {WORDTAG_ROWID}, WORDTAG_TAG + "='" + tag+"'", null, null, null, WORDTAG_ROWID + " ASC", null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return a list of char ids from the database * @return ids list of all char ids */ public List<Long> getAllCharIds(){ Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, null, null, null, null, CHAR_ROWID+" ASC", null); List<Long> ids = new ArrayList<Long>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } ids.add(mCursor.getLong(mCursor.getColumnIndexOrThrow(CHAR_ROWID))); } while(mCursor.moveToNext()); return ids; } /** * Return a Cursor positioned at all characters * @return Cursor positioned to characters */ public Cursor getAllCharIdsCursor(){ Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, null, null, null, null, CHAR_ROWID+" ASC", null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Updates a private tag for a character. * * @param id row id for a character * @param tag the text of the tag to add * @return number of rows that were affected, 0 on no rows affected */ public long updatePrivateTag(long id, String tag){ ContentValues initialValues = new ContentValues(); initialValues.put(CHAR_ROWID, id); initialValues.put("name", tag); Log.e("Adding Private Tag",tag); return mDb.update(CHAR_TABLE, initialValues, CHAR_ROWID+"="+id,null); } /** * Updates a private tag for a word. Returns row id on * * @param id row id for a word * @param tag the text of the tag to add * @return number of rows that were affected, 0 on no rows affected */ public long updatePrivateWordTag(long id, String tag){ ContentValues initialValues = new ContentValues(); //initialValues.put(CHAR_ROWID, id); initialValues.put("name", tag); return mDb.update(WORDS_TABLE, initialValues, "_id="+id,null); } /** * Return a list of word ids from the database * @return ids list of all word ids */ public List<Long> getAllWordIds() { Cursor mCursor = mDb.query(true, WORDS_TABLE, new String[] {WORDS_ROWID}, null, null, null, null, WORDS_ROWID+" ASC", null); List<Long> ids = new ArrayList<Long>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } ids.add(mCursor.getLong(mCursor.getColumnIndexOrThrow(WORDS_ROWID))); } while(mCursor.moveToNext()); return ids; } public List<String> getAllLessonNames(){ Cursor mCursor = mDb.query(true, LESSONS_TABLE, new String[] {"name"}, null, null, null, null, "name ASC", null); List<String> names = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } names.add(mCursor.getString((mCursor.getColumnIndexOrThrow("name")))); } while(mCursor.moveToNext()); return names; } public long addWordToLesson(String lessonName, long wordId){ mDb.beginTransaction(); Cursor x = mDb.query(LESSONS_TABLE, new String[]{"_id"}, "name='"+lessonName+"'", null, null, null, null, null); if (x != null) { x.moveToFirst(); } else{ return -1; } int lessonId = x.getInt(x.getColumnIndexOrThrow("_id")); x = mDb.query(LESSONS_DETAILS_TABLE, new String[]{"LessonOrder"}, null, null, null, null, "LessonOrder DESC", "1"); if (x != null) { x.moveToFirst(); } else{ return -1; } int lessonOrder = x.getInt(x.getColumnIndexOrThrow("LessonOrder")); ContentValues values = new ContentValues(); values.put("LessonId", lessonId); values.put("WordId", wordId); values.put("LessonOrder",lessonOrder); long ret = mDb.insert(LESSONS_DETAILS_TABLE, null, values); mDb.setTransactionSuccessful(); mDb.endTransaction(); return ret; } /** * Add a Lesson to the database * @param les lesson to be added to the database * @return true if lesson is added to DB. False on error. */ public boolean addLesson(Lesson les) { mDb.beginTransaction(); //add to WORDS_TABLE ContentValues initialLessonValues = new ContentValues(); initializePrivateTag(les,initialLessonValues); long id = mDb.insert(LESSONS_TABLE, null, initialLessonValues); if(id == -1) { //if error Log.e(LESSONS_TABLE, "cannot add new character to table "+LESSONS_TABLE); mDb.endTransaction(); return false; } Cursor x = mDb.query(LESSONS_TABLE, new String[]{"_id"}, null, null, null, null, "_id DESC", "1"); if (x != null) { x.moveToFirst(); } les.setId(x.getInt(x.getColumnIndexOrThrow("_id"))); //add each word to LESSONS_DETAILS_TABLE List<Long> l = les.getWordIds(); //word ordering int wordNumber=0; for(Long wordId:l) { ContentValues lessonValues = new ContentValues(); lessonValues.put("LessonId", id); lessonValues.put("WordId", wordId); lessonValues.put("LessonOrder", wordNumber); long success = mDb.insert(LESSONS_DETAILS_TABLE, null, lessonValues); if(success == -1) { //if error Log.e(LESSONS_DETAILS_TABLE,"cannot add to table"); mDb.endTransaction(); return false; } wordNumber++; } mDb.setTransactionSuccessful(); mDb.endTransaction(); return true; } /** * Initializes a private tag * * @param i the LessonItem * @param v ContentValues */ private void initializePrivateTag(LessonItem i, ContentValues v) { if(i.getPrivateTag()!=null) v.put("name",i.getPrivateTag()); else v.put("name",""); } }
public boolean addCharacter(LessonCharacter c) { mDb.beginTransaction(); //add to CHAR_TABLE ContentValues initialCharValues = new ContentValues(); initializePrivateTag(c,initialCharValues); long id = mDb.insert(CHAR_TABLE, null, initialCharValues); if(id == -1) { //if error Log.e(CHAR_TABLE, "cannot add new character to table "+CHAR_TABLE); mDb.endTransaction(); return false; } Cursor x = mDb.query(CHAR_TABLE, new String[]{CHAR_ROWID}, null, null, null, null, CHAR_ROWID+" DESC", "1"); if (x != null) { x.moveToFirst(); } c.setId(x.getInt(x.getColumnIndexOrThrow(CHAR_ROWID))); //add each stroke to CHAR_DETAILS_TABLE List<Stroke> l = c.getStrokes(); //stroke ordering int strokeNumber=0; for(Stroke s:l) { ContentValues strokeValues = new ContentValues(); strokeValues.put("CharId", id); strokeValues.put("Stroke", strokeNumber); //point ordering int pointNumber=0; for(PointF p : s.getSamplePoints()) { strokeValues.put("PointX", p.x); strokeValues.put("PointY", p.y); strokeValues.put("OrderPoint", pointNumber); long success = mDb.insert(CHAR_DETAILS_TABLE, null, strokeValues); if(success == -1) { //if error Log.e(CHAR_DETAILS_TABLE,"cannot add stroke"); mDb.endTransaction(); return false; } pointNumber++; } strokeNumber++; } //need to add character as a word so that we can add them to lessons as not part of a word ContentValues initialWordValue = new ContentValues(); initialWordValue.put("name", ""); long word_id = mDb.insert(WORDS_TABLE, null, initialWordValue); if(word_id == -1) { //if error Log.e(WORDS_TABLE, "cannot add new character to table "+WORDS_TABLE); mDb.endTransaction(); return false; } Cursor cur = mDb.query(WORDS_TABLE, new String[]{"_id"}, null, null, null, null, "_id DESC", "1"); if (cur != null) { cur.moveToFirst(); } word_id = cur.getInt(cur.getColumnIndexOrThrow("_id")); ContentValues wordValues = new ContentValues(); wordValues.put("_id", word_id); wordValues.put("CharId", id); wordValues.put("WordOrder", 0); wordValues.put("FlagUserCreated", 0); long success = mDb.insert(WORDS_DETAILS_TABLE, null, wordValues); if(success == -1) { //if error Log.e(WORDS_DETAILS_TABLE,"cannot add to table"); mDb.endTransaction(); return false; } mDb.setTransactionSuccessful(); mDb.endTransaction(); return true; } public long deleteCharacter(long id){ Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, CHAR_ROWID + "=" + id, null, null, null, null, null); if (mCursor == null) { return -2; } mCursor = mDb.query(true, WORDS_DETAILS_TABLE, new String[] {"CharId"}, "CharId =" + id +" AND FlagUserCreated=1", null, null, null, null, null); if(mCursor.getCount()>0){ //Some word is using the character return -1; } else{ mDb.delete(CHAR_TABLE, CHAR_ROWID + "=" + id, null); mDb.delete(CHAR_DETAILS_TABLE, "CharId = " + id, null); mCursor = mDb.query(true, WORDS_DETAILS_TABLE, new String[] {WORDS_ROWID}, "CharId =" + id, null, null, null, null, null); mCursor.moveToFirst(); do { if(mCursor.getCount()==0){ break; } long wordId = (mCursor.getLong(mCursor.getColumnIndexOrThrow(WORDS_ROWID))); mDb.delete(WORDS_TABLE, WORDS_ROWID + "=" + wordId, null); } while(mCursor.moveToNext()); mDb.delete(WORDS_DETAILS_TABLE, "CharId="+id, null); } return id; } /** * Get a LessonCharacter from the database * @param id id of the LessonCharacter * @return The LessonCharacter if id exists, null otherwise. */ public LessonCharacter getCharacterById(long id) { Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, CHAR_ROWID + "=" + id, null, null, null, null, null); LessonCharacter c = new LessonCharacter(); //if the character doesn't exists if (mCursor == null) { return null; } //grab its details (step one might not be necessary and might cause slow downs // but it is for data consistency. mCursor = mDb.query(true, CHAR_DETAILS_TABLE, new String[] {"CharId", "Stroke","PointX","PointY"}, "CharId = "+ id, null, null, null, "Stroke ASC, OrderPoint ASC", null); mCursor.moveToFirst(); Stroke s = new Stroke(); int strokeNumber = mCursor.getInt(mCursor.getColumnIndexOrThrow("Stroke")); do { if(mCursor.getCount()==0){ c.addStroke(s); break; } if(strokeNumber != mCursor.getInt(mCursor.getColumnIndexOrThrow("Stroke"))) { c.addStroke(s); strokeNumber = mCursor.getInt(mCursor.getColumnIndexOrThrow("Stroke")); s = new Stroke(); } s.addPoint(mCursor.getFloat(mCursor.getColumnIndexOrThrow("PointX")), mCursor.getFloat(mCursor.getColumnIndexOrThrow("PointY"))); } while(mCursor.moveToNext()); c.addStroke(s); c.setId(id); mCursor = mDb.query(true, CHAR_TABLE, new String[] {"name"}, CHAR_ROWID + " = "+ id, null, null, null, null, null); mCursor.moveToFirst(); String privateTag = mCursor.getString(mCursor.getColumnIndexOrThrow("name")); c.setPrivateTag(privateTag); return c; } /** * Get a LessonCharacter from the database * @param id id of the LessonCharacter * @return The LessonCharacter if id exists, null otherwise. */ public LessonWord getWordById(long id) { Cursor mCursor = mDb.query(true, WORDS_TABLE, new String[] {WORDS_ROWID}, WORDS_ROWID + "=" + id, null, null, null, null, null); LessonWord w = new LessonWord(); //if the character doesn't exists if (mCursor == null) { return null; } //grab its details (step one might not be necessary and might cause slow downs // but it is for data consistency. mCursor = mDb.query(true, WORDS_DETAILS_TABLE, new String[] {WORDS_ROWID, "CharId", "WordOrder"}, WORDS_ROWID + "=" + id, null, null, null, "WordOrder ASC", null); mCursor.moveToFirst(); Stroke s = new Stroke(); do { if(mCursor.getCount()==0){ break; } long charId = mCursor.getLong(mCursor.getColumnIndexOrThrow("CharId")); Log.i("LOAD", "Char: " + charId); w.addCharacter(charId); } while(mCursor.moveToNext()); w.setId(id); w.setDatabase(this); return w; } /** * Add a word to the database * @param w word to be added to the database * @return true if word is added to DB. False on error. */ public boolean addWord(LessonWord w) { mDb.beginTransaction(); //add to WORDS_TABLE ContentValues initialWordsValues = new ContentValues(); initializePrivateTag(w, initialWordsValues); long id = mDb.insert(WORDS_TABLE, null, initialWordsValues); if(id == -1) { //if error Log.e(WORDS_TABLE, "cannot add new character to table "+WORDS_TABLE); mDb.endTransaction(); return false; } Cursor x = mDb.query(WORDS_TABLE, new String[]{"_id"}, null, null, null, null, "_id DESC", "1"); if (x != null) { x.moveToFirst(); } w.setId(x.getInt(x.getColumnIndexOrThrow("_id"))); //add each character to WORDS_DETAILS_TABLE List<Long> l = w.getCharacterIds(); //character ordering int charNumber=0; for(Long c:l) { ContentValues characterValues = new ContentValues(); characterValues.put("_id", id); characterValues.put("CharId", c.intValue()); characterValues.put("WordOrder", charNumber); characterValues.put("FlagUserCreated", 1); long success = mDb.insert(WORDS_DETAILS_TABLE, null, characterValues); if(success == -1) { //if error Log.e(WORDS_DETAILS_TABLE,"cannot add to table"); mDb.endTransaction(); return false; } charNumber++; } mDb.setTransactionSuccessful(); mDb.endTransaction(); return true; } /** * Return a List of tags that matches the given character's charId * * @param charId id of character whose tags we want to retrieve * @return List of tags * @throws SQLException if character could not be found/retrieved */ public List<String> getTags(long charId) throws SQLException { Cursor mCursor = mDb.query(true, CHARTAG_TABLE, new String[] {CHARTAG_TAG}, CHARTAG_ROWID + "=" + charId, null, null, null, CHARTAG_TAG+" ASC", null); List<String> tags = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } tags.add(mCursor.getString(mCursor.getColumnIndexOrThrow(CHARTAG_TAG))); } while(mCursor.moveToNext()); return tags; } /** * Return a Cursor positioned at the character that matches the given tag * * @param tag text of tag to match * @return Cursor positioned to matching character, if found * @throws SQLException if character could not be found/retrieved */ public Cursor getChars(String tag) throws SQLException { Cursor mCursor = mDb.query(true, CHARTAG_TABLE, new String[] {CHARTAG_ROWID}, CHARTAG_TAG + "='" + tag+"'", null, null, null, CHARTAG_ROWID + " ASC", null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return a List of tags that matches the given Lesson's id * * @param lessonId id of lesson whose tags we want to retrieve * @return List of tags * @throws SQLException if lesson could not be found/retrieved */ public List<String> getLessonTags(long lessonId) throws SQLException { Cursor mCursor = mDb.query(true, LESSONTAG_TABLE, new String[] {"tag"}, "_id" + "=" + lessonId, null, null, null, "tag"+" ASC", null); List<String> tags = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } tags.add(mCursor.getString(mCursor.getColumnIndexOrThrow("tag"))); } while(mCursor.moveToNext()); return tags; } /** * Return a List of tags that matches the given word's wordId * * @param wordId id of word whose tags we want to retrieve * @return List of tags * @throws SQLException if word could not be found/retrieved */ public List<String> getWordTags(long wordId) throws SQLException { Cursor mCursor = mDb.query(true, WORDTAG_TABLE, new String[] {WORDTAG_TAG}, WORDTAG_ROWID + "=" + wordId, null, null, null, WORDTAG_TAG+" ASC", null); List<String> tags = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } tags.add(mCursor.getString(mCursor.getColumnIndexOrThrow(WORDTAG_TAG))); } while(mCursor.moveToNext()); return tags; } /** * Return a Cursor positioned at the word that matches the given tag * * @param tag text of tag to match * @return Cursor positioned to matching word, if found * @throws SQLException if word could not be found/retrieved */ public Cursor getWords(String tag) throws SQLException { Cursor mCursor = mDb.query(true, WORDTAG_TABLE, new String[] {WORDTAG_ROWID}, WORDTAG_TAG + "='" + tag+"'", null, null, null, WORDTAG_ROWID + " ASC", null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Return a list of char ids from the database * @return ids list of all char ids */ public List<Long> getAllCharIds(){ Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, null, null, null, null, CHAR_ROWID+" ASC", null); List<Long> ids = new ArrayList<Long>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } ids.add(mCursor.getLong(mCursor.getColumnIndexOrThrow(CHAR_ROWID))); } while(mCursor.moveToNext()); return ids; } /** * Return a Cursor positioned at all characters * @return Cursor positioned to characters */ public Cursor getAllCharIdsCursor(){ Cursor mCursor = mDb.query(true, CHAR_TABLE, new String[] {CHAR_ROWID}, null, null, null, null, CHAR_ROWID+" ASC", null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * Updates a private tag for a character. * * @param id row id for a character * @param tag the text of the tag to add * @return number of rows that were affected, 0 on no rows affected */ public long updatePrivateTag(long id, String tag){ ContentValues initialValues = new ContentValues(); initialValues.put(CHAR_ROWID, id); initialValues.put("name", tag); Log.e("Adding Private Tag",tag); return mDb.update(CHAR_TABLE, initialValues, CHAR_ROWID+"="+id,null); } /** * Updates a private tag for a word. Returns row id on * * @param id row id for a word * @param tag the text of the tag to add * @return number of rows that were affected, 0 on no rows affected */ public long updatePrivateWordTag(long id, String tag){ ContentValues initialValues = new ContentValues(); //initialValues.put(CHAR_ROWID, id); initialValues.put("name", tag); return mDb.update(WORDS_TABLE, initialValues, "_id="+id,null); } /** * Return a list of word ids from the database * @return ids list of all word ids */ public List<Long> getAllWordIds() { Cursor mCursor = mDb.query(true, WORDS_TABLE, new String[] {WORDS_ROWID}, null, null, null, null, WORDS_ROWID+" ASC", null); List<Long> ids = new ArrayList<Long>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } ids.add(mCursor.getLong(mCursor.getColumnIndexOrThrow(WORDS_ROWID))); } while(mCursor.moveToNext()); return ids; } public List<String> getAllLessonNames(){ Cursor mCursor = mDb.query(true, LESSONS_TABLE, new String[] {"name"}, null, null, null, null, "name ASC", null); List<String> names = new ArrayList<String>(); if (mCursor != null) { mCursor.moveToFirst(); } do { if(mCursor.getCount()==0){ break; } names.add(mCursor.getString((mCursor.getColumnIndexOrThrow("name")))); } while(mCursor.moveToNext()); return names; } public long addWordToLesson(String lessonName, long wordId){ mDb.beginTransaction(); Cursor x = mDb.query(LESSONS_TABLE, new String[]{"_id"}, "name='"+lessonName+"'", null, null, null, null, null); if (x != null) { x.moveToFirst(); } else{ return -1; } int lessonId = x.getInt(x.getColumnIndexOrThrow("_id")); x = mDb.query(LESSONS_DETAILS_TABLE, new String[]{"LessonOrder"}, null, null, null, null, "LessonOrder DESC", "1"); if (x != null) { x.moveToFirst(); } else{ return -1; } int lessonOrder = x.getInt(x.getColumnIndexOrThrow("LessonOrder")); ContentValues values = new ContentValues(); values.put("LessonId", lessonId); values.put("WordId", wordId); values.put("LessonOrder",lessonOrder); long ret = mDb.insert(LESSONS_DETAILS_TABLE, null, values); mDb.setTransactionSuccessful(); mDb.endTransaction(); return ret; } /** * Add a Lesson to the database * @param les lesson to be added to the database * @return true if lesson is added to DB. False on error. */ public boolean addLesson(Lesson les) { mDb.beginTransaction(); //add to WORDS_TABLE ContentValues initialLessonValues = new ContentValues(); initializePrivateTag(les,initialLessonValues); long id = mDb.insert(LESSONS_TABLE, null, initialLessonValues); if(id == -1) { //if error Log.e(LESSONS_TABLE, "cannot add new character to table "+LESSONS_TABLE); mDb.endTransaction(); return false; } Cursor x = mDb.query(LESSONS_TABLE, new String[]{"_id"}, null, null, null, null, "_id DESC", "1"); if (x != null) { x.moveToFirst(); } les.setId(x.getInt(x.getColumnIndexOrThrow("_id"))); //add each word to LESSONS_DETAILS_TABLE List<Long> l = les.getWordIds(); //word ordering int wordNumber=0; for(Long wordId:l) { ContentValues lessonValues = new ContentValues(); lessonValues.put("LessonId", id); lessonValues.put("WordId", wordId); lessonValues.put("LessonOrder", wordNumber); long success = mDb.insert(LESSONS_DETAILS_TABLE, null, lessonValues); if(success == -1) { //if error Log.e(LESSONS_DETAILS_TABLE,"cannot add to table"); mDb.endTransaction(); return false; } wordNumber++; } mDb.setTransactionSuccessful(); mDb.endTransaction(); return true; } /** * Initializes a private tag * * @param i the LessonItem * @param v ContentValues */ private void initializePrivateTag(LessonItem i, ContentValues v) { if(i.getPrivateTag()!=null) v.put("name",i.getPrivateTag()); else v.put("name",""); } }
diff --git a/src/org/eclipse/cdt/core/resources/ACBuilder.java b/src/org/eclipse/cdt/core/resources/ACBuilder.java index 8328d5fe3..643f2d388 100644 --- a/src/org/eclipse/cdt/core/resources/ACBuilder.java +++ b/src/org/eclipse/cdt/core/resources/ACBuilder.java @@ -1,93 +1,93 @@ /******************************************************************************* * Copyright (c) 2000, 2006 QNX Software Systems 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: * QNX Software Systems - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.resources; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.IMarkerGenerator; import org.eclipse.cdt.core.ProblemMarkerInfo; import org.eclipse.cdt.core.model.ICModelMarker; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; public abstract class ACBuilder extends IncrementalProjectBuilder implements IMarkerGenerator { /** * Constructor for ACBuilder */ public ACBuilder() { super(); } public void addMarker(IResource file, int lineNumber, String errorDesc, int severity, String errorVar) { ProblemMarkerInfo problemMarkerInfo = new ProblemMarkerInfo(file, lineNumber, errorDesc, severity, errorVar, null); addMarker(problemMarkerInfo); } /* * callback from Output Parser */ public void addMarker(ProblemMarkerInfo problemMarkerInfo) { try { IResource markerResource = problemMarkerInfo.file ; if (markerResource==null) { markerResource = getProject(); } IMarker[] cur = markerResource.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_ONE); /* * Try to find matching markers and don't put in duplicates */ if ((cur != null) && (cur.length > 0)) { for (int i = 0; i < cur.length; i++) { - int line = ((Integer) cur[i].getAttribute(IMarker.LOCATION)).intValue(); + int line = ((Integer) cur[i].getAttribute(IMarker.LINE_NUMBER)).intValue(); int sev = ((Integer) cur[i].getAttribute(IMarker.SEVERITY)).intValue(); String mesg = (String) cur[i].getAttribute(IMarker.MESSAGE); if (line == problemMarkerInfo.lineNumber && sev == mapMarkerSeverity(problemMarkerInfo.severity) && mesg.equals(problemMarkerInfo.description)) { return; } } } IMarker marker = markerResource.createMarker(ICModelMarker.C_MODEL_PROBLEM_MARKER); - marker.setAttribute(IMarker.LOCATION, problemMarkerInfo.lineNumber); + marker.setAttribute(IMarker.LOCATION, String.valueOf(problemMarkerInfo.lineNumber)); marker.setAttribute(IMarker.MESSAGE, problemMarkerInfo.description); marker.setAttribute(IMarker.SEVERITY, mapMarkerSeverity(problemMarkerInfo.severity)); marker.setAttribute(IMarker.LINE_NUMBER, problemMarkerInfo.lineNumber); marker.setAttribute(IMarker.CHAR_START, -1); marker.setAttribute(IMarker.CHAR_END, -1); if (problemMarkerInfo.variableName != null) { marker.setAttribute(ICModelMarker.C_MODEL_MARKER_VARIABLE, problemMarkerInfo.variableName); } if (problemMarkerInfo.externalPath != null) { marker.setAttribute(ICModelMarker.C_MODEL_MARKER_EXTERNAL_LOCATION, problemMarkerInfo.externalPath.toOSString()); } } catch (CoreException e) { CCorePlugin.log(e.getStatus()); } } int mapMarkerSeverity(int severity) { switch (severity) { case SEVERITY_ERROR_BUILD : case SEVERITY_ERROR_RESOURCE : return IMarker.SEVERITY_ERROR; case SEVERITY_INFO : return IMarker.SEVERITY_INFO; case SEVERITY_WARNING : return IMarker.SEVERITY_WARNING; } return IMarker.SEVERITY_ERROR; } }
false
true
public void addMarker(ProblemMarkerInfo problemMarkerInfo) { try { IResource markerResource = problemMarkerInfo.file ; if (markerResource==null) { markerResource = getProject(); } IMarker[] cur = markerResource.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_ONE); /* * Try to find matching markers and don't put in duplicates */ if ((cur != null) && (cur.length > 0)) { for (int i = 0; i < cur.length; i++) { int line = ((Integer) cur[i].getAttribute(IMarker.LOCATION)).intValue(); int sev = ((Integer) cur[i].getAttribute(IMarker.SEVERITY)).intValue(); String mesg = (String) cur[i].getAttribute(IMarker.MESSAGE); if (line == problemMarkerInfo.lineNumber && sev == mapMarkerSeverity(problemMarkerInfo.severity) && mesg.equals(problemMarkerInfo.description)) { return; } } } IMarker marker = markerResource.createMarker(ICModelMarker.C_MODEL_PROBLEM_MARKER); marker.setAttribute(IMarker.LOCATION, problemMarkerInfo.lineNumber); marker.setAttribute(IMarker.MESSAGE, problemMarkerInfo.description); marker.setAttribute(IMarker.SEVERITY, mapMarkerSeverity(problemMarkerInfo.severity)); marker.setAttribute(IMarker.LINE_NUMBER, problemMarkerInfo.lineNumber); marker.setAttribute(IMarker.CHAR_START, -1); marker.setAttribute(IMarker.CHAR_END, -1); if (problemMarkerInfo.variableName != null) { marker.setAttribute(ICModelMarker.C_MODEL_MARKER_VARIABLE, problemMarkerInfo.variableName); } if (problemMarkerInfo.externalPath != null) { marker.setAttribute(ICModelMarker.C_MODEL_MARKER_EXTERNAL_LOCATION, problemMarkerInfo.externalPath.toOSString()); } } catch (CoreException e) { CCorePlugin.log(e.getStatus()); } }
public void addMarker(ProblemMarkerInfo problemMarkerInfo) { try { IResource markerResource = problemMarkerInfo.file ; if (markerResource==null) { markerResource = getProject(); } IMarker[] cur = markerResource.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_ONE); /* * Try to find matching markers and don't put in duplicates */ if ((cur != null) && (cur.length > 0)) { for (int i = 0; i < cur.length; i++) { int line = ((Integer) cur[i].getAttribute(IMarker.LINE_NUMBER)).intValue(); int sev = ((Integer) cur[i].getAttribute(IMarker.SEVERITY)).intValue(); String mesg = (String) cur[i].getAttribute(IMarker.MESSAGE); if (line == problemMarkerInfo.lineNumber && sev == mapMarkerSeverity(problemMarkerInfo.severity) && mesg.equals(problemMarkerInfo.description)) { return; } } } IMarker marker = markerResource.createMarker(ICModelMarker.C_MODEL_PROBLEM_MARKER); marker.setAttribute(IMarker.LOCATION, String.valueOf(problemMarkerInfo.lineNumber)); marker.setAttribute(IMarker.MESSAGE, problemMarkerInfo.description); marker.setAttribute(IMarker.SEVERITY, mapMarkerSeverity(problemMarkerInfo.severity)); marker.setAttribute(IMarker.LINE_NUMBER, problemMarkerInfo.lineNumber); marker.setAttribute(IMarker.CHAR_START, -1); marker.setAttribute(IMarker.CHAR_END, -1); if (problemMarkerInfo.variableName != null) { marker.setAttribute(ICModelMarker.C_MODEL_MARKER_VARIABLE, problemMarkerInfo.variableName); } if (problemMarkerInfo.externalPath != null) { marker.setAttribute(ICModelMarker.C_MODEL_MARKER_EXTERNAL_LOCATION, problemMarkerInfo.externalPath.toOSString()); } } catch (CoreException e) { CCorePlugin.log(e.getStatus()); } }
diff --git a/src/org/nypl/mss/dgi/FileInput.java b/src/org/nypl/mss/dgi/FileInput.java index 38c0143..117a6ff 100644 --- a/src/org/nypl/mss/dgi/FileInput.java +++ b/src/org/nypl/mss/dgi/FileInput.java @@ -1,98 +1,105 @@ package org.nypl.mss.dgi; import java.io.*; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.maven.wagon.CommandExecutionException; import uk.gov.nationalarchives.droid.core.interfaces.IdentificationResult; public class FileInput { private File file; private String sigFile = "/Users/dm/.droid6/signature_files/DROID_SignatureFile_V60.xml"; private String host; private int port; private int timeout; FileInput(String fileIn) throws FileNotFoundException, IOException, CommandExecutionException{ this.file = new File(fileIn); if(this.file.exists()){ //getProps(); droid6(); clamav(); } else { System.exit(0); } } private void droid6() throws FileNotFoundException, IOException, CommandExecutionException { BinarySignatureIdentification bin = new BinarySignatureIdentification(file, sigFile); List<IdentificationResult> resultList = bin.getResultList(); List<IdentificationResult> extResultList = bin.getExtResultList(); if(resultList.size() == 1){ IdentificationResult result = resultList.get(0); System.out.println("droidMatch: true"); System.out.println("droidPuid: " + result.getPuid()); + if(result.getMimeType() != null) System.out.println("droidMimeType: " + result.getMimeType()); - System.out.println("droidMethod: binary signature" ); if(result.getName() != null) System.out.println("droidFileName: " + result.getName()); if(result.getVersion() != null) System.out.println("droidFileVersion: " + result.getVersion()); + System.out.println("droidIdentificationMethod: binary signature" ); } if(resultList.isEmpty()){ if(extResultList.isEmpty()){ System.out.println("droidMatch: false"); } else{ + IdentificationResult result = extResultList.get(0); System.out.println("droidMatch: true"); - System.out.println("droidPuid: " + extResultList.get(0).getPuid()); - System.out.println("droidMimeType: " + extResultList.get(0).getMimeType()); - System.out.println("droidMethod: extension" ); + System.out.println("droidPuid: " + result.getPuid()); + if(result.getMimeType() != null) + System.out.println("droidMimeType: " + result.getMimeType()); + if(result.getName() != null) + System.out.println("droidFileName: " + result.getName()); + if(result.getVersion() != null) + System.out.println("droidFileVersion: " + result.getVersion()); + System.out.println("droidIdentificationMethod: extension" ); } } } private void clamav() throws FileNotFoundException { Logger logger = Logger.getLogger("org.nypl.mss.dgi.ClamScan"); logger.setLevel(Level.OFF); BasicConfigurator.configure(); InputStream fis = new FileInputStream(file); ClamScan c = new ClamScan("127.0.0.1", 3310, 600000000); ScanResult result = c.scan(fis); Pattern pattern = Pattern.compile("FOUND"); Matcher matcher = pattern.matcher(result.getResult()); if(matcher.find()){ System.out.println("virusFound: true"); System.out.println("VirusSignature: " + result.getSignature()); } else{ System.out.println("virusFound: false"); } } private void getProps() throws FileNotFoundException, IOException { Properties prop = new Properties(); prop.load(new FileInputStream("nyplDgiProps.properties")); sigFile = prop.getProperty("droidSignatureFileLoc"); host = prop.getProperty("clamavHost"); port = Integer.parseInt(prop.getProperty("clamavPort")); timeout = Integer.parseInt(prop.getProperty("clamavTimeout")); } public static void main(String[] args) throws FileNotFoundException, IOException, CommandExecutionException{ FileInput f = new FileInput(args[0]); } }
false
true
private void droid6() throws FileNotFoundException, IOException, CommandExecutionException { BinarySignatureIdentification bin = new BinarySignatureIdentification(file, sigFile); List<IdentificationResult> resultList = bin.getResultList(); List<IdentificationResult> extResultList = bin.getExtResultList(); if(resultList.size() == 1){ IdentificationResult result = resultList.get(0); System.out.println("droidMatch: true"); System.out.println("droidPuid: " + result.getPuid()); System.out.println("droidMimeType: " + result.getMimeType()); System.out.println("droidMethod: binary signature" ); if(result.getName() != null) System.out.println("droidFileName: " + result.getName()); if(result.getVersion() != null) System.out.println("droidFileVersion: " + result.getVersion()); } if(resultList.isEmpty()){ if(extResultList.isEmpty()){ System.out.println("droidMatch: false"); } else{ System.out.println("droidMatch: true"); System.out.println("droidPuid: " + extResultList.get(0).getPuid()); System.out.println("droidMimeType: " + extResultList.get(0).getMimeType()); System.out.println("droidMethod: extension" ); } } }
private void droid6() throws FileNotFoundException, IOException, CommandExecutionException { BinarySignatureIdentification bin = new BinarySignatureIdentification(file, sigFile); List<IdentificationResult> resultList = bin.getResultList(); List<IdentificationResult> extResultList = bin.getExtResultList(); if(resultList.size() == 1){ IdentificationResult result = resultList.get(0); System.out.println("droidMatch: true"); System.out.println("droidPuid: " + result.getPuid()); if(result.getMimeType() != null) System.out.println("droidMimeType: " + result.getMimeType()); if(result.getName() != null) System.out.println("droidFileName: " + result.getName()); if(result.getVersion() != null) System.out.println("droidFileVersion: " + result.getVersion()); System.out.println("droidIdentificationMethod: binary signature" ); } if(resultList.isEmpty()){ if(extResultList.isEmpty()){ System.out.println("droidMatch: false"); } else{ IdentificationResult result = extResultList.get(0); System.out.println("droidMatch: true"); System.out.println("droidPuid: " + result.getPuid()); if(result.getMimeType() != null) System.out.println("droidMimeType: " + result.getMimeType()); if(result.getName() != null) System.out.println("droidFileName: " + result.getName()); if(result.getVersion() != null) System.out.println("droidFileVersion: " + result.getVersion()); System.out.println("droidIdentificationMethod: extension" ); } } }
diff --git a/src/pi/interpreter/commands/Ls.java b/src/pi/interpreter/commands/Ls.java index 5368f9b..60003e0 100644 --- a/src/pi/interpreter/commands/Ls.java +++ b/src/pi/interpreter/commands/Ls.java @@ -1,71 +1,71 @@ /** * @author Clément Sipieter <[email protected]> */ package pi.interpreter.commands; import java.io.File; import pi.interpreter.Environment; public class Ls implements Command { private static final String LABEL = "ls"; private static final String SYNTAX = ""; private static final String SHORT_DESC = "display current directory"; @Override public String getLabel() { return LABEL; } @Override public int exec(String[] args, Environment env) { File dir; File[] list; - String dir_name = env.get("_pwd").toString(); + String dir_name = env.get(Environment.PWD_KEY).toString(); String file_name; boolean opt_all = false; for (int i = 1; i < args.length; ++i) if (args[i].length() > 0) { if (args[i].charAt(0) != '-') { if(args[i].charAt(0) == '/') dir_name = args[i]; else dir_name += args[i]; } else if (args[i].equals("-a")) opt_all = true; } dir = new File(dir_name); list = dir.listFiles(); if (list != null) for (File file : list) { file_name = file.getName(); if(opt_all || file_name.charAt(0) != '.') env.out.println(file_name); } return Command.EXIT_SUCCESS; } @Override public String manual() { return syntax(); } public String syntax() { return SYNTAX_KEYWORD + getLabel() + " " + SYNTAX; } public String shortDescription() { return SHORT_DESC; } }
true
true
public int exec(String[] args, Environment env) { File dir; File[] list; String dir_name = env.get("_pwd").toString(); String file_name; boolean opt_all = false; for (int i = 1; i < args.length; ++i) if (args[i].length() > 0) { if (args[i].charAt(0) != '-') { if(args[i].charAt(0) == '/') dir_name = args[i]; else dir_name += args[i]; } else if (args[i].equals("-a")) opt_all = true; } dir = new File(dir_name); list = dir.listFiles(); if (list != null) for (File file : list) { file_name = file.getName(); if(opt_all || file_name.charAt(0) != '.') env.out.println(file_name); } return Command.EXIT_SUCCESS; }
public int exec(String[] args, Environment env) { File dir; File[] list; String dir_name = env.get(Environment.PWD_KEY).toString(); String file_name; boolean opt_all = false; for (int i = 1; i < args.length; ++i) if (args[i].length() > 0) { if (args[i].charAt(0) != '-') { if(args[i].charAt(0) == '/') dir_name = args[i]; else dir_name += args[i]; } else if (args[i].equals("-a")) opt_all = true; } dir = new File(dir_name); list = dir.listFiles(); if (list != null) for (File file : list) { file_name = file.getName(); if(opt_all || file_name.charAt(0) != '.') env.out.println(file_name); } return Command.EXIT_SUCCESS; }
diff --git a/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/SimController.java b/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/SimController.java index 7539908..52a8484 100644 --- a/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/SimController.java +++ b/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/SimController.java @@ -1,1360 +1,1360 @@ package harvard.robobees.simbeeotic; import com.bulletphysics.collision.broadphase.AxisSweep3; import com.bulletphysics.collision.broadphase.BroadphaseInterface; import com.bulletphysics.collision.broadphase.DbvtBroadphase; import com.bulletphysics.collision.dispatch.CollisionConfiguration; import com.bulletphysics.collision.dispatch.CollisionDispatcher; import com.bulletphysics.collision.dispatch.CollisionObject; import com.bulletphysics.collision.dispatch.CollisionWorld; import com.bulletphysics.collision.dispatch.DefaultCollisionConfiguration; import com.bulletphysics.collision.narrowphase.ManifoldPoint; import com.bulletphysics.collision.narrowphase.PersistentManifold; import com.bulletphysics.dynamics.DiscreteDynamicsWorld; import com.bulletphysics.dynamics.constraintsolver.SequentialImpulseConstraintSolver; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.name.Named; import com.google.inject.name.Names; import harvard.robobees.simbeeotic.configuration.ConfigurationAnnotations.GlobalScope; import harvard.robobees.simbeeotic.configuration.Variation; import harvard.robobees.simbeeotic.configuration.VariationIterator; import harvard.robobees.simbeeotic.configuration.InvalidScenarioException; import harvard.robobees.simbeeotic.configuration.scenario.ConfigProps; import harvard.robobees.simbeeotic.configuration.scenario.Scenario; import harvard.robobees.simbeeotic.configuration.scenario.ModelConfig; import harvard.robobees.simbeeotic.configuration.scenario.SensorConfig; import harvard.robobees.simbeeotic.configuration.scenario.RadioConfig; import harvard.robobees.simbeeotic.configuration.scenario.Vector; import harvard.robobees.simbeeotic.configuration.scenario.CustomClass; import harvard.robobees.simbeeotic.configuration.world.Meta; import harvard.robobees.simbeeotic.configuration.world.World; import static harvard.robobees.simbeeotic.environment.PhysicalConstants.EARTH_GRAVITY; import harvard.robobees.simbeeotic.environment.WorldMap; import harvard.robobees.simbeeotic.model.Contact; import harvard.robobees.simbeeotic.model.EntityInfo; import harvard.robobees.simbeeotic.model.ExternalStateSync; import harvard.robobees.simbeeotic.model.Model; import harvard.robobees.simbeeotic.model.Event; import harvard.robobees.simbeeotic.model.PhysicalEntity; import harvard.robobees.simbeeotic.model.CollisionEvent; import harvard.robobees.simbeeotic.model.MotionRecorder; import harvard.robobees.simbeeotic.model.sensor.AbstractSensor; import harvard.robobees.simbeeotic.util.DocUtil; import harvard.robobees.simbeeotic.model.comms.AntennaPattern; import harvard.robobees.simbeeotic.model.comms.IsotropicAntenna; import harvard.robobees.simbeeotic.model.comms.AbstractRadio; import harvard.robobees.simbeeotic.component.VariationComponent; import org.apache.log4j.Logger; import org.w3c.dom.Document; import javax.vecmath.Vector3f; import java.util.HashSet; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.List; import java.util.LinkedList; import java.util.Queue; import java.util.PriorityQueue; import java.util.Map; import java.util.HashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * The entry point to the simulation. The controller takes descriptions of the scenario and world * and executes the variations. * * @author bkate */ public class SimController { private static final double DEFAULT_STEP = 0.1; // s private static final double DEFAULT_SUBSTEP = 1.0 / 240.0; // s private static Logger logger = Logger.getLogger(SimController.class); /** * Runs all simulation variations of a given scenario. Each variation * will be executed as fast as possible, meaning that virtual time may * progress faster than real time. * * @param scenario The scenario, describing the models to execute. * @param world The world in which the models operate. */ public void runSim(final Scenario scenario, final World world) { runSim(scenario, world, 0, false); } /** * Behaves identically to {@link #runSim(Scenario, World)} with the exception that * an attempt is made to constrain virtual time to real time, meaning that the * simulation may not run as fast as possible. * * @param scenario The scenario, describing the models to execute. * @param world The world in which the models operate. * @param realTimeScale The scale factor for constraining real time. A scale less * than or equal to zero indicates that no constraint should be made, * and values greater than zero will scale the virtual time accordingly. * For example, a value of 2 will allow the simulation to progress, * at most, twice the rate of real time. * @param startPaused Indicates that the clock controlling each scenario variation should start * in a paused state and wait to be started. * */ public void runSim(final Scenario scenario, final World world, double realTimeScale, boolean startPaused) { int currVariation = 0; VariationIterator variations = new VariationIterator(scenario); // todo: parallelize the running of variations for (final Variation variation : variations) { final int varId = ++currVariation; logger.info(""); logger.info("--------------------------------------------"); logger.info("Executing scenario variation " + currVariation); logger.info("--------------------------------------------"); logger.info(""); final AtomicInteger nextModelId = new AtomicInteger(0); final AtomicInteger nextMotionId = new AtomicInteger(0); final Random variationSeedGenerator = new Random(variation.getSeed()); // sim engine setup final SimEngineImpl simEngine = new SimEngineImpl(realTimeScale); - final ClockControl clockControl = new ClockControl(new SimTime((long)scenario.getSimulation().getEndTime() * TimeUnit.SECONDS.toMicros(1)), + final ClockControl clockControl = new ClockControl(new SimTime((long)scenario.getSimulation().getEndTime() * TimeUnit.SECONDS.toMillis(1)), (scenario.getSimulation().getEpoch() != null) ? scenario.getSimulation().getEpoch() : TimeUnit.HOURS.toMillis(8)); if (startPaused) { clockControl.pause(); } // setup a new world in the physics engine CollisionConfiguration collisionConfiguration = new DefaultCollisionConfiguration(); CollisionDispatcher dispatcher = new CollisionDispatcher(collisionConfiguration); BroadphaseInterface broadphase = new DbvtBroadphase(); SequentialImpulseConstraintSolver solver = new SequentialImpulseConstraintSolver(); final DiscreteDynamicsWorld dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); dynamicsWorld.setGravity(new Vector3f(0, 0, (float)EARTH_GRAVITY)); final MotionRecorder motionRecorder = new MotionRecorder(); final ExternalStateSync externalSync = new ExternalStateSync(); // top level guice injector - all others are derived from this Module baseModule = new AbstractModule() { protected void configure() { // the variation number of this scenario variation bindConstant().annotatedWith(Names.named("variation-number")).to(varId); // scenario variation variable map bind(Variation.class).toInstance(variation); // the global access to sim engine executive bind(SimEngine.class).annotatedWith(GlobalScope.class).toInstance(simEngine); // clock controller for the sim engine bind(ClockControl.class).annotatedWith(GlobalScope.class).toInstance(clockControl); // dynamics world bind(DiscreteDynamicsWorld.class).annotatedWith(GlobalScope.class).toInstance(dynamicsWorld); // motion recorder bind(MotionRecorder.class).annotatedWith(GlobalScope.class).toInstance(motionRecorder); // external synchronizer bind(ExternalStateSync.class).annotatedWith(GlobalScope.class).toInstance(externalSync); } // todo: figure out how to get these providers to not be called for each child injector? @Provides @Named("random-seed") public long generateRandomSeed() { return variationSeedGenerator.nextLong(); } }; Injector baseInjector = Guice.createInjector(baseModule); // establish components final List<VariationComponent> varComponents = new LinkedList<VariationComponent>(); if (scenario.getComponents() != null) { for (CustomClass config : scenario.getComponents().getVariation()) { final Class compClass; final Properties compProps = loadConfigProps(config.getProperties(), variation); try { // locate the model implementation compClass = Class.forName(config.getJavaClass()); // make sure it implements Model if (!VariationComponent.class.isAssignableFrom(compClass)) { throw new RuntimeException("The component implementation must extend from VariationComponent."); } } catch(ClassNotFoundException cnf) { throw new RuntimeException("Could not locate the component class: " + config.getJavaClass(), cnf); } Injector compInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), compProps); // component class bind(VariationComponent.class).to(compClass); } }); VariationComponent component = compInjector.getInstance(VariationComponent.class); component.initialize(); varComponents.add(component); } } // setup the simulated world (obstacle, flowers, etc) final Properties worldProps = new Properties(); if (world.getProperties() != null) { for (Meta.Prop prop : world.getProperties().getProp()) { worldProps.setProperty(prop.getName(), prop.getValue()); } } baseInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), worldProps); bind(WorldMap.class); bind(World.class).toInstance(world); bind(AtomicInteger.class).annotatedWith(Names.named("next-id")).toInstance(nextMotionId); } }); final WorldMap map = baseInjector.getInstance(WorldMap.class); map.initialize(); baseInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { // established simulated world instance bind(WorldMap.class).annotatedWith(GlobalScope.class).toInstance(map); } }); // parse model definitions final List<Model> models = new LinkedList<Model>(); if (scenario.getModels() != null) { for (ModelConfig config : scenario.getModels().getModel()) { parseModelConfig(config, null, null, models, variation, baseInjector, nextModelId, nextMotionId); } } for (Model model : models) { simEngine.addModel(model); } // initialize all models for (Model model : models) { model.initialize(); } // setup a handler for dealing with contacts and informing objects // of when they collide ContactHandler contactHandler = new ContactHandler(dynamicsWorld, simEngine); // add a shutdown hook final AtomicBoolean cleaned = new AtomicBoolean(false); final Lock cleanupLock = new ReentrantLock(); Thread hook = new Thread() { @Override public void run() { cleanupLock.lock(); try { if (!cleaned.get()) { // clean out any events simEngine.shutdown(); // breakdown services, models, and components map.destroy(); for (Model m : models) { m.finish(); if (m instanceof PhysicalEntity) { ((PhysicalEntity)m).destroy(); } } for (VariationComponent comp : varComponents) { comp.shutdown(); } motionRecorder.shutdown(); cleaned.set(true); } } finally { cleanupLock.unlock(); } } }; Runtime.getRuntime().addShutdownHook(hook); // run it long variationStartTime = System.currentTimeMillis(); SimTime lastSimTime = new SimTime(0); SimTime nextSimTime = simEngine.getNextEventTime(); SimTime endTime = clockControl.getEndTime(); while((nextSimTime != null) && (nextSimTime.compareTo(endTime) <= 0)) { clockControl.waitUntilStarted(); // update positions in physical world so that all // objects are up to date with the event time if (nextSimTime.getTime() > lastSimTime.getTime()) { double diff = nextSimTime.getImpreciseTime() - lastSimTime.getImpreciseTime(); long updatedTime = 0; while(diff > 0) { // update the kinematic state of any externally driven objects externalSync.updateStates(); double step = Math.min(DEFAULT_STEP, diff); dynamicsWorld.stepSimulation((float)step, (int)Math.ceil(step / DEFAULT_SUBSTEP), (float)DEFAULT_SUBSTEP); // keep track of how far ahead the physics engine is getting from the last processed event time updatedTime += (long)(step * TimeUnit.SECONDS.toNanos(1)); // update collisions if (contactHandler.update(lastSimTime, updatedTime)) { break; } diff -= DEFAULT_STEP; } lastSimTime = simEngine.getNextEventTime(); } if (logger.isDebugEnabled()) { logger.debug("Executing event at time: " + nextSimTime); } clockControl.notifyListeners(nextSimTime); nextSimTime = simEngine.processNextEvent(); } // cleanup hook.run(); Runtime.getRuntime().removeShutdownHook(hook); double runTime = (double)(System.currentTimeMillis() - variationStartTime) / TimeUnit.SECONDS.toMillis(1); logger.info(""); logger.info("--------------------------------------------"); logger.info("Scenario variation " + currVariation + " executed in " + runTime + " seconds."); logger.info("--------------------------------------------"); } } /** * Creates a virtual world and the components specified in the scenario, but does not * create any models or start a simulation engine. This method allows users to * utilize the Simbeeotic framework without running a scenario (e.g. for visualization). * <p/> * Note that not all aspects of the framework will be available to components - specifically, * there will be no sim engine or clock control. In addition, only the first variation * will be executed if the scenario defines multiple variations. * * @param scenario The scenario, describing the models to execute. * @param world The world in which the models operate. */ public void runComponents(final Scenario scenario, final World world) { VariationIterator variations = new VariationIterator(scenario); final int varId = 1; final Variation firstVariation = variations.next(); final AtomicInteger nextMotionId = new AtomicInteger(0); final Random seedGenerator = new Random(112181); // setup a new world in the physics engine CollisionConfiguration collisionConfiguration = new DefaultCollisionConfiguration(); CollisionDispatcher dispatcher = new CollisionDispatcher(collisionConfiguration); float aabbDim = world.getRadius() / (float)Math.sqrt(3); Vector3f worldAabbMin = new Vector3f(-aabbDim, -aabbDim, 0); Vector3f worldAabbMax = new Vector3f(aabbDim, aabbDim, aabbDim * 2); AxisSweep3 overlappingPairCache = new AxisSweep3(worldAabbMin, worldAabbMax); SequentialImpulseConstraintSolver solver = new SequentialImpulseConstraintSolver(); final DiscreteDynamicsWorld dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration); dynamicsWorld.setGravity(new Vector3f(0, 0, (float)EARTH_GRAVITY)); final MotionRecorder motionRecorder = new MotionRecorder(); // top level guice injector - all others are derived from this Module baseModule = new AbstractModule() { protected void configure() { // the variation number of this scenario variation bindConstant().annotatedWith(Names.named("variation-number")).to(varId); // scenario variation variable map bind(Variation.class).toInstance(firstVariation); // dynamics world bind(DiscreteDynamicsWorld.class).annotatedWith(GlobalScope.class).toInstance(dynamicsWorld); // motion recorder bind(MotionRecorder.class).annotatedWith(GlobalScope.class).toInstance(motionRecorder); } // todo: figure out how to get these providers to not be called for each child injector? @Provides @Named("random-seed") public long generateRandomSeed() { return seedGenerator.nextLong(); } }; Injector baseInjector = Guice.createInjector(baseModule); // establish components final List<VariationComponent> varComponents = new LinkedList<VariationComponent>(); if (scenario.getComponents() != null) { for (CustomClass config : scenario.getComponents().getVariation()) { final Class compClass; final Properties compProps = loadConfigProps(config.getProperties(), firstVariation); try { // locate the model implementation compClass = Class.forName(config.getJavaClass()); // make sure it implements Model if (!VariationComponent.class.isAssignableFrom(compClass)) { throw new RuntimeException("The component implementation must extend from VariationComponent."); } } catch(ClassNotFoundException cnf) { throw new RuntimeException("Could not locate the component class: " + config.getJavaClass(), cnf); } Injector compInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), compProps); // component class bind(VariationComponent.class).to(compClass); } }); VariationComponent component = compInjector.getInstance(VariationComponent.class); component.initialize(); varComponents.add(component); } } // setup the simulated world (obstacle, flowers, etc) final Properties worldProps = new Properties(); if (world.getProperties() != null) { for (Meta.Prop prop : world.getProperties().getProp()) { worldProps.setProperty(prop.getName(), prop.getValue()); } } Injector worldInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), worldProps); bind(WorldMap.class); bind(World.class).toInstance(world); bind(AtomicInteger.class).annotatedWith(Names.named("next-id")).toInstance(nextMotionId); } }); final WorldMap map = worldInjector.getInstance(WorldMap.class); map.initialize(); // do nothing until killed - there is no way to know that the components are done while(true) { try { Thread.sleep(1000000); } catch(InterruptedException ie) { break; } } } /** * Properly shuts down the simulation. */ private void breakdownSim() { } /** * Parses model definitions and returns the corresponding models. This is a * recursive call, allowing nested models to be instantiated. The entire model * tree is returned as a flattened list of models. * * @param config The model config to parse. * @param parent The parent model, or {@code null} if the model config is a root. * @param startPos The starting position in the world. May be {@code null} if it is not set by an ancestor. * @param models The list of configured models. * @param variation The current scenario variation. * @param injector The Guice injector to use as a parent injector. * @param nextModelId The next ID for a model. * @param nextMotionId The next ID for a motion-recorded object. */ private void parseModelConfig(final ModelConfig config, Model parent, Vector3f startPos, List<Model> models, Variation variation, Injector injector, final AtomicInteger nextModelId, final AtomicInteger nextMotionId) { if (config == null) { return; } final Class modelClass; try { // locate the model implementation modelClass = Class.forName(config.getJavaClass()); // make sure it implements Model if (!Model.class.isAssignableFrom(modelClass)) { throw new RuntimeException("The model implementation must extend from Model."); } } catch(ClassNotFoundException cnf) { throw new RuntimeException("Could not locate the model class: " + config.getJavaClass(), cnf); } // custom properties final Properties modelProps = loadConfigProps(config.getProperties(), variation); final Vector3f starting; if (startPos != null) { starting = new Vector3f(startPos); Vector pos = config.getStartPosition(); if ((pos != null) && ((starting.x != pos.getX()) || (starting.y != pos.getY()) || (starting.z != pos.getZ()))) { logger.warn("A child model has specified a starting position different from its parent, using parent position."); } } else { starting = new Vector3f(); if (config.getStartPosition() != null) { starting.x = config.getStartPosition().getX(); starting.y = config.getStartPosition().getY(); starting.z = config.getStartPosition().getZ(); } } // optional config doc Document optionalDoc = null; if (config.getCustomConfig() != null) { optionalDoc = DocUtil.createDocumentFromElement(config.getCustomConfig().getAny()); } // model injection config for (int i = 0; i < config.getCount(); i++) { Injector modelInjector = injector.createChildInjector(new AbstractModule() { protected void configure() { bindConstant().annotatedWith(Names.named("model-id")).to(nextModelId.getAndIncrement()); bindConstant().annotatedWith(Names.named("object-id")).to(nextMotionId.getAndIncrement()); bindConstant().annotatedWith(Names.named("model-name")).to(config.getName()); bind(Vector3f.class).annotatedWith(Names.named("start-position")).toInstance(starting); Names.bindProperties(binder(), modelProps); // model class bind(Model.class).to(modelClass); // a workaround for guice issue 282 bind(modelClass); } }); // instantiate the model final Model m = modelInjector.getInstance(Model.class); if (parent != null) { m.setParentModel(parent); parent.addChildModel(m); } models.add(m); m.setCustomConfig(optionalDoc); // go through child models for (ModelConfig childConfig : config.getModel()) { parseModelConfig(childConfig, m, starting, models, variation, injector, nextModelId, nextMotionId); } // sensors for (final SensorConfig sensorConfig : config.getSensor()) { // sensors must be attached to physical entities because they rely on // their position and orientation information if (!(m instanceof PhysicalEntity)) { throw new InvalidScenarioException("Sensor being attached to a model that is not a PhysicalEntity."); } final Class sensorClass; try { sensorClass = Class.forName(sensorConfig.getJavaClass()); if (!Model.class.isAssignableFrom(sensorClass)) { throw new RuntimeException("The sensor implementation must implement Model."); } else if (!AbstractSensor.class.isAssignableFrom(sensorClass)) { throw new RuntimeException("The sensor implementation must extend from AbstractSensor."); } } catch(ClassNotFoundException cnf) { throw new RuntimeException("Could not locate the sensor class: " + config.getJavaClass(), cnf); } final Properties sensorProps = loadConfigProps(sensorConfig.getProperties(), variation); final Vector3f offset = new Vector3f(); final Vector3f pointing = new Vector3f(); if (sensorConfig.getOffset() != null) { offset.set(sensorConfig.getOffset().getX(), sensorConfig.getOffset().getY(), sensorConfig.getOffset().getZ()); } if (sensorConfig.getPointing() != null) { pointing.set(sensorConfig.getPointing().getX(), sensorConfig.getPointing().getY(), sensorConfig.getPointing().getZ()); } Injector sensorInjector = injector.createChildInjector(new AbstractModule() { protected void configure() { Names.bindProperties(binder(), sensorProps); bindConstant().annotatedWith(Names.named("model-id")).to(nextModelId.getAndIncrement()); bindConstant().annotatedWith(Names.named("model-name")).to(sensorConfig.getName()); bind(Vector3f.class).annotatedWith(Names.named("offset")).toInstance(offset); bind(Vector3f.class).annotatedWith(Names.named("pointing")).toInstance(pointing); bind(Model.class).to(sensorClass); // a workaround for guice issue 282 bind(sensorClass); } }); Model sensor = sensorInjector.getInstance(Model.class); models.add(sensor); sensor.setParentModel(m); m.addChildModel(sensor); } // radio if (config.getRadio() != null) { // radios must be attached to physical entities because they rely on // their position and orientation information if (!(m instanceof PhysicalEntity)) { throw new InvalidScenarioException("Radio being attached to a model that is not a PhysicalEntity."); } final RadioConfig radioConfig = config.getRadio(); final Class radioClass; final AntennaPattern pattern; final Properties radioProps = loadConfigProps(radioConfig.getProperties(), variation); try { radioClass = Class.forName(radioConfig.getJavaClass()); if (!Model.class.isAssignableFrom(radioClass)) { throw new RuntimeException("The radio implementation must implement Model."); } else if (!AbstractRadio.class.isAssignableFrom(radioClass)) { throw new RuntimeException("The radio implementation must implement AbstractRadio."); } } catch(ClassNotFoundException cnf) { throw new RuntimeException("Could not locate the radio class: " + radioConfig.getJavaClass(), cnf); } if (config.getRadio().getAntennaPattern() != null) { final Class patternClass; final Properties patternProps = loadConfigProps(radioConfig.getAntennaPattern().getProperties(), variation); try { patternClass = Class.forName(radioConfig.getAntennaPattern().getJavaClass()); if (!AntennaPattern.class.isAssignableFrom(patternClass)) { throw new RuntimeException("The antenna pattern implementation must implement AntennaPattern."); } } catch(ClassNotFoundException cnf) { throw new RuntimeException("Could not locate the antenna pattern class: " + radioConfig.getAntennaPattern().getJavaClass(), cnf); } Injector patternInjector = injector.createChildInjector(new AbstractModule() { protected void configure() { Names.bindProperties(binder(), patternProps); bind(AntennaPattern.class).to(patternClass); // a workaround for guice issue 282 bind(patternClass); } }); pattern = patternInjector.getInstance(AntennaPattern.class); } else { pattern = new IsotropicAntenna(); } Injector radioInjector = injector.createChildInjector(new AbstractModule() { protected void configure() { Names.bindProperties(binder(), radioProps); bindConstant().annotatedWith(Names.named("model-id")).to(nextModelId.getAndIncrement()); bindConstant().annotatedWith(Names.named("model-name")).to(radioConfig.getName()); bind(AntennaPattern.class).toInstance(pattern); bind(Model.class).to(radioClass); // a workaround for guice issue 282 bind(radioClass); } }); Model radio = radioInjector.getInstance(Model.class); models.add(radio); radio.setParentModel(m); m.addChildModel(radio); } } } /** * Loads configuration properties into a Properties object and substitutes values * according to the variable map for the given variation, if necessary. * * @param config The configuration properties defined in the scenario file. * @param variation The map of current variable values. * * @return The loaded properties. */ private Properties loadConfigProps(ConfigProps config, Variation variation) { Properties resolved = new Properties(); if (config == null) { return resolved; } for (ConfigProps.Prop prop : config.getProp()) { String val = prop.getValue(); if (DocUtil.isPlaceholder(val)) { String var = DocUtil.extractPlaceholderName(val); if (variation.getVariables().containsKey(var)) { val = variation.getVariables().get(var); } else { logger.warn("The variable '" + prop.getName() + "' has not been set."); String def = DocUtil.extractPlaceholderDefault(val); if (def != null) { val = def; } else { logger.warn("The variable '" + prop.getName() + "' has no default."); } } } resolved.setProperty(prop.getName(), val); } return resolved; } /** * A class that iterates through contacts and informs each object of its contact. */ private static final class ContactHandler { private CollisionWorld world; private SimEngine simEngine; private Map<CollisionObject, Set<CollisionObject>> contactMap = new HashMap<CollisionObject, Set<CollisionObject>>(); public ContactHandler(CollisionWorld world, SimEngine engine) { this.world = world; this.simEngine = engine; } /** * Looks for contacts between objects at the given time. * * @param lastSimTime The last officially processed evnet time. * @param updatedTime The amount of time that the physics engine has moved forward since the last event was executed (nanoseconds). * * @return True if a collision event was scheduled, false otherwise. */ public boolean update(SimTime lastSimTime, long updatedTime) { // remove old contacts for (CollisionObject obj : contactMap.keySet()) { ((EntityInfo)obj.getUserPointer()).getContactPoints().clear(); } Map<CollisionObject, Set<CollisionObject>> newContacts = new HashMap<CollisionObject, Set<CollisionObject>>(); boolean scheduledEvent = false; int numManifolds = world.getDispatcher().getNumManifolds(); for (int i = 0; i < numManifolds; i++) { PersistentManifold manifold = world.getDispatcher().getManifoldByIndexInternal(i); CollisionObject objectA = (CollisionObject)manifold.getBody0(); CollisionObject objectB = (CollisionObject)manifold.getBody1(); EntityInfo infoA = (EntityInfo)objectA.getUserPointer(); EntityInfo infoB = (EntityInfo)objectB.getUserPointer(); int numPoints = manifold.getNumContacts(); for (int j = 0; j < numPoints; j++) { ManifoldPoint point = manifold.getContactPoint(j); Contact contactA = new Contact(point.localPointA, point.getPositionWorldOnA(new Vector3f()), ((EntityInfo)objectB.getUserPointer()).getMetadata()); Contact contactB = new Contact(point.localPointB, point.getPositionWorldOnB(new Vector3f()), ((EntityInfo)objectA.getUserPointer()).getMetadata()); // add the contact points to the objects infoA.getContactPoints().add(contactA); infoB.getContactPoints().add(contactB); } // record that the two objects are touching if (numPoints > 0) { if (!newContacts.containsKey(objectA)) { newContacts.put(objectA, new HashSet<CollisionObject>()); } if (!newContacts.containsKey(objectB)) { newContacts.put(objectB, new HashSet<CollisionObject>()); } newContacts.get(objectA).add(objectB); newContacts.get(objectB).add(objectA); // if it wasn't in the old map, it is a new contact (i.e. collision) if (!contactMap.containsKey(objectA) || (contactMap.containsKey(objectA) && !contactMap.get(objectA).contains(objectB))) { // schedule an event to signify the collision on the object(s) that // are expecting such an event. it is better to do it this way (despite the // hackiness) than broadcasting an event to all models and having them check // if they are involved in the collision. SimTime time = new SimTime(lastSimTime, updatedTime, TimeUnit.NANOSECONDS); CollisionEvent event = new CollisionEvent(); for (int id : infoA.getCollisionListeners()) { simEngine.scheduleEvent(id, time, event); scheduledEvent = true; } for (int id : infoB.getCollisionListeners()) { simEngine.scheduleEvent(id, time, event); scheduledEvent = true; } } } } contactMap = newContacts; return scheduledEvent; } } /** * An implementation of {@link SimEngine} that is used as a container * and coordinator for events in each scenario variation. * * <br/> * This class is not thread safe, so it would need to be updated if * multiple models are allowed to execute in parallel in the future. */ private static final class SimEngineImpl implements SimEngine { private Queue<ScheduledEvent> eventQ = new PriorityQueue<ScheduledEvent>(); private Map<Integer, Model> modelMap = new HashMap<Integer, Model>(); private Map<String, List<Model>> modelNameMap = new HashMap<String, List<Model>>(); private Map<Class, List> modelTypeMap = new HashMap<Class, List>(); private SimTime processing = null; private SimTime lastProcessed = null; private long nextEventId = 1; private boolean terminated = false; private double realTimeScale = 1; private long firstEventRealTime = -1; public SimEngineImpl(double realTimeScale) { this.realTimeScale = realTimeScale; } /** {@inheritDoc} */ public SimTime getCurrentTime() { return processing; } /** {@inheritDoc} */ public long scheduleEvent(final int modelId, final SimTime time, final Event event) { if (terminated) { logger.debug("Attempting to schedule an event after scenario termination was requested."); return -1; } SimTime minTime = processing; if ((minTime == null) && (lastProcessed != null)) { minTime = lastProcessed; } // the user is trying to schedule an event for a time in the past if ((minTime != null) && (time.compareTo(minTime) < 0)) { throw new CausalityViolationException("The time of the event (" + time + ") is prior to GVT (" + minTime + ")."); } Model model = modelMap.get(modelId); if (model == null) { throw new ModelNotFoundException(); } long eventId = nextEventId++; // add it to the queue eventQ.add(new ScheduledEvent(eventId, time, event, model)); return eventId; } /** {@inheritDoc} */ public void cancelEvent(long eventId) { // todo: do this better ScheduledEvent toRemove = null; for (ScheduledEvent e : eventQ) { if (e.getId() == eventId) { toRemove = e; break; } } if (toRemove != null) { eventQ.remove(toRemove); } } /** {@inheritDoc} */ public void requestScenarioTermination() { logger.info("A model has requested scenario termination."); // for now we will just shutdown on the first request shutdown(); } /** * Shuts down the sim engine by clearing all events and setting the terminated flag. */ public void shutdown() { terminated = true; eventQ.clear(); } /** {@inheritDoc} */ public Model findModelById(int ID) { return modelMap.get(ID); } /** {@inheritDoc} */ public Model findModelByName(String name) { List<Model> models = findModelsByName(name); if (models.isEmpty()) { return null; } else if (models.size() > 1) { throw new RuntimeException("There is more than one model with the name: '" + name + "'."); } return models.get(0); } /** {@inheritDoc} */ public <T> T findModelByType(Class<T> type) { List<T> models = findModelsByType(type); if (models.isEmpty()) { return null; } else if (models.size() > 1) { throw new RuntimeException("There is more than one model with the type: '" + type.toString() + "'."); } return type.cast(models.get(0)); } /** {@inheritDoc} */ public List<Model> findModelsByName(String name) { return modelNameMap.get(name); } /** {@inheritDoc} */ public <T> List<T> findModelsByType(Class<T> type) { if (!modelTypeMap.containsKey(type)) { List<T> results = new LinkedList<T>(); // search all models and cache the results for (Model m : modelMap.values()) { if (type.isAssignableFrom(m.getClass())) { results.add(type.cast(m)); } } modelTypeMap.put(type, results); return results; } return modelTypeMap.get(type); } /** * Gets the time of the event that is at the head of the queue. * * @return The {@link SimTime} of the next {@link Event} to be processed, * or {@code null} if there are no events scheduled. */ public SimTime getNextEventTime() { ScheduledEvent next = eventQ.peek(); if (next != null) { return next.time; } return null; } /** * Processes the next event in the queue. This method will block while the * event is being processed. * * @return The time of the event <i>following</i> the event that was just * processed, which is the head of the event queue. This is equivalent * to calling {@link #getNextEventTime()} immediately after this call. */ public SimTime processNextEvent() { ScheduledEvent next = eventQ.poll(); if (next != null) { if (firstEventRealTime < 0) { firstEventRealTime = System.nanoTime(); } // if we are scaling to real time, hold off until we are ready to run the event. // this implementation provide millisecond precision long nanos = (long)(next.time.getTime() * realTimeScale) - (System.nanoTime() - firstEventRealTime); if (nanos > 0) { long millis = TimeUnit.NANOSECONDS.toMillis(nanos); if (millis > 0) { nanos -= TimeUnit.MILLISECONDS.toNanos(millis); } try { Thread.sleep(millis, (int)nanos); } catch(InterruptedException ie) { throw new RuntimeException("SimEngine was interrupted while sleeping."); } } processing = next.time; next.model.processEvent(next.time, next.event); } lastProcessed = processing; processing = null; return getNextEventTime(); } /** * Adds a model to the simulation. Only models that have been added can have events * scheduled on them. * * @param model The model that is capable of event execution. */ public void addModel(final Model model) { if (modelMap.containsKey(model.getModelId())) { throw new RuntimeException("A model with the ID " + model.getModelId() + " is already registered."); } modelMap.put(model.getModelId(), model); if (!modelNameMap.containsKey(model.getName())) { modelNameMap.put(model.getName(), new LinkedList<Model>()); } modelNameMap.get(model.getName()).add(model); } /** * A container that holds the details of an event to be processed in the future. */ private static class ScheduledEvent implements Comparable<ScheduledEvent> { public long id; public SimTime time; public Event event; public Model model; public ScheduledEvent(long id, SimTime time, Event event, Model model) { this.id = id; this.time = time; this.event = event; this.model = model; } /** * We need an absolute (deterministic) sorting of scheduled events, so we use the * time, model ID, and event ID as tiebreakers. * * @param o The other event. * * @return An integer less than 0 if this event should come before the other, greater * than zero if it should come after the other, and 0 if there is no difference * in the order of processing. */ @Override public int compareTo(ScheduledEvent o) { int timeComp = time.compareTo(o.time); if (timeComp == 0) { int modelComp = Integer.valueOf(model.getModelId()).compareTo(o.model.getModelId()); if (modelComp == 0) { return Long.valueOf(id).compareTo(o.id); } return modelComp; } return timeComp; } public long getId() { return id; } } } }
true
true
public void runSim(final Scenario scenario, final World world, double realTimeScale, boolean startPaused) { int currVariation = 0; VariationIterator variations = new VariationIterator(scenario); // todo: parallelize the running of variations for (final Variation variation : variations) { final int varId = ++currVariation; logger.info(""); logger.info("--------------------------------------------"); logger.info("Executing scenario variation " + currVariation); logger.info("--------------------------------------------"); logger.info(""); final AtomicInteger nextModelId = new AtomicInteger(0); final AtomicInteger nextMotionId = new AtomicInteger(0); final Random variationSeedGenerator = new Random(variation.getSeed()); // sim engine setup final SimEngineImpl simEngine = new SimEngineImpl(realTimeScale); final ClockControl clockControl = new ClockControl(new SimTime((long)scenario.getSimulation().getEndTime() * TimeUnit.SECONDS.toMicros(1)), (scenario.getSimulation().getEpoch() != null) ? scenario.getSimulation().getEpoch() : TimeUnit.HOURS.toMillis(8)); if (startPaused) { clockControl.pause(); } // setup a new world in the physics engine CollisionConfiguration collisionConfiguration = new DefaultCollisionConfiguration(); CollisionDispatcher dispatcher = new CollisionDispatcher(collisionConfiguration); BroadphaseInterface broadphase = new DbvtBroadphase(); SequentialImpulseConstraintSolver solver = new SequentialImpulseConstraintSolver(); final DiscreteDynamicsWorld dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); dynamicsWorld.setGravity(new Vector3f(0, 0, (float)EARTH_GRAVITY)); final MotionRecorder motionRecorder = new MotionRecorder(); final ExternalStateSync externalSync = new ExternalStateSync(); // top level guice injector - all others are derived from this Module baseModule = new AbstractModule() { protected void configure() { // the variation number of this scenario variation bindConstant().annotatedWith(Names.named("variation-number")).to(varId); // scenario variation variable map bind(Variation.class).toInstance(variation); // the global access to sim engine executive bind(SimEngine.class).annotatedWith(GlobalScope.class).toInstance(simEngine); // clock controller for the sim engine bind(ClockControl.class).annotatedWith(GlobalScope.class).toInstance(clockControl); // dynamics world bind(DiscreteDynamicsWorld.class).annotatedWith(GlobalScope.class).toInstance(dynamicsWorld); // motion recorder bind(MotionRecorder.class).annotatedWith(GlobalScope.class).toInstance(motionRecorder); // external synchronizer bind(ExternalStateSync.class).annotatedWith(GlobalScope.class).toInstance(externalSync); } // todo: figure out how to get these providers to not be called for each child injector? @Provides @Named("random-seed") public long generateRandomSeed() { return variationSeedGenerator.nextLong(); } }; Injector baseInjector = Guice.createInjector(baseModule); // establish components final List<VariationComponent> varComponents = new LinkedList<VariationComponent>(); if (scenario.getComponents() != null) { for (CustomClass config : scenario.getComponents().getVariation()) { final Class compClass; final Properties compProps = loadConfigProps(config.getProperties(), variation); try { // locate the model implementation compClass = Class.forName(config.getJavaClass()); // make sure it implements Model if (!VariationComponent.class.isAssignableFrom(compClass)) { throw new RuntimeException("The component implementation must extend from VariationComponent."); } } catch(ClassNotFoundException cnf) { throw new RuntimeException("Could not locate the component class: " + config.getJavaClass(), cnf); } Injector compInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), compProps); // component class bind(VariationComponent.class).to(compClass); } }); VariationComponent component = compInjector.getInstance(VariationComponent.class); component.initialize(); varComponents.add(component); } } // setup the simulated world (obstacle, flowers, etc) final Properties worldProps = new Properties(); if (world.getProperties() != null) { for (Meta.Prop prop : world.getProperties().getProp()) { worldProps.setProperty(prop.getName(), prop.getValue()); } } baseInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), worldProps); bind(WorldMap.class); bind(World.class).toInstance(world); bind(AtomicInteger.class).annotatedWith(Names.named("next-id")).toInstance(nextMotionId); } }); final WorldMap map = baseInjector.getInstance(WorldMap.class); map.initialize(); baseInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { // established simulated world instance bind(WorldMap.class).annotatedWith(GlobalScope.class).toInstance(map); } }); // parse model definitions final List<Model> models = new LinkedList<Model>(); if (scenario.getModels() != null) { for (ModelConfig config : scenario.getModels().getModel()) { parseModelConfig(config, null, null, models, variation, baseInjector, nextModelId, nextMotionId); } } for (Model model : models) { simEngine.addModel(model); } // initialize all models for (Model model : models) { model.initialize(); } // setup a handler for dealing with contacts and informing objects // of when they collide ContactHandler contactHandler = new ContactHandler(dynamicsWorld, simEngine); // add a shutdown hook final AtomicBoolean cleaned = new AtomicBoolean(false); final Lock cleanupLock = new ReentrantLock(); Thread hook = new Thread() { @Override public void run() { cleanupLock.lock(); try { if (!cleaned.get()) { // clean out any events simEngine.shutdown(); // breakdown services, models, and components map.destroy(); for (Model m : models) { m.finish(); if (m instanceof PhysicalEntity) { ((PhysicalEntity)m).destroy(); } } for (VariationComponent comp : varComponents) { comp.shutdown(); } motionRecorder.shutdown(); cleaned.set(true); } } finally { cleanupLock.unlock(); } } }; Runtime.getRuntime().addShutdownHook(hook); // run it long variationStartTime = System.currentTimeMillis(); SimTime lastSimTime = new SimTime(0); SimTime nextSimTime = simEngine.getNextEventTime(); SimTime endTime = clockControl.getEndTime(); while((nextSimTime != null) && (nextSimTime.compareTo(endTime) <= 0)) { clockControl.waitUntilStarted(); // update positions in physical world so that all // objects are up to date with the event time if (nextSimTime.getTime() > lastSimTime.getTime()) { double diff = nextSimTime.getImpreciseTime() - lastSimTime.getImpreciseTime(); long updatedTime = 0; while(diff > 0) { // update the kinematic state of any externally driven objects externalSync.updateStates(); double step = Math.min(DEFAULT_STEP, diff); dynamicsWorld.stepSimulation((float)step, (int)Math.ceil(step / DEFAULT_SUBSTEP), (float)DEFAULT_SUBSTEP); // keep track of how far ahead the physics engine is getting from the last processed event time updatedTime += (long)(step * TimeUnit.SECONDS.toNanos(1)); // update collisions if (contactHandler.update(lastSimTime, updatedTime)) { break; } diff -= DEFAULT_STEP; } lastSimTime = simEngine.getNextEventTime(); } if (logger.isDebugEnabled()) { logger.debug("Executing event at time: " + nextSimTime); } clockControl.notifyListeners(nextSimTime); nextSimTime = simEngine.processNextEvent(); } // cleanup hook.run(); Runtime.getRuntime().removeShutdownHook(hook); double runTime = (double)(System.currentTimeMillis() - variationStartTime) / TimeUnit.SECONDS.toMillis(1); logger.info(""); logger.info("--------------------------------------------"); logger.info("Scenario variation " + currVariation + " executed in " + runTime + " seconds."); logger.info("--------------------------------------------"); } }
public void runSim(final Scenario scenario, final World world, double realTimeScale, boolean startPaused) { int currVariation = 0; VariationIterator variations = new VariationIterator(scenario); // todo: parallelize the running of variations for (final Variation variation : variations) { final int varId = ++currVariation; logger.info(""); logger.info("--------------------------------------------"); logger.info("Executing scenario variation " + currVariation); logger.info("--------------------------------------------"); logger.info(""); final AtomicInteger nextModelId = new AtomicInteger(0); final AtomicInteger nextMotionId = new AtomicInteger(0); final Random variationSeedGenerator = new Random(variation.getSeed()); // sim engine setup final SimEngineImpl simEngine = new SimEngineImpl(realTimeScale); final ClockControl clockControl = new ClockControl(new SimTime((long)scenario.getSimulation().getEndTime() * TimeUnit.SECONDS.toMillis(1)), (scenario.getSimulation().getEpoch() != null) ? scenario.getSimulation().getEpoch() : TimeUnit.HOURS.toMillis(8)); if (startPaused) { clockControl.pause(); } // setup a new world in the physics engine CollisionConfiguration collisionConfiguration = new DefaultCollisionConfiguration(); CollisionDispatcher dispatcher = new CollisionDispatcher(collisionConfiguration); BroadphaseInterface broadphase = new DbvtBroadphase(); SequentialImpulseConstraintSolver solver = new SequentialImpulseConstraintSolver(); final DiscreteDynamicsWorld dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); dynamicsWorld.setGravity(new Vector3f(0, 0, (float)EARTH_GRAVITY)); final MotionRecorder motionRecorder = new MotionRecorder(); final ExternalStateSync externalSync = new ExternalStateSync(); // top level guice injector - all others are derived from this Module baseModule = new AbstractModule() { protected void configure() { // the variation number of this scenario variation bindConstant().annotatedWith(Names.named("variation-number")).to(varId); // scenario variation variable map bind(Variation.class).toInstance(variation); // the global access to sim engine executive bind(SimEngine.class).annotatedWith(GlobalScope.class).toInstance(simEngine); // clock controller for the sim engine bind(ClockControl.class).annotatedWith(GlobalScope.class).toInstance(clockControl); // dynamics world bind(DiscreteDynamicsWorld.class).annotatedWith(GlobalScope.class).toInstance(dynamicsWorld); // motion recorder bind(MotionRecorder.class).annotatedWith(GlobalScope.class).toInstance(motionRecorder); // external synchronizer bind(ExternalStateSync.class).annotatedWith(GlobalScope.class).toInstance(externalSync); } // todo: figure out how to get these providers to not be called for each child injector? @Provides @Named("random-seed") public long generateRandomSeed() { return variationSeedGenerator.nextLong(); } }; Injector baseInjector = Guice.createInjector(baseModule); // establish components final List<VariationComponent> varComponents = new LinkedList<VariationComponent>(); if (scenario.getComponents() != null) { for (CustomClass config : scenario.getComponents().getVariation()) { final Class compClass; final Properties compProps = loadConfigProps(config.getProperties(), variation); try { // locate the model implementation compClass = Class.forName(config.getJavaClass()); // make sure it implements Model if (!VariationComponent.class.isAssignableFrom(compClass)) { throw new RuntimeException("The component implementation must extend from VariationComponent."); } } catch(ClassNotFoundException cnf) { throw new RuntimeException("Could not locate the component class: " + config.getJavaClass(), cnf); } Injector compInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), compProps); // component class bind(VariationComponent.class).to(compClass); } }); VariationComponent component = compInjector.getInstance(VariationComponent.class); component.initialize(); varComponents.add(component); } } // setup the simulated world (obstacle, flowers, etc) final Properties worldProps = new Properties(); if (world.getProperties() != null) { for (Meta.Prop prop : world.getProperties().getProp()) { worldProps.setProperty(prop.getName(), prop.getValue()); } } baseInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { Names.bindProperties(binder(), worldProps); bind(WorldMap.class); bind(World.class).toInstance(world); bind(AtomicInteger.class).annotatedWith(Names.named("next-id")).toInstance(nextMotionId); } }); final WorldMap map = baseInjector.getInstance(WorldMap.class); map.initialize(); baseInjector = baseInjector.createChildInjector(new AbstractModule() { @Override protected void configure() { // established simulated world instance bind(WorldMap.class).annotatedWith(GlobalScope.class).toInstance(map); } }); // parse model definitions final List<Model> models = new LinkedList<Model>(); if (scenario.getModels() != null) { for (ModelConfig config : scenario.getModels().getModel()) { parseModelConfig(config, null, null, models, variation, baseInjector, nextModelId, nextMotionId); } } for (Model model : models) { simEngine.addModel(model); } // initialize all models for (Model model : models) { model.initialize(); } // setup a handler for dealing with contacts and informing objects // of when they collide ContactHandler contactHandler = new ContactHandler(dynamicsWorld, simEngine); // add a shutdown hook final AtomicBoolean cleaned = new AtomicBoolean(false); final Lock cleanupLock = new ReentrantLock(); Thread hook = new Thread() { @Override public void run() { cleanupLock.lock(); try { if (!cleaned.get()) { // clean out any events simEngine.shutdown(); // breakdown services, models, and components map.destroy(); for (Model m : models) { m.finish(); if (m instanceof PhysicalEntity) { ((PhysicalEntity)m).destroy(); } } for (VariationComponent comp : varComponents) { comp.shutdown(); } motionRecorder.shutdown(); cleaned.set(true); } } finally { cleanupLock.unlock(); } } }; Runtime.getRuntime().addShutdownHook(hook); // run it long variationStartTime = System.currentTimeMillis(); SimTime lastSimTime = new SimTime(0); SimTime nextSimTime = simEngine.getNextEventTime(); SimTime endTime = clockControl.getEndTime(); while((nextSimTime != null) && (nextSimTime.compareTo(endTime) <= 0)) { clockControl.waitUntilStarted(); // update positions in physical world so that all // objects are up to date with the event time if (nextSimTime.getTime() > lastSimTime.getTime()) { double diff = nextSimTime.getImpreciseTime() - lastSimTime.getImpreciseTime(); long updatedTime = 0; while(diff > 0) { // update the kinematic state of any externally driven objects externalSync.updateStates(); double step = Math.min(DEFAULT_STEP, diff); dynamicsWorld.stepSimulation((float)step, (int)Math.ceil(step / DEFAULT_SUBSTEP), (float)DEFAULT_SUBSTEP); // keep track of how far ahead the physics engine is getting from the last processed event time updatedTime += (long)(step * TimeUnit.SECONDS.toNanos(1)); // update collisions if (contactHandler.update(lastSimTime, updatedTime)) { break; } diff -= DEFAULT_STEP; } lastSimTime = simEngine.getNextEventTime(); } if (logger.isDebugEnabled()) { logger.debug("Executing event at time: " + nextSimTime); } clockControl.notifyListeners(nextSimTime); nextSimTime = simEngine.processNextEvent(); } // cleanup hook.run(); Runtime.getRuntime().removeShutdownHook(hook); double runTime = (double)(System.currentTimeMillis() - variationStartTime) / TimeUnit.SECONDS.toMillis(1); logger.info(""); logger.info("--------------------------------------------"); logger.info("Scenario variation " + currVariation + " executed in " + runTime + " seconds."); logger.info("--------------------------------------------"); } }
diff --git a/src/ru/spbau/bioinf/tagfinder/Scan.java b/src/ru/spbau/bioinf/tagfinder/Scan.java index 9021c3c..7544d7d 100644 --- a/src/ru/spbau/bioinf/tagfinder/Scan.java +++ b/src/ru/spbau/bioinf/tagfinder/Scan.java @@ -1,59 +1,61 @@ package ru.spbau.bioinf.tagfinder; import ru.spbau.bioinf.tagfinder.util.ReaderUtil; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class Scan { private int id; private List<Peak> peaks = new ArrayList<Peak>(); private double precursorMz; private int precursorCharge; private double precursorMass; public Scan(Properties prop, BufferedReader input, int scanId) throws IOException { id = scanId; precursorCharge = ReaderUtil.getIntValue(prop, "CHARGE"); precursorMass = ReaderUtil.getDoubleValue(prop, "MONOISOTOPIC_MASS"); List<String[]> datas; + peaks.add(new Peak(0, 0 , 0)); while ((datas = ReaderUtil.readDataUntil(input, "END ENVELOPE")).size() > 0) { double mass = 0; double score = 0; int charge = 0; for (String[] data : datas) { if (data.length > 3) { if ("REAL_MONO_MASS".equals(data[2])) { mass = Double.parseDouble(data[3]); } } if ("CHARGE".equals(data[0])) { charge = Integer.parseInt(data[1]); } if ("SCORE".equals(data[0])) { score = Double.parseDouble(data[1]); } } peaks.add(new Peak(mass, score , charge)); } + peaks.add(new Peak(precursorMass, 0, 0)); } public int getId() { return id; } public double getPrecursorMass() { return precursorMass; } public List<Peak> getPeaks() { return peaks; } }
false
true
public Scan(Properties prop, BufferedReader input, int scanId) throws IOException { id = scanId; precursorCharge = ReaderUtil.getIntValue(prop, "CHARGE"); precursorMass = ReaderUtil.getDoubleValue(prop, "MONOISOTOPIC_MASS"); List<String[]> datas; while ((datas = ReaderUtil.readDataUntil(input, "END ENVELOPE")).size() > 0) { double mass = 0; double score = 0; int charge = 0; for (String[] data : datas) { if (data.length > 3) { if ("REAL_MONO_MASS".equals(data[2])) { mass = Double.parseDouble(data[3]); } } if ("CHARGE".equals(data[0])) { charge = Integer.parseInt(data[1]); } if ("SCORE".equals(data[0])) { score = Double.parseDouble(data[1]); } } peaks.add(new Peak(mass, score , charge)); } }
public Scan(Properties prop, BufferedReader input, int scanId) throws IOException { id = scanId; precursorCharge = ReaderUtil.getIntValue(prop, "CHARGE"); precursorMass = ReaderUtil.getDoubleValue(prop, "MONOISOTOPIC_MASS"); List<String[]> datas; peaks.add(new Peak(0, 0 , 0)); while ((datas = ReaderUtil.readDataUntil(input, "END ENVELOPE")).size() > 0) { double mass = 0; double score = 0; int charge = 0; for (String[] data : datas) { if (data.length > 3) { if ("REAL_MONO_MASS".equals(data[2])) { mass = Double.parseDouble(data[3]); } } if ("CHARGE".equals(data[0])) { charge = Integer.parseInt(data[1]); } if ("SCORE".equals(data[0])) { score = Double.parseDouble(data[1]); } } peaks.add(new Peak(mass, score , charge)); } peaks.add(new Peak(precursorMass, 0, 0)); }
diff --git a/src/main/java/de/cismet/cids/custom/wunda_blau/search/BaulastWindowSearch.java b/src/main/java/de/cismet/cids/custom/wunda_blau/search/BaulastWindowSearch.java index 4405c2cc..314beb9a 100644 --- a/src/main/java/de/cismet/cids/custom/wunda_blau/search/BaulastWindowSearch.java +++ b/src/main/java/de/cismet/cids/custom/wunda_blau/search/BaulastWindowSearch.java @@ -1,607 +1,607 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * BaulastWindowSearch.java * * Created on 09.12.2010, 14:33:10 */ package de.cismet.cids.custom.wunda_blau.search; import de.cismet.cids.custom.wunda_blau.search.server.FlurstueckInfo; import de.cismet.cids.custom.wunda_blau.search.server.BaulastSearchInfo; import de.cismet.cids.custom.wunda_blau.search.server.CidsBaulastSearchStatement; import Sirius.navigator.actiontag.ActionTagProtected; import Sirius.navigator.connection.SessionManager; import Sirius.navigator.exception.ConnectionException; import Sirius.navigator.method.MethodManager; import Sirius.server.middleware.types.MetaClass; import Sirius.server.middleware.types.MetaObject; import Sirius.server.middleware.types.Node; import Sirius.server.search.CidsServerSearch; import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.SwingWorker; import de.cismet.cids.custom.objecteditors.wunda_blau.FlurstueckSelectionDialoge; import de.cismet.cids.custom.objectrenderer.utils.CidsBeanSupport; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.editors.DefaultBindableReferenceCombo; import de.cismet.cids.navigator.utils.CidsBeanDropListener; import de.cismet.cids.navigator.utils.CidsBeanDropTarget; import de.cismet.cids.navigator.utils.ClassCacheMultiple; import de.cismet.cids.tools.search.clientstuff.CidsWindowSearch; import de.cismet.cismap.commons.BoundingBox; import de.cismet.cismap.commons.features.Feature; import de.cismet.cismap.commons.interaction.CismapBroker; import de.cismet.cismap.navigatorplugin.CidsFeature; import de.cismet.tools.CismetThreadPool; /** * DOCUMENT ME! * * @author stefan * @version $Revision$, $Date$ */ @org.openide.util.lookup.ServiceProvider(service = CidsWindowSearch.class) public class BaulastWindowSearch extends javax.swing.JPanel implements CidsWindowSearch, CidsBeanDropListener, ActionTagProtected { //~ Static fields/initializers --------------------------------------------- static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(BaulastWindowSearch.class); //~ Instance fields -------------------------------------------------------- private final MetaClass mc; private final ImageIcon icon; private final FlurstueckSelectionDialoge fsSelectionDialoge; private final DefaultListModel model; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAddFS; private javax.swing.JButton btnFromMapFS; private javax.swing.JButton btnRemoveFS; private javax.swing.JButton btnSearch; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JComboBox cbArt; private javax.swing.JCheckBox chkBeguenstigt; private javax.swing.JCheckBox chkBelastet; private javax.swing.JCheckBox chkGeloescht; private javax.swing.JCheckBox chkGueltig; private javax.swing.JCheckBox chkKartenausschnitt; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private org.jdesktop.swingx.JXBusyLabel lblBusy; private javax.swing.JList lstFlurstueck; private javax.swing.JPanel panCommand; private javax.swing.JPanel panSearch; private javax.swing.JRadioButton rbBaulastBlaetter; private javax.swing.JRadioButton rbBaulasten; private javax.swing.JTextField txtBlattnummer; // End of variables declaration//GEN-END:variables //~ Constructors ----------------------------------------------------------- /** * Creates new form BaulastWindowSearch. */ public BaulastWindowSearch() { mc = ClassCacheMultiple.getMetaClass(CidsBeanSupport.DOMAIN_NAME, "ALB_BAULAST"); icon = new ImageIcon(mc.getIconData()); fsSelectionDialoge = new FlurstueckSelectionDialoge(false) { @Override public void okHook() { final List<CidsBean> result = getCurrentListToAdd(); if (result.size() > 0) { model.addElement(result.get(0)); } } }; initComponents(); final MetaClass artMC = ClassCacheMultiple.getMetaClass("WUNDA_BLAU", "ALB_BAULAST_ART"); final DefaultComboBoxModel cbArtModel; try { cbArtModel = DefaultBindableReferenceCombo.getModelByMetaClass(artMC, true); cbArt.setModel(cbArtModel); } catch (Exception ex) { log.error(ex, ex); } model = new DefaultListModel(); lstFlurstueck.setModel(model); AutoCompleteDecorator.decorate(cbArt); new CidsBeanDropTarget(this); fsSelectionDialoge.pack(); fsSelectionDialoge.setLocationRelativeTo(this); } //~ Methods ---------------------------------------------------------------- /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroup1 = new javax.swing.ButtonGroup(); panSearch = new javax.swing.JPanel(); panCommand = new javax.swing.JPanel(); lblBusy = new org.jdesktop.swingx.JXBusyLabel(); btnSearch = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); chkGeloescht = new javax.swing.JCheckBox(); chkGueltig = new javax.swing.JCheckBox(); cbArt = new javax.swing.JComboBox(); txtBlattnummer = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); lstFlurstueck = new javax.swing.JList(); btnAddFS = new javax.swing.JButton(); btnRemoveFS = new javax.swing.JButton(); btnFromMapFS = new javax.swing.JButton(); chkBeguenstigt = new javax.swing.JCheckBox(); chkBelastet = new javax.swing.JCheckBox(); chkKartenausschnitt = new javax.swing.JCheckBox(); jPanel4 = new javax.swing.JPanel(); rbBaulastBlaetter = new javax.swing.JRadioButton(); rbBaulasten = new javax.swing.JRadioButton(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); setMaximumSize(new java.awt.Dimension(325, 460)); setMinimumSize(new java.awt.Dimension(325, 460)); setPreferredSize(new java.awt.Dimension(325, 460)); setLayout(new java.awt.BorderLayout()); panSearch.setMaximumSize(new java.awt.Dimension(400, 150)); panSearch.setMinimumSize(new java.awt.Dimension(400, 150)); panSearch.setPreferredSize(new java.awt.Dimension(400, 150)); panSearch.setLayout(new java.awt.GridBagLayout()); panCommand.add(lblBusy); btnSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N btnSearch.setText("Suchen"); btnSearch.setToolTipText("Suche starten"); btnSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSearchActionPerformed(evt); } }); panCommand.add(btnSearch); jPanel1.setMaximumSize(new java.awt.Dimension(26, 26)); jPanel1.setMinimumSize(new java.awt.Dimension(26, 26)); jPanel1.setPreferredSize(new java.awt.Dimension(26, 26)); panCommand.add(jPanel1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(panCommand, gridBagConstraints); - jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Attribut Filter")); + jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Attributfilter")); jPanel2.setLayout(new java.awt.GridBagLayout()); chkGeloescht.setSelected(true); chkGeloescht.setText("gelöscht / geschlossen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(chkGeloescht, gridBagConstraints); chkGueltig.setSelected(true); chkGueltig.setText("gültig"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(chkGueltig, gridBagConstraints); cbArt.setEditable(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(cbArt, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(txtBlattnummer, gridBagConstraints); jLabel1.setText("Blattnummer:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel1, gridBagConstraints); jLabel2.setText("Art der Baulast:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(jPanel2, gridBagConstraints); - jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Flurstück Filter")); + jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Flurstückfilter")); jPanel3.setLayout(new java.awt.GridBagLayout()); jScrollPane1.setMaximumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setMinimumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setPreferredSize(new java.awt.Dimension(200, 100)); jScrollPane1.setViewportView(lstFlurstueck); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.gridheight = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jScrollPane1, gridBagConstraints); btnAddFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-add.png"))); // NOI18N btnAddFS.setToolTipText("Flurstück hinzufügen"); btnAddFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(btnAddFS, gridBagConstraints); btnRemoveFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-delete.png"))); // NOI18N btnRemoveFS.setToolTipText("Ausgewählte Flurstücke entfernen"); btnRemoveFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(btnRemoveFS, gridBagConstraints); btnFromMapFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/bookmark-new.png"))); // NOI18N btnFromMapFS.setToolTipText("Selektierte Flurstücke aus Karte hinzufügen"); btnFromMapFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFromMapFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(btnFromMapFS, gridBagConstraints); chkBeguenstigt.setSelected(true); chkBeguenstigt.setText("begünstigt"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(chkBeguenstigt, gridBagConstraints); chkBelastet.setSelected(true); chkBelastet.setText("belastet"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(chkBelastet, gridBagConstraints); chkKartenausschnitt.setText("Nur im aktuellen Kartenausschnitt suchen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(chkKartenausschnitt, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(jPanel3, gridBagConstraints); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Suche nach")); jPanel4.setLayout(new java.awt.GridBagLayout()); buttonGroup1.add(rbBaulastBlaetter); rbBaulastBlaetter.setSelected(true); rbBaulastBlaetter.setText("Baulastblätter"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel4.add(rbBaulastBlaetter, gridBagConstraints); buttonGroup1.add(rbBaulasten); rbBaulasten.setText("Baulasten"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel4.add(rbBaulasten, gridBagConstraints); jPanel5.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; jPanel4.add(jPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(jPanel4, gridBagConstraints); jPanel6.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.weighty = 1.0; panSearch.add(jPanel6, gridBagConstraints); add(panSearch, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnAddFSActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddFSActionPerformed final List<CidsBean> result = new ArrayList<CidsBean>(1); fsSelectionDialoge.setCurrentListToAdd(result); fsSelectionDialoge.setVisible(true); }//GEN-LAST:event_btnAddFSActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnRemoveFSActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveFSActionPerformed final Object[] selection = lstFlurstueck.getSelectedValues(); for (final Object o : selection) { model.removeElement(o); } }//GEN-LAST:event_btnRemoveFSActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnSearchActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed performSearch(); }//GEN-LAST:event_btnSearchActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnFromMapFSActionPerformed(final java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFromMapFSActionPerformed final Collection<Feature> selFeatures = CismapBroker.getInstance() .getMappingComponent() .getFeatureCollection() .getSelectedFeatures(); for (final Feature feature : selFeatures) { if (feature instanceof CidsFeature) { final CidsFeature cf = (CidsFeature)feature; final MetaObject mo = cf.getMetaObject(); final String tableName = mo.getMetaClass().getTableName(); if ("FLURSTUECK".equalsIgnoreCase(tableName) || "ALB_FLURSTUECK_KICKER".equalsIgnoreCase(tableName)) { // if ("FLURSTUECK".equalsIgnoreCase(tableName) || "ALB_FLURSTUECK_KICKER".equalsIgnoreCase(tableName) || "ALKIS_LANDPARCEL".equalsIgnoreCase(tableName)) { model.addElement(mo.getBean()); } } } }//GEN-LAST:event_btnFromMapFSActionPerformed /** * DOCUMENT ME! */ private void performSearch() { btnSearch.setEnabled(false); lblBusy.setBusy(true); final SwingWorker<Void, Void> searchWorker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { final Collection<Node> r = SessionManager.getProxy() .customServerSearch(SessionManager.getSession().getUser(), getServerSearch()); MethodManager.getManager().showSearchResults(r.toArray(new Node[r.size()]), false); return null; } @Override protected void done() { try { get(); } catch (InterruptedException ex) { log.warn(ex, ex); } catch (ExecutionException ex) { log.error(ex, ex); } finally { lblBusy.setBusy(false); btnSearch.setEnabled(true); } } }; CismetThreadPool.execute(searchWorker); } @Override public ImageIcon getIcon() { return icon; } @Override public String getName() { return "Baulast Suche"; } @Override public JComponent getSearchWindowComponent() { return this; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ private BaulastSearchInfo getBaulastInfoFromGUI() { final BaulastSearchInfo bsi = new BaulastSearchInfo(); bsi.setResult(rbBaulastBlaetter.isSelected() ? CidsBaulastSearchStatement.Result.BAULASTBLATT : CidsBaulastSearchStatement.Result.BAULAST); if (chkKartenausschnitt.isSelected()) { final BoundingBox bb = CismapBroker.getInstance().getMappingComponent().getCurrentBoundingBox(); bsi.setBounds(bb.getGeometryFromTextLineString()); } bsi.setBelastet(chkBelastet.isSelected()); bsi.setBeguenstigt(chkBeguenstigt.isSelected()); bsi.setUngueltig(chkGeloescht.isSelected()); bsi.setGueltig(chkGueltig.isSelected()); bsi.setBlattnummer(txtBlattnummer.getText()); final Object art = cbArt.getSelectedItem(); if (art != null) { bsi.setArt(art.toString()); } return bsi; } @Override public CidsServerSearch getServerSearch() { final BaulastSearchInfo bsi = getBaulastInfoFromGUI(); for (int i = 0; i < model.size(); ++i) { final CidsBean fsBean = (CidsBean)model.getElementAt(i); try { if ("ALB_FLURSTUECK_KICKER".equalsIgnoreCase(fsBean.getMetaObject().getMetaClass().getTableName())) { final FlurstueckInfo fi = new FlurstueckInfo((Integer)fsBean.getProperty("gemarkung"), (String)fsBean.getProperty("flur"), (String)fsBean.getProperty("zaehler"), (String)fsBean.getProperty("nenner")); bsi.getFlurstuecke().add(fi); } else if ("FLURSTUECK".equalsIgnoreCase(fsBean.getMetaObject().getMetaClass().getTableName())) { final CidsBean gemarkung = (CidsBean)fsBean.getProperty("gemarkungs_nr"); final FlurstueckInfo fi = new FlurstueckInfo((Integer)gemarkung.getProperty("gemarkungsnummer"), (String)fsBean.getProperty("flur"), String.valueOf(fsBean.getProperty("fstnr_z")), String.valueOf(fsBean.getProperty("fstnr_n"))); bsi.getFlurstuecke().add(fi); } // else if ("ALKIS_LANDPARCEL".equalsIgnoreCase(fsBean.getMetaObject().getMetaClass().getTableName())) { // //TODO: merke // FlurstueckInfo fi = new FlurstueckInfo(Integer.parseInt(String.valueOf(fsBean.getProperty("gemarkung"))), (String) fsBean.getProperty("flur"), String.valueOf(fsBean.getProperty("fstck_zaehler")), String.valueOf(fsBean.getProperty("fstck_nenner"))); // bsi.getFlurstuecke().add(fi); // } } catch (Exception ex) { log.error("Can not parse information from Flurstueck bean: " + fsBean, ex); } } MetaClass mc = ClassCacheMultiple.getMetaClass("WUNDA_BLAU", "ALB_BAULAST"); final int baulastClassID = mc.getID(); mc = ClassCacheMultiple.getMetaClass("WUNDA_BLAU", "ALB_BAULASTBLATT"); final int baulastblattClassID = mc.getID(); return new CidsBaulastSearchStatement(bsi,baulastClassID,baulastblattClassID); } @Override public void beansDropped(final ArrayList<CidsBean> beans) { for (final CidsBean bean : beans) { if ("FLURSTUECK".equalsIgnoreCase(bean.getMetaObject().getMetaClass().getTableName())) { // if ("FLURSTUECK".equalsIgnoreCase(bean.getMetaObject().getMetaClass().getTableName()) || "ALKIS_LANDPARCEL".equalsIgnoreCase(bean.getMetaObject().getMetaClass().getTableName())) { model.addElement(bean); } lstFlurstueck.repaint(); } } @Override public boolean checkActionTag() { try { return SessionManager.getConnection() .getConfigAttr(SessionManager.getSession().getUser(), "navigator.baulasten.search") != null; } catch (ConnectionException ex) { log.error("Can not validate ActionTag for Baulasten Suche!", ex); return false; } } }
false
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroup1 = new javax.swing.ButtonGroup(); panSearch = new javax.swing.JPanel(); panCommand = new javax.swing.JPanel(); lblBusy = new org.jdesktop.swingx.JXBusyLabel(); btnSearch = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); chkGeloescht = new javax.swing.JCheckBox(); chkGueltig = new javax.swing.JCheckBox(); cbArt = new javax.swing.JComboBox(); txtBlattnummer = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); lstFlurstueck = new javax.swing.JList(); btnAddFS = new javax.swing.JButton(); btnRemoveFS = new javax.swing.JButton(); btnFromMapFS = new javax.swing.JButton(); chkBeguenstigt = new javax.swing.JCheckBox(); chkBelastet = new javax.swing.JCheckBox(); chkKartenausschnitt = new javax.swing.JCheckBox(); jPanel4 = new javax.swing.JPanel(); rbBaulastBlaetter = new javax.swing.JRadioButton(); rbBaulasten = new javax.swing.JRadioButton(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); setMaximumSize(new java.awt.Dimension(325, 460)); setMinimumSize(new java.awt.Dimension(325, 460)); setPreferredSize(new java.awt.Dimension(325, 460)); setLayout(new java.awt.BorderLayout()); panSearch.setMaximumSize(new java.awt.Dimension(400, 150)); panSearch.setMinimumSize(new java.awt.Dimension(400, 150)); panSearch.setPreferredSize(new java.awt.Dimension(400, 150)); panSearch.setLayout(new java.awt.GridBagLayout()); panCommand.add(lblBusy); btnSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N btnSearch.setText("Suchen"); btnSearch.setToolTipText("Suche starten"); btnSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSearchActionPerformed(evt); } }); panCommand.add(btnSearch); jPanel1.setMaximumSize(new java.awt.Dimension(26, 26)); jPanel1.setMinimumSize(new java.awt.Dimension(26, 26)); jPanel1.setPreferredSize(new java.awt.Dimension(26, 26)); panCommand.add(jPanel1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(panCommand, gridBagConstraints); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Attribut Filter")); jPanel2.setLayout(new java.awt.GridBagLayout()); chkGeloescht.setSelected(true); chkGeloescht.setText("gelöscht / geschlossen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(chkGeloescht, gridBagConstraints); chkGueltig.setSelected(true); chkGueltig.setText("gültig"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(chkGueltig, gridBagConstraints); cbArt.setEditable(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(cbArt, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(txtBlattnummer, gridBagConstraints); jLabel1.setText("Blattnummer:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel1, gridBagConstraints); jLabel2.setText("Art der Baulast:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(jPanel2, gridBagConstraints); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Flurstück Filter")); jPanel3.setLayout(new java.awt.GridBagLayout()); jScrollPane1.setMaximumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setMinimumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setPreferredSize(new java.awt.Dimension(200, 100)); jScrollPane1.setViewportView(lstFlurstueck); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.gridheight = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jScrollPane1, gridBagConstraints); btnAddFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-add.png"))); // NOI18N btnAddFS.setToolTipText("Flurstück hinzufügen"); btnAddFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(btnAddFS, gridBagConstraints); btnRemoveFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-delete.png"))); // NOI18N btnRemoveFS.setToolTipText("Ausgewählte Flurstücke entfernen"); btnRemoveFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(btnRemoveFS, gridBagConstraints); btnFromMapFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/bookmark-new.png"))); // NOI18N btnFromMapFS.setToolTipText("Selektierte Flurstücke aus Karte hinzufügen"); btnFromMapFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFromMapFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(btnFromMapFS, gridBagConstraints); chkBeguenstigt.setSelected(true); chkBeguenstigt.setText("begünstigt"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(chkBeguenstigt, gridBagConstraints); chkBelastet.setSelected(true); chkBelastet.setText("belastet"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(chkBelastet, gridBagConstraints); chkKartenausschnitt.setText("Nur im aktuellen Kartenausschnitt suchen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(chkKartenausschnitt, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(jPanel3, gridBagConstraints); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Suche nach")); jPanel4.setLayout(new java.awt.GridBagLayout()); buttonGroup1.add(rbBaulastBlaetter); rbBaulastBlaetter.setSelected(true); rbBaulastBlaetter.setText("Baulastblätter"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel4.add(rbBaulastBlaetter, gridBagConstraints); buttonGroup1.add(rbBaulasten); rbBaulasten.setText("Baulasten"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel4.add(rbBaulasten, gridBagConstraints); jPanel5.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; jPanel4.add(jPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(jPanel4, gridBagConstraints); jPanel6.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.weighty = 1.0; panSearch.add(jPanel6, gridBagConstraints); add(panSearch, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroup1 = new javax.swing.ButtonGroup(); panSearch = new javax.swing.JPanel(); panCommand = new javax.swing.JPanel(); lblBusy = new org.jdesktop.swingx.JXBusyLabel(); btnSearch = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); chkGeloescht = new javax.swing.JCheckBox(); chkGueltig = new javax.swing.JCheckBox(); cbArt = new javax.swing.JComboBox(); txtBlattnummer = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); lstFlurstueck = new javax.swing.JList(); btnAddFS = new javax.swing.JButton(); btnRemoveFS = new javax.swing.JButton(); btnFromMapFS = new javax.swing.JButton(); chkBeguenstigt = new javax.swing.JCheckBox(); chkBelastet = new javax.swing.JCheckBox(); chkKartenausschnitt = new javax.swing.JCheckBox(); jPanel4 = new javax.swing.JPanel(); rbBaulastBlaetter = new javax.swing.JRadioButton(); rbBaulasten = new javax.swing.JRadioButton(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); setMaximumSize(new java.awt.Dimension(325, 460)); setMinimumSize(new java.awt.Dimension(325, 460)); setPreferredSize(new java.awt.Dimension(325, 460)); setLayout(new java.awt.BorderLayout()); panSearch.setMaximumSize(new java.awt.Dimension(400, 150)); panSearch.setMinimumSize(new java.awt.Dimension(400, 150)); panSearch.setPreferredSize(new java.awt.Dimension(400, 150)); panSearch.setLayout(new java.awt.GridBagLayout()); panCommand.add(lblBusy); btnSearch.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N btnSearch.setText("Suchen"); btnSearch.setToolTipText("Suche starten"); btnSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSearchActionPerformed(evt); } }); panCommand.add(btnSearch); jPanel1.setMaximumSize(new java.awt.Dimension(26, 26)); jPanel1.setMinimumSize(new java.awt.Dimension(26, 26)); jPanel1.setPreferredSize(new java.awt.Dimension(26, 26)); panCommand.add(jPanel1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(panCommand, gridBagConstraints); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Attributfilter")); jPanel2.setLayout(new java.awt.GridBagLayout()); chkGeloescht.setSelected(true); chkGeloescht.setText("gelöscht / geschlossen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(chkGeloescht, gridBagConstraints); chkGueltig.setSelected(true); chkGueltig.setText("gültig"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(chkGueltig, gridBagConstraints); cbArt.setEditable(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(cbArt, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(txtBlattnummer, gridBagConstraints); jLabel1.setText("Blattnummer:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel1, gridBagConstraints); jLabel2.setText("Art der Baulast:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel2.add(jLabel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(jPanel2, gridBagConstraints); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Flurstückfilter")); jPanel3.setLayout(new java.awt.GridBagLayout()); jScrollPane1.setMaximumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setMinimumSize(new java.awt.Dimension(200, 100)); jScrollPane1.setPreferredSize(new java.awt.Dimension(200, 100)); jScrollPane1.setViewportView(lstFlurstueck); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.gridheight = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(jScrollPane1, gridBagConstraints); btnAddFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-add.png"))); // NOI18N btnAddFS.setToolTipText("Flurstück hinzufügen"); btnAddFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(btnAddFS, gridBagConstraints); btnRemoveFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit-delete.png"))); // NOI18N btnRemoveFS.setToolTipText("Ausgewählte Flurstücke entfernen"); btnRemoveFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoveFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(btnRemoveFS, gridBagConstraints); btnFromMapFS.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/bookmark-new.png"))); // NOI18N btnFromMapFS.setToolTipText("Selektierte Flurstücke aus Karte hinzufügen"); btnFromMapFS.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFromMapFSActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(btnFromMapFS, gridBagConstraints); chkBeguenstigt.setSelected(true); chkBeguenstigt.setText("begünstigt"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(chkBeguenstigt, gridBagConstraints); chkBelastet.setSelected(true); chkBelastet.setText("belastet"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(chkBelastet, gridBagConstraints); chkKartenausschnitt.setText("Nur im aktuellen Kartenausschnitt suchen"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel3.add(chkKartenausschnitt, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(jPanel3, gridBagConstraints); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Suche nach")); jPanel4.setLayout(new java.awt.GridBagLayout()); buttonGroup1.add(rbBaulastBlaetter); rbBaulastBlaetter.setSelected(true); rbBaulastBlaetter.setText("Baulastblätter"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel4.add(rbBaulastBlaetter, gridBagConstraints); buttonGroup1.add(rbBaulasten); rbBaulasten.setText("Baulasten"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel4.add(rbBaulasten, gridBagConstraints); jPanel5.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; jPanel4.add(jPanel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); panSearch.add(jPanel4, gridBagConstraints); jPanel6.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.weighty = 1.0; panSearch.add(jPanel6, gridBagConstraints); add(panSearch, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/org/jbs/happysad/More.java b/src/org/jbs/happysad/More.java index 122550e..ace88e0 100644 --- a/src/org/jbs/happysad/More.java +++ b/src/org/jbs/happysad/More.java @@ -1,187 +1,187 @@ package org.jbs.happysad; import static android.provider.BaseColumns._ID; import static org.jbs.happysad.Constants.EMO; import static org.jbs.happysad.Constants.LAT; import static org.jbs.happysad.Constants.LONG; import static org.jbs.happysad.Constants.MSG; import static org.jbs.happysad.Constants.TABLE_NAME; import static org.jbs.happysad.Constants.TIME; import android.app.Activity; import android.content.Context; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.widget.EditText; import android.widget.TextView; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; public class More extends Activity implements OnKeyListener, OnClickListener { private static final String TAG = "there's more screen"; private static String[] FROM = { _ID, LAT, LONG, EMO, MSG, TIME, }; private static String ORDER_BY = TIME + " DESC"; private HappyData updates; int emotion = -1; String extradata; public void onCreate(Bundle savedInstanceState) { //basic stuff Log.d(TAG, "entering oncreate"); super.onCreate(savedInstanceState); setContentView(R.layout.more); //figure out whether they clicked happy or sad Intent sender = getIntent(); extradata = sender.getExtras().getString("Clicked"); //emotion is an int, Clicked gets you a string emotion = sender.getExtras().getInt("Emotion"); //for now, we're showing "happy" or "sad" depending on what the previous click was. TextView t = (TextView) findViewById(R.id.more_text); t.setText(extradata); //Setting up the layout etc EditText textField = (EditText)findViewById(R.id.more_textbox); textField.setOnKeyListener(this); TextView locationView = (TextView) findViewById(R.id.location); locationView.setText("unknown"); //now we're getting a handle on the database updates = new HappyData(this); //setting up buttons View submitButton = findViewById(R.id.more_to_dash); submitButton.setOnClickListener(this); // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates Log.d(TAG, "creating a new location listner"); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location // provider. makeUseOfNewLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; // Register the listener with the Location Manager to receive location // updates Log.d(TAG, "Registration of listener"); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); //SAHAR STORE FROM HERE!! try { - Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); + Location location = new Location(LocationManager.GPS_PROVIDER); double longitude = location.getLongitude(); double latitude = location.getLatitude(); makeUseOfNewLocation(location); } catch (Exception e){ // Remove the listener you previously added Log.d(TAG, "Error"); } locationManager.removeUpdates(locationListener); } private void makeUseOfNewLocation(Location location) { Log.d(TAG, "entering makeuseofnewlocatoin"); int x = 0; System.out.println(x); double longitude = location.getLongitude(); double latitude = location.getLatitude(); TextView locationView = (TextView) findViewById(R.id.location); locationView.setText("unknown"); locationView.setText("lat = " + latitude + " long = " + longitude); locationView.invalidate(); } public void onClick(View v) { Log.d(TAG, "clicked" + v.getId()); System.out.println(TAG + "clicked" + v.getId()); switch (v.getId()) { case R.id.more_to_dash: Intent i = new Intent(this, Dashboard.class); String userstring = ((TextView) findViewById(R.id.more_textbox)).getText().toString(); try { saveUpdate(userstring); } finally { updates.close(); } i.putExtra("textboxmessage", userstring); i.putExtra("happysaddata", extradata); Log.d(TAG, "adding " + userstring + " to intent"); startActivity(i); break; } } private void saveUpdate(String msg){ SQLiteDatabase db = updates.getWritableDatabase(); ContentValues values = basicValues(emotion); values.put(MSG, msg); db.insertOrThrow(TABLE_NAME, null, values); Log.d(TAG, "saved update to db"); updates.close(); } // got following code from // http://stackoverflow.com/questions/2004344/android-edittext-imeoptions-done-track-finish-typing public boolean onKey(View v, int keyCode, KeyEvent event) { if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // Done pressed! Do something here. EditText t = (EditText) v; Log.d(TAG, "text entered: " + t.getText()); this.onClick(findViewById(R.id.more_to_dash)); // Intent i = new Intent(this, prompt.class); // startActivity(i); } // Returning false allows other listeners to react to the press. return false; } private ContentValues basicValues(int emo){ //for basic updates ContentValues values = new ContentValues(); values.put(TIME, System.currentTimeMillis()); //values.put(LAT, <latitude>); //values.put(LONG, <longitude>); values.put(EMO, emo); return values; } }
true
true
public void onCreate(Bundle savedInstanceState) { //basic stuff Log.d(TAG, "entering oncreate"); super.onCreate(savedInstanceState); setContentView(R.layout.more); //figure out whether they clicked happy or sad Intent sender = getIntent(); extradata = sender.getExtras().getString("Clicked"); //emotion is an int, Clicked gets you a string emotion = sender.getExtras().getInt("Emotion"); //for now, we're showing "happy" or "sad" depending on what the previous click was. TextView t = (TextView) findViewById(R.id.more_text); t.setText(extradata); //Setting up the layout etc EditText textField = (EditText)findViewById(R.id.more_textbox); textField.setOnKeyListener(this); TextView locationView = (TextView) findViewById(R.id.location); locationView.setText("unknown"); //now we're getting a handle on the database updates = new HappyData(this); //setting up buttons View submitButton = findViewById(R.id.more_to_dash); submitButton.setOnClickListener(this); // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates Log.d(TAG, "creating a new location listner"); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location // provider. makeUseOfNewLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; // Register the listener with the Location Manager to receive location // updates Log.d(TAG, "Registration of listener"); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); //SAHAR STORE FROM HERE!! try { Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); double longitude = location.getLongitude(); double latitude = location.getLatitude(); makeUseOfNewLocation(location); } catch (Exception e){ // Remove the listener you previously added Log.d(TAG, "Error"); } locationManager.removeUpdates(locationListener); }
public void onCreate(Bundle savedInstanceState) { //basic stuff Log.d(TAG, "entering oncreate"); super.onCreate(savedInstanceState); setContentView(R.layout.more); //figure out whether they clicked happy or sad Intent sender = getIntent(); extradata = sender.getExtras().getString("Clicked"); //emotion is an int, Clicked gets you a string emotion = sender.getExtras().getInt("Emotion"); //for now, we're showing "happy" or "sad" depending on what the previous click was. TextView t = (TextView) findViewById(R.id.more_text); t.setText(extradata); //Setting up the layout etc EditText textField = (EditText)findViewById(R.id.more_textbox); textField.setOnKeyListener(this); TextView locationView = (TextView) findViewById(R.id.location); locationView.setText("unknown"); //now we're getting a handle on the database updates = new HappyData(this); //setting up buttons View submitButton = findViewById(R.id.more_to_dash); submitButton.setOnClickListener(this); // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates Log.d(TAG, "creating a new location listner"); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location // provider. makeUseOfNewLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; // Register the listener with the Location Manager to receive location // updates Log.d(TAG, "Registration of listener"); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); //SAHAR STORE FROM HERE!! try { Location location = new Location(LocationManager.GPS_PROVIDER); double longitude = location.getLongitude(); double latitude = location.getLatitude(); makeUseOfNewLocation(location); } catch (Exception e){ // Remove the listener you previously added Log.d(TAG, "Error"); } locationManager.removeUpdates(locationListener); }
diff --git a/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/MethodImpl.java b/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/MethodImpl.java index 63f593637..220a8751c 100644 --- a/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/MethodImpl.java +++ b/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/MethodImpl.java @@ -1,670 +1,672 @@ package org.eclipse.jdi.internal; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.eclipse.jdi.internal.jdwp.JdwpCommandPacket; import org.eclipse.jdi.internal.jdwp.JdwpMethodID; import org.eclipse.jdi.internal.jdwp.JdwpReplyPacket; import com.sun.jdi.AbsentInformationException; import com.sun.jdi.ClassNotLoadedException; import com.sun.jdi.InvalidCodeIndexException; import com.sun.jdi.InvalidLineNumberException; import com.sun.jdi.Locatable; import com.sun.jdi.Location; import com.sun.jdi.Method; import com.sun.jdi.Type; /** * this class implements the corresponding interfaces * declared by the JDI specification. See the com.sun.jdi package * for more information. * */ public class MethodImpl extends TypeComponentImpl implements Method, Locatable { /** InvokeOptions Constants. */ public static final int INVOKE_SINGLE_THREADED_JDWP = 0x01; public static final int INVOKE_NONVIRTUAL_JDWP = 0x02; /** Map with Strings for flag bits. */ private static Vector fInvokeOptionsVector = null; /** MethodTypeID that corresponds to this reference. */ private JdwpMethodID fMethodID; /** The following are the stored results of JDWP calls. */ private Vector fVariables = null; private long fLowestValidCodeIndex = -1; private long fHighestValidCodeIndex = -1; private HashMap fCodeIndexToLine = null; private Vector fLineToCodeIndexes = null; private Vector fAllLineLocations = null; private int fArgumentSlotsCount = -1; private Vector fArguments = null; private Vector fArgumentTypes = null; private Vector fArgumentTypeNames = null; private Vector fArgumentTypeSignatures = null; private byte[] fByteCodes = null; /** * Creates new MethodImpl. */ public MethodImpl(VirtualMachineImpl vmImpl, ReferenceTypeImpl declaringType, JdwpMethodID methodID, String name, String signature, int modifierBits) { super("Method", vmImpl, declaringType, name, signature, modifierBits); //$NON-NLS-1$ fMethodID = methodID; } /** * Flushes all stored Jdwp results. */ public void flushStoredJdwpResults() { fVariables = null; fLowestValidCodeIndex = -1; fHighestValidCodeIndex = -1; fCodeIndexToLine = null; fLineToCodeIndexes = null; fAllLineLocations = null; fArgumentSlotsCount = -1; fArguments = null; fArgumentTypes = null; fArgumentTypeNames = null; fArgumentTypeSignatures = null; fByteCodes = null; } /** * @return Returns methodID of method. */ public JdwpMethodID getMethodID() { return fMethodID; } /** * @return Returns map of location to line number. */ public HashMap codeIndexToLine() throws AbsentInformationException { getLineTable(); return fCodeIndexToLine; } /** * @return Returns map of line number to locations. */ public Vector lineToCodeIndexes(int line) throws AbsentInformationException { getLineTable(); if (fLineToCodeIndexes.size() <= line) return null; return (Vector)fLineToCodeIndexes.get(line); } /** * Gets line table from VM. */ private void getLineTable() throws AbsentInformationException { if (isObsolete()) { return; } if (fCodeIndexToLine != null) { if (fCodeIndexToLine.isEmpty()) throw new AbsentInformationException(JDIMessages.getString("MethodImpl.Got_empty_line_number_table_for_this_method_1")); //$NON-NLS-1$ else return; } initJdwpRequest(); try { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); DataOutputStream outData = new DataOutputStream(outBytes); writeWithReferenceType(this, outData); JdwpReplyPacket replyPacket = requestVM(JdwpCommandPacket.M_LINE_TABLE, outBytes); switch (replyPacket.errorCode()) { case JdwpReplyPacket.ABSENT_INFORMATION: throw new AbsentInformationException(JDIMessages.getString("MethodImpl.No_line_number_information_available_2")); //$NON-NLS-1$ + case JdwpReplyPacket.NATIVE_METHOD: + throw new AbsentInformationException(JDIMessages.getString("MethodImpl.No_line_number_information_available_2")); //$NON-NLS-1$ } defaultReplyErrorHandler(replyPacket.errorCode()); DataInputStream replyData = replyPacket.dataInStream(); fLowestValidCodeIndex = readLong("lowest index", replyData); //$NON-NLS-1$ fHighestValidCodeIndex = readLong("highest index", replyData); //$NON-NLS-1$ int nrOfElements = readInt("elements", replyData); //$NON-NLS-1$ fCodeIndexToLine = new HashMap(); fLineToCodeIndexes = new Vector(); if (nrOfElements == 0) throw new AbsentInformationException(JDIMessages.getString("MethodImpl.Got_empty_line_number_table_for_this_method_3")); //$NON-NLS-1$ for (int i = 0; i < nrOfElements; i++) { long lineCodeIndex = readLong("code index", replyData); //$NON-NLS-1$ Long lineCodeIndexLong = new Long(lineCodeIndex); int lineNr = readInt("line nr", replyData); //$NON-NLS-1$ Integer lineNrInt = new Integer(lineNr); // Add entry to code-index to line mapping. fCodeIndexToLine.put(lineCodeIndexLong, lineNrInt); // Add entry to line to code-index mapping. if (fLineToCodeIndexes.size() <= lineNr) fLineToCodeIndexes.setSize(lineNr + 1); if (fLineToCodeIndexes.get(lineNr) == null) fLineToCodeIndexes.set(lineNr, new Vector()); Vector lineNrEntry = (Vector)fLineToCodeIndexes.get(lineNr); lineNrEntry.add(lineCodeIndexLong); } } catch (IOException e) { fCodeIndexToLine = null; fLineToCodeIndexes = null; defaultIOExceptionHandler(e); } finally { handledJdwpRequest(); } } /** * @return Returns the line number that corresponds to the given lineCodeIndex. */ public int findLineNr(long lineCodeIndex) throws AbsentInformationException { if (isObsolete()) { return -1; } getLineTable(); if (lineCodeIndex > fHighestValidCodeIndex) throw new InvalidCodeIndexException (JDIMessages.getString("MethodImpl.Invalid_code_index_of_a_location_given_4")); //$NON-NLS-1$ Long lineCodeIndexObj; Integer lineNrObj; // Search for the line where this code index is located. do { lineCodeIndexObj = new Long(lineCodeIndex); lineNrObj = (Integer)codeIndexToLine().get(lineCodeIndexObj); } while (lineNrObj == null && --lineCodeIndex >= fLowestValidCodeIndex); if (lineNrObj == null) throw new InvalidCodeIndexException (JDIMessages.getString("MethodImpl.Invalid_code_index_of_a_location_given_4")); //$NON-NLS-1$ return lineNrObj.intValue(); } /** * @return Returns the beginning Location objects for each executable source line in this method. */ public List allLineLocations() throws AbsentInformationException { if (fAllLineLocations != null) return fAllLineLocations; Iterator locations = codeIndexToLine().keySet().iterator(); Vector result = new Vector(); while (locations.hasNext()) { Long lineCodeIndex = (Long)locations.next(); result.add(new LocationImpl(virtualMachineImpl(), this, lineCodeIndex.longValue())); } fAllLineLocations = result; return fAllLineLocations; } /** * @return Returns a list containing each LocalVariable that is declared as an argument of this method. */ public List arguments() throws AbsentInformationException { if (fArguments != null) return fArguments; Vector result = new Vector(); Iterator iter = variables().iterator(); while (iter.hasNext()) { LocalVariableImpl var = (LocalVariableImpl)iter.next(); if (var.isArgument()) result.add(var); } fArguments = result; return fArguments; } /** * @return Returns a text representation of all declared argument types of this method. */ public List argumentTypeNames() { if (fArgumentTypeNames != null) return fArgumentTypeNames; // Get typenames from method signatures. Vector result = new Vector(); Iterator iter = argumentTypeSignatures().iterator(); while (iter.hasNext()) { String name = TypeImpl.signatureToName((String)iter.next()); result.add(name); } fArgumentTypeNames = result; return fArgumentTypeNames; } /** * @return Returns a signatures of all declared argument types of this method. */ private List argumentTypeSignatures() { if (fArgumentTypeSignatures != null) return fArgumentTypeSignatures; Vector result = new Vector(); int index = 1; // Start position is just after the starting brace. int endIndex = signature().lastIndexOf(')') - 1; // End position is just before ending brace. while (index <= endIndex) { int typeLen = TypeImpl.signatureTypeStringLength(signature(), index); result.add(signature().substring(index, index + typeLen)); index += typeLen; } fArgumentTypeSignatures = result; return fArgumentTypeSignatures; } /** * @return Returns the list containing the type of each argument. */ public List argumentTypes() throws ClassNotLoadedException { if (fArgumentTypes != null) return fArgumentTypes; Vector result = new Vector(); Iterator iter = argumentTypeSignatures().iterator(); while (iter.hasNext()) { String argumentTypeSignature = (String)iter.next(); result.add(TypeImpl.create(virtualMachineImpl(), argumentTypeSignature, declaringType().classLoader())); } fArgumentTypes = result; return fArgumentTypes; } /** * @return Returns an array containing the bytecodes for this method. */ public byte bytecodes()[] { if (fByteCodes != null) return fByteCodes; initJdwpRequest(); try { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); DataOutputStream outData = new DataOutputStream(outBytes); writeWithReferenceType(this, outData); JdwpReplyPacket replyPacket = requestVM(JdwpCommandPacket.M_BYTECODES, outBytes); defaultReplyErrorHandler(replyPacket.errorCode()); DataInputStream replyData = replyPacket.dataInStream(); int length = readInt("length", replyData); //$NON-NLS-1$ fByteCodes = readByteArray(length, "bytecodes", replyData); //$NON-NLS-1$ return fByteCodes; } catch (IOException e) { fByteCodes = null; defaultIOExceptionHandler(e); return null; } finally { handledJdwpRequest(); } } /** * @return Returns the hash code value. */ public int hashCode() { return fMethodID.hashCode(); } /** * @return Returns true if two mirrors refer to the same entity in the target VM. * @see java.lang.Object#equals(Object) */ public boolean equals(Object object) { return object != null && object.getClass().equals(this.getClass()) && fMethodID.equals(((MethodImpl)object).fMethodID) && referenceTypeImpl().equals(((MethodImpl)object).referenceTypeImpl()); } /** * @return Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. */ public int compareTo(Object object) { if (object == null || !object.getClass().equals(this.getClass())) throw new ClassCastException(JDIMessages.getString("MethodImpl.Can__t_compare_method_to_given_object_6")); //$NON-NLS-1$ // See if declaring types are the same, if not return comparison between declaring types. Method type2 = (Method)object; if (!declaringType().equals(type2.declaringType())) return declaringType().compareTo(type2.declaringType()); // Return comparison of position within declaring type. int index1 = declaringType().methods().indexOf(this); int index2 = type2.declaringType().methods().indexOf(type2); if (index1 < index2) return -1; else if (index1 > index2) return 1; else return 0; } /** * @return Returns true if method is abstract. */ public boolean isAbstract() { return (fModifierBits & MODIFIER_ACC_ABSTRACT) != 0; } /** * @return Returns true if method is constructor. */ public boolean isConstructor() { return name().equals("<init>"); //$NON-NLS-1$ } /** * @return Returns true if method is native. */ public boolean isNative() { return (fModifierBits & MODIFIER_ACC_NATIVE) != 0; } /** * @return Returns true if method is a static initializer. */ public boolean isStaticInitializer() { return name().equals("<clinit>"); //$NON-NLS-1$ } /** * @return Returns true if method is synchronized. */ public boolean isSynchronized() { return (fModifierBits & MODIFIER_ACC_SYNCHRONIZED) != 0; } /** * @return Returns a Location for the given code index. */ public Location locationOfCodeIndex(long index) { try { Integer lineNrInt = (Integer)codeIndexToLine().get(new Long(index)); if (lineNrInt == null) throw new InvalidCodeIndexException(); } catch (AbsentInformationException e ) { } return new LocationImpl(virtualMachineImpl(), this, index); } /** * @return Returns a list containing each Location that maps to the given line. */ public List locationsOfLine(int line) throws AbsentInformationException, InvalidLineNumberException { Vector indexes = lineToCodeIndexes(line); if (indexes == null) throw new InvalidLineNumberException(JDIMessages.getString("MethodImpl.No_executable_code_at_line__7") + line + JDIMessages.getString("MethodImpl._8")); //$NON-NLS-1$ //$NON-NLS-2$ Iterator codeIndexes = indexes.iterator(); Vector locations = new Vector(); while (codeIndexes.hasNext()) { long codeIndex = ((Long)codeIndexes.next()).longValue(); locations.add(new LocationImpl(virtualMachineImpl(), this, codeIndex)); } return locations; } /** * @return Returns the return type of the this Method. */ public Type returnType() throws ClassNotLoadedException { int startIndex = signature().lastIndexOf(')') + 1; // Signature position is just after ending brace. return TypeImpl.create(virtualMachineImpl(), signature().substring(startIndex), declaringType().classLoader()); } /** * @return Returns a text representation of the declared return type of this method. */ public String returnTypeName() { int startIndex = signature().lastIndexOf(')') + 1; // Signature position is just after ending brace. return TypeImpl.signatureToName(signature().substring(startIndex)); } /** * @return Returns a list containing each LocalVariable declared in this method. */ public List variables() throws AbsentInformationException { if (fVariables != null) return fVariables; initJdwpRequest(); try { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); DataOutputStream outData = new DataOutputStream(outBytes); writeWithReferenceType(this, outData); JdwpReplyPacket replyPacket = requestVM(JdwpCommandPacket.M_VARIABLE_TABLE, outBytes); switch (replyPacket.errorCode()) { case JdwpReplyPacket.ABSENT_INFORMATION: throw new AbsentInformationException(JDIMessages.getString("MethodImpl.No_local_variable_information_available_9")); //$NON-NLS-1$ } defaultReplyErrorHandler(replyPacket.errorCode()); DataInputStream replyData = replyPacket.dataInStream(); fArgumentSlotsCount = readInt("arg count", replyData); //$NON-NLS-1$ int nrOfElements = readInt("elements", replyData); //$NON-NLS-1$ fVariables = new Vector(nrOfElements); for (int i = 0; i < nrOfElements; i++) { long codeIndex = readLong("code index", replyData); //$NON-NLS-1$ String name = readString("name", replyData); //$NON-NLS-1$ String signature = readString("signature", replyData); //$NON-NLS-1$ int length = readInt("length", replyData); //$NON-NLS-1$ int slot = readInt("slot", replyData); //$NON-NLS-1$ boolean isArgument = slot < fArgumentSlotsCount; // Note that for static methods, the first variable will be the this reference. if (isStatic() || i > 0) { LocalVariableImpl localVar = new LocalVariableImpl(virtualMachineImpl(), this, codeIndex, name, signature, length, slot, isArgument); fVariables.add(localVar); } } return fVariables; } catch (IOException e) { fArgumentSlotsCount = -1; fVariables = null; defaultIOExceptionHandler(e); return null; } finally { handledJdwpRequest(); } } /** * @return Returns a list containing each LocalVariable of a given name in this method. */ public List variablesByName(String name) throws AbsentInformationException { Iterator iter = variables().iterator(); Vector result = new Vector(); while (iter.hasNext()) { LocalVariableImpl var = (LocalVariableImpl)iter.next(); if (var.name().equals(name)) result.add(var); } return result; } /** * @return Returns the Location of this mirror, if there is executable Java language code associated with it. */ public Location location() { // First retrieve line code table. try { getLineTable(); } catch (AbsentInformationException e) { return null; } // Return location with Lowest Valid Code Index. return new LocationImpl(virtualMachineImpl(), this, fLowestValidCodeIndex); } /** * @return Returns modifier bits of method. */ public int modifierBits() { return fModifierBits; } /** * Writes JDWP representation. */ public void write(MirrorImpl target, DataOutputStream out) throws IOException { fMethodID.write(out); if (target.fVerboseWriter != null) target.fVerboseWriter.println("method", fMethodID.value()); //$NON-NLS-1$ } /** * Writes JDWP representation, including ReferenceType. */ public void writeWithReferenceType(MirrorImpl target, DataOutputStream out) throws IOException { referenceTypeImpl().write(target, out); write(target, out); } /** * Writes JDWP representation, including ReferenceType with Tag. */ public void writeWithReferenceTypeWithTag(MirrorImpl target, DataOutputStream out) throws IOException { referenceTypeImpl().writeWithTag(target, out); write(target, out); } /** * @return Reads JDWP representation and returns new instance. */ public static MethodImpl readWithReferenceTypeWithTag(MirrorImpl target, DataInputStream in) throws IOException { VirtualMachineImpl vmImpl = target.virtualMachineImpl(); // See Location. ReferenceTypeImpl referenceType = ReferenceTypeImpl.readWithTypeTag(target, in); if (referenceType == null) return null; JdwpMethodID ID = new JdwpMethodID(vmImpl); if (target.fVerboseWriter != null) target.fVerboseWriter.println("method", ID.value()); //$NON-NLS-1$ ID.read(in); if (ID.isNull()) return null; // The method must be part of a known reference type. MethodImpl method = referenceType.findMethod(ID); if (method == null) throw new InternalError(JDIMessages.getString("MethodImpl.Got_MethodID_of_ReferenceType_that_is_not_a_member_of_the_ReferenceType_10")); //$NON-NLS-1$ return method; } /** * @return Reads JDWP representation and returns new instance. */ public static MethodImpl readWithNameSignatureModifiers(ReferenceTypeImpl target, ReferenceTypeImpl referenceType, DataInputStream in) throws IOException { VirtualMachineImpl vmImpl = target.virtualMachineImpl(); JdwpMethodID ID = new JdwpMethodID(vmImpl); ID.read(in); if (target.fVerboseWriter != null) target.fVerboseWriter.println("method", ID.value()); //$NON-NLS-1$ if (ID.isNull()) return null; String name = target.readString("name", in); //$NON-NLS-1$ String signature = target.readString("signature", in); //$NON-NLS-1$ int modifierBits = target.readInt("modifiers", AccessibleImpl.modifierVector(), in); //$NON-NLS-1$ MethodImpl mirror = new MethodImpl(vmImpl, referenceType, ID, name, signature, modifierBits); return mirror; } /** * Retrieves constant mappings. */ public static void getConstantMaps() { if (fInvokeOptionsVector != null) return; java.lang.reflect.Field[] fields = MethodImpl.class.getDeclaredFields(); fInvokeOptionsVector = new Vector(); fInvokeOptionsVector.setSize(32); // Int for (int i = 0; i < fields.length; i++) { java.lang.reflect.Field field = fields[i]; if ((field.getModifiers() & java.lang.reflect.Modifier.PUBLIC) == 0 || (field.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 || (field.getModifiers() & java.lang.reflect.Modifier.FINAL) == 0) continue; try { String name = field.getName(); int value = field.getInt(null); if (name.startsWith("INVOKE_")) { //$NON-NLS-1$ //fInvokeOptionsMap.put(intValue, name); for (int j = 0; j < fInvokeOptionsVector.size(); j++) { if ((1 << j & value) != 0) { fInvokeOptionsVector.set(j, name); break; } } } } catch (IllegalAccessException e) { // Will not occur for own class. } catch (IllegalArgumentException e) { // Should not occur. // We should take care that all public static final constants // in this class are numbers that are convertible to int. } } } /** * @return Returns a map with string representations of tags. */ public static Vector invokeOptionsVector() { getConstantMaps(); return fInvokeOptionsVector; } /** * @see Method#isObsolete() * * The JDK 1.4.0 specification states that obsolete methods * are given an ID of zero. It also states that when a method * is redefined, the new method gets the ID of the old method. * Thus, the JDWP query for isObsolete will never return true * for a non-zero method ID. The query is therefore not needed. */ public boolean isObsolete() { return (fMethodID.value() == 0); } /* * @see Method#allLineLocations(String, String) */ public List allLineLocations(String stratum, String sourceName) throws AbsentInformationException { return new ArrayList(0); } /* * @see Method#locationsOfLine(String, String, int) */ public List locationsOfLine(String stratum, String sourceName, int lineNumber) throws AbsentInformationException { return new ArrayList(0); } }
true
true
private void getLineTable() throws AbsentInformationException { if (isObsolete()) { return; } if (fCodeIndexToLine != null) { if (fCodeIndexToLine.isEmpty()) throw new AbsentInformationException(JDIMessages.getString("MethodImpl.Got_empty_line_number_table_for_this_method_1")); //$NON-NLS-1$ else return; } initJdwpRequest(); try { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); DataOutputStream outData = new DataOutputStream(outBytes); writeWithReferenceType(this, outData); JdwpReplyPacket replyPacket = requestVM(JdwpCommandPacket.M_LINE_TABLE, outBytes); switch (replyPacket.errorCode()) { case JdwpReplyPacket.ABSENT_INFORMATION: throw new AbsentInformationException(JDIMessages.getString("MethodImpl.No_line_number_information_available_2")); //$NON-NLS-1$ } defaultReplyErrorHandler(replyPacket.errorCode()); DataInputStream replyData = replyPacket.dataInStream(); fLowestValidCodeIndex = readLong("lowest index", replyData); //$NON-NLS-1$ fHighestValidCodeIndex = readLong("highest index", replyData); //$NON-NLS-1$ int nrOfElements = readInt("elements", replyData); //$NON-NLS-1$ fCodeIndexToLine = new HashMap(); fLineToCodeIndexes = new Vector(); if (nrOfElements == 0) throw new AbsentInformationException(JDIMessages.getString("MethodImpl.Got_empty_line_number_table_for_this_method_3")); //$NON-NLS-1$ for (int i = 0; i < nrOfElements; i++) { long lineCodeIndex = readLong("code index", replyData); //$NON-NLS-1$ Long lineCodeIndexLong = new Long(lineCodeIndex); int lineNr = readInt("line nr", replyData); //$NON-NLS-1$ Integer lineNrInt = new Integer(lineNr); // Add entry to code-index to line mapping. fCodeIndexToLine.put(lineCodeIndexLong, lineNrInt); // Add entry to line to code-index mapping. if (fLineToCodeIndexes.size() <= lineNr) fLineToCodeIndexes.setSize(lineNr + 1); if (fLineToCodeIndexes.get(lineNr) == null) fLineToCodeIndexes.set(lineNr, new Vector()); Vector lineNrEntry = (Vector)fLineToCodeIndexes.get(lineNr); lineNrEntry.add(lineCodeIndexLong); } } catch (IOException e) { fCodeIndexToLine = null; fLineToCodeIndexes = null; defaultIOExceptionHandler(e); } finally { handledJdwpRequest(); } }
private void getLineTable() throws AbsentInformationException { if (isObsolete()) { return; } if (fCodeIndexToLine != null) { if (fCodeIndexToLine.isEmpty()) throw new AbsentInformationException(JDIMessages.getString("MethodImpl.Got_empty_line_number_table_for_this_method_1")); //$NON-NLS-1$ else return; } initJdwpRequest(); try { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); DataOutputStream outData = new DataOutputStream(outBytes); writeWithReferenceType(this, outData); JdwpReplyPacket replyPacket = requestVM(JdwpCommandPacket.M_LINE_TABLE, outBytes); switch (replyPacket.errorCode()) { case JdwpReplyPacket.ABSENT_INFORMATION: throw new AbsentInformationException(JDIMessages.getString("MethodImpl.No_line_number_information_available_2")); //$NON-NLS-1$ case JdwpReplyPacket.NATIVE_METHOD: throw new AbsentInformationException(JDIMessages.getString("MethodImpl.No_line_number_information_available_2")); //$NON-NLS-1$ } defaultReplyErrorHandler(replyPacket.errorCode()); DataInputStream replyData = replyPacket.dataInStream(); fLowestValidCodeIndex = readLong("lowest index", replyData); //$NON-NLS-1$ fHighestValidCodeIndex = readLong("highest index", replyData); //$NON-NLS-1$ int nrOfElements = readInt("elements", replyData); //$NON-NLS-1$ fCodeIndexToLine = new HashMap(); fLineToCodeIndexes = new Vector(); if (nrOfElements == 0) throw new AbsentInformationException(JDIMessages.getString("MethodImpl.Got_empty_line_number_table_for_this_method_3")); //$NON-NLS-1$ for (int i = 0; i < nrOfElements; i++) { long lineCodeIndex = readLong("code index", replyData); //$NON-NLS-1$ Long lineCodeIndexLong = new Long(lineCodeIndex); int lineNr = readInt("line nr", replyData); //$NON-NLS-1$ Integer lineNrInt = new Integer(lineNr); // Add entry to code-index to line mapping. fCodeIndexToLine.put(lineCodeIndexLong, lineNrInt); // Add entry to line to code-index mapping. if (fLineToCodeIndexes.size() <= lineNr) fLineToCodeIndexes.setSize(lineNr + 1); if (fLineToCodeIndexes.get(lineNr) == null) fLineToCodeIndexes.set(lineNr, new Vector()); Vector lineNrEntry = (Vector)fLineToCodeIndexes.get(lineNr); lineNrEntry.add(lineCodeIndexLong); } } catch (IOException e) { fCodeIndexToLine = null; fLineToCodeIndexes = null; defaultIOExceptionHandler(e); } finally { handledJdwpRequest(); } }
diff --git a/src/com/bekvon/bukkit/residence/itemlist/ResidenceItemList.java b/src/com/bekvon/bukkit/residence/itemlist/ResidenceItemList.java index 067918e..eae10e8 100644 --- a/src/com/bekvon/bukkit/residence/itemlist/ResidenceItemList.java +++ b/src/com/bekvon/bukkit/residence/itemlist/ResidenceItemList.java @@ -1,55 +1,55 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.bekvon.bukkit.residence.itemlist; import org.bukkit.ChatColor; import com.bekvon.bukkit.residence.Residence; import com.bekvon.bukkit.residence.permissions.PermissionGroup; import com.bekvon.bukkit.residence.protection.ClaimedResidence; import java.util.Map; import org.bukkit.Material; import org.bukkit.entity.Player; /** * * @author Administrator */ public class ResidenceItemList extends ItemList { ClaimedResidence res; public ResidenceItemList(ClaimedResidence parent, ListType type) { super(type); res = parent; } private ResidenceItemList() { } public void playerListChange(Player player, Material mat, boolean resadmin) { PermissionGroup group = Residence.getPermissionManager().getGroup(player); if(resadmin || (res.getPermissions().hasResidencePermission(player, true) && group.itemListAccess())) { if(super.toggle(mat)) - player.sendMessage(ChatColor.YELLOW + Residence.getLanguage().getPhrase("ListMaterialAdd",ChatColor.GREEN + String.format("%d",mat) + ChatColor.YELLOW+"."+ChatColor.GREEN + type.toString().toLowerCase() + ChatColor.YELLOW)); + player.sendMessage(ChatColor.YELLOW + Residence.getLanguage().getPhrase("ListMaterialAdd",ChatColor.GREEN + mat.toString() + ChatColor.YELLOW+"."+ChatColor.GREEN + type.toString().toLowerCase() + ChatColor.YELLOW)); else - player.sendMessage(ChatColor.YELLOW + Residence.getLanguage().getPhrase("ListMaterialRemove",ChatColor.GREEN + String.format("%d",mat) + ChatColor.YELLOW+"."+ChatColor.GREEN + type.toString().toLowerCase() + ChatColor.YELLOW)); + player.sendMessage(ChatColor.YELLOW + Residence.getLanguage().getPhrase("ListMaterialRemove",ChatColor.GREEN + mat.toString() + ChatColor.YELLOW+"."+ChatColor.GREEN + type.toString().toLowerCase() + ChatColor.YELLOW)); } else { player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("NoPermission")); } } public static ResidenceItemList load(ClaimedResidence parent, Map<String,Object> map) { ResidenceItemList newlist = new ResidenceItemList(); newlist.res = parent; return (ResidenceItemList) ItemList.load(map, newlist); } }
false
true
public void playerListChange(Player player, Material mat, boolean resadmin) { PermissionGroup group = Residence.getPermissionManager().getGroup(player); if(resadmin || (res.getPermissions().hasResidencePermission(player, true) && group.itemListAccess())) { if(super.toggle(mat)) player.sendMessage(ChatColor.YELLOW + Residence.getLanguage().getPhrase("ListMaterialAdd",ChatColor.GREEN + String.format("%d",mat) + ChatColor.YELLOW+"."+ChatColor.GREEN + type.toString().toLowerCase() + ChatColor.YELLOW)); else player.sendMessage(ChatColor.YELLOW + Residence.getLanguage().getPhrase("ListMaterialRemove",ChatColor.GREEN + String.format("%d",mat) + ChatColor.YELLOW+"."+ChatColor.GREEN + type.toString().toLowerCase() + ChatColor.YELLOW)); } else { player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("NoPermission")); } }
public void playerListChange(Player player, Material mat, boolean resadmin) { PermissionGroup group = Residence.getPermissionManager().getGroup(player); if(resadmin || (res.getPermissions().hasResidencePermission(player, true) && group.itemListAccess())) { if(super.toggle(mat)) player.sendMessage(ChatColor.YELLOW + Residence.getLanguage().getPhrase("ListMaterialAdd",ChatColor.GREEN + mat.toString() + ChatColor.YELLOW+"."+ChatColor.GREEN + type.toString().toLowerCase() + ChatColor.YELLOW)); else player.sendMessage(ChatColor.YELLOW + Residence.getLanguage().getPhrase("ListMaterialRemove",ChatColor.GREEN + mat.toString() + ChatColor.YELLOW+"."+ChatColor.GREEN + type.toString().toLowerCase() + ChatColor.YELLOW)); } else { player.sendMessage(ChatColor.RED+Residence.getLanguage().getPhrase("NoPermission")); } }
diff --git a/src/main/java/de/lemo/dms/service/ServiceCourseDetails.java b/src/main/java/de/lemo/dms/service/ServiceCourseDetails.java index 6753dde7..32eef975 100644 --- a/src/main/java/de/lemo/dms/service/ServiceCourseDetails.java +++ b/src/main/java/de/lemo/dms/service/ServiceCourseDetails.java @@ -1,256 +1,257 @@ /** * File ./src/main/java/de/lemo/dms/service/ServiceCourseDetails.java * Lemo-Data-Management-Server for learning analytics. * Copyright (C) 2013 * Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff * * 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 * 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/>. **/ /** * File ./main/java/de/lemo/dms/service/ServiceCourseDetails.java * Date 2013-01-24 * Project Lemo Learning Analytics */ package de.lemo.dms.service; import java.util.ArrayList; import java.util.Collections; 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.core.MediaType; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import de.lemo.dms.core.config.ServerConfiguration; import de.lemo.dms.db.IDBHandler; import de.lemo.dms.db.mapping.CourseMining; import de.lemo.dms.db.mapping.abstractions.ICourseLORelation; import de.lemo.dms.db.mapping.abstractions.ILogMining; import de.lemo.dms.processing.MetaParam; import de.lemo.dms.processing.StudentHelper; import de.lemo.dms.processing.resulttype.CourseObject; import de.lemo.dms.processing.resulttype.ResultListCourseObject; import de.lemo.dms.service.responses.ResourceNotFoundException; /** * Service to get details for a single course or a list of courses. * * @author Boris Wenzlaff * @author Leonard Kappe * @author Sebastian Schwarzrock */ @Path("courses") @Produces(MediaType.APPLICATION_JSON) public class ServiceCourseDetails { private Logger logger; /** * Gets the details for a single course including id, title, description, * number of participants, time of first student-request, time of latest student-request. * * @param id Identifier of the course. * * @return A CourseObject containing the information. */ @SuppressWarnings("unchecked") @GET @Path("{cid}") public CourseObject getCourseDetails(@PathParam("cid") final Long id) { IDBHandler dbHandler = ServerConfiguration.getInstance().getMiningDbHandler(); final Session session = dbHandler.getMiningSession(); CourseMining course = (CourseMining) session.get(CourseMining.class, id); if (course == null) { throw new ResourceNotFoundException("Course " + id); } final Criteria criteria = session.createCriteria(ILogMining.class, "log"); List<Long> cid = new ArrayList<Long>(); cid.add(id); List<Long> users = new ArrayList<Long>(StudentHelper.getCourseStudentsAliasKeys(cid, new ArrayList<Long>()).values()); criteria.add(Restrictions.eq("log.course.id", id)); if(users.size() > 0) { criteria.add(Restrictions.in("log.user.id", users)); } ArrayList<ILogMining> logs = (ArrayList<ILogMining>) criteria.list(); Collections.sort(logs); Long lastTime = 0L; Long firstTime = 0L; if (logs.size() > 0) { lastTime = logs.get(logs.size() - 1).getTimestamp(); firstTime = logs.get(0).getTimestamp(); } CourseObject result = new CourseObject(course.getId(), course.getShortname(), course.getTitle(), users.size(), lastTime, firstTime, getCourseHash(id), StudentHelper.getGenderSupport(id)); //dbHandler.closeSession(session); session.close(); return result; } /** * Gets the details for a a list of courses including id, title, description, * number of participants, time of first student-request, time of latest student-request. * * @param id List of course identifiers. * * @return A List of CourseObjects containing the information. */ @GET @Path("/multi") public ResultListCourseObject getCoursesDetails(@QueryParam(MetaParam.COURSE_IDS) final List<Long> courses) { IDBHandler dbHandler = ServerConfiguration.getInstance().getMiningDbHandler(); final ArrayList<CourseObject> results = new ArrayList<CourseObject>(); - if (courses.isEmpty()) { + if (courses == null || courses.isEmpty()) { logger.debug("Courses List is empty"); return new ResultListCourseObject(results); - } else for(Long id : courses) logger.debug("Looking for Course: "+ id); + } else + for(Long id : courses) logger.debug("Looking for Course: "+ id); // Set up db-connection final Session session = dbHandler.getMiningSession(); Criteria criteria = session.createCriteria(CourseMining.class, "course"); criteria.add(Restrictions.in("course.id", courses)); @SuppressWarnings("unchecked") final ArrayList<CourseMining> ci = (ArrayList<CourseMining>) criteria.list(); Map<Long, Long> userMap = StudentHelper.getCourseStudentsAliasKeys(courses, new ArrayList<Long>()); for (CourseMining courseMining : ci) { criteria = session.createCriteria(ILogMining.class, "log"); criteria.add(Restrictions.eq("log.course.id", courseMining.getId())); if(userMap.size() > 0) { criteria.add(Restrictions.in("log.user.id", userMap.values())); } //TODO Redefine projection for max id as detachable criteria (Subselect) //DetachedCriteria sub = DetachedCriteria.forClass(ILogMining.class); // sub.setProjection(Projections.max("id")); // //criteria.add(Restrictions.eq("id",sub)); ArrayList<ILogMining> logs = (ArrayList<ILogMining>) criteria.list(); Collections.sort(logs); Long lastTime = 0L; Long firstTime = 0L; if (logs.size() > 0) { lastTime = logs.get(0).getTimestamp(); firstTime = logs.get(logs.size() - 1).getTimestamp(); } final CourseObject co = new CourseObject(courseMining.getId(), courseMining.getShortname(), courseMining.getTitle(), userMap.size(), lastTime, firstTime, getCourseHash(courseMining.getId()), StudentHelper.getGenderSupport(courseMining.getId())); results.add(co); } if (results.isEmpty()) { logger.debug("Result List is empty"); } else for(CourseObject co : results) logger.debug("Result Course: "+ co.getDescription()); session.close(); return new ResultListCourseObject(results); } /** * Gets the details for a a list of courses including id, title, description, * number of participants, time of first student-request, time of latest student-request. * * @param id List of course identifiers. * * @return A List of CourseObjects containing the information. */ @GET @Path("{cid}/hash") public Long getCourseHash(@PathParam("cid") final Long id) { IDBHandler dbHandler = ServerConfiguration.getInstance().getMiningDbHandler(); final Session session = dbHandler.getMiningSession(); CourseMining course = (CourseMining) session.get(CourseMining.class, id); if (course == null) { throw new ResourceNotFoundException("Course " + id); } Criteria criteria = session.createCriteria(ILogMining.class, "log"); List<Long> cid = new ArrayList<Long>(); cid.add(id); List<Long> users = new ArrayList<Long>(StudentHelper.getCourseStudentsRealKeys(cid, new ArrayList<Long>()).values()); criteria.add(Restrictions.eq("log.course.id", id)); if(users.size() > 0) { criteria.add(Restrictions.in("log.user.id", users)); } ArrayList<ILogMining> logs = (ArrayList<ILogMining>) criteria.list(); Collections.sort(logs); Long lastTime = 0L; Long firstTime = 0L; if (logs.size() > 0) { lastTime = logs.get(logs.size() - 1).getTimestamp(); firstTime = logs.get(0).getTimestamp(); } criteria = session.createCriteria(ICourseLORelation.class, "lor"); criteria.add(Restrictions.eq("lor.course.id", id)); ArrayList<ICourseLORelation> lor = (ArrayList<ICourseLORelation>) criteria.list(); Long hash = lastTime * 13 + firstTime * 17 + 19 * users.hashCode() + 23 * lor.hashCode(); //dbHandler.closeSession(session); session.close(); return hash; } /** * Gets the details for a a list of courses including id, title, description, * number of participants, time of first student-request, time of latest student-request. * * @param id List of course identifiers. * * @return A List of CourseObjects containing the information. */ @GET @Path("{cid}/genderSupport") public boolean getGenderSupport(@PathParam("cid") final Long id) { return StudentHelper.getGenderSupport(id); } }
false
true
public ResultListCourseObject getCoursesDetails(@QueryParam(MetaParam.COURSE_IDS) final List<Long> courses) { IDBHandler dbHandler = ServerConfiguration.getInstance().getMiningDbHandler(); final ArrayList<CourseObject> results = new ArrayList<CourseObject>(); if (courses.isEmpty()) { logger.debug("Courses List is empty"); return new ResultListCourseObject(results); } else for(Long id : courses) logger.debug("Looking for Course: "+ id); // Set up db-connection final Session session = dbHandler.getMiningSession(); Criteria criteria = session.createCriteria(CourseMining.class, "course"); criteria.add(Restrictions.in("course.id", courses)); @SuppressWarnings("unchecked") final ArrayList<CourseMining> ci = (ArrayList<CourseMining>) criteria.list(); Map<Long, Long> userMap = StudentHelper.getCourseStudentsAliasKeys(courses, new ArrayList<Long>()); for (CourseMining courseMining : ci) { criteria = session.createCriteria(ILogMining.class, "log"); criteria.add(Restrictions.eq("log.course.id", courseMining.getId())); if(userMap.size() > 0) { criteria.add(Restrictions.in("log.user.id", userMap.values())); } //TODO Redefine projection for max id as detachable criteria (Subselect) //DetachedCriteria sub = DetachedCriteria.forClass(ILogMining.class); // sub.setProjection(Projections.max("id")); // //criteria.add(Restrictions.eq("id",sub)); ArrayList<ILogMining> logs = (ArrayList<ILogMining>) criteria.list(); Collections.sort(logs); Long lastTime = 0L; Long firstTime = 0L; if (logs.size() > 0) { lastTime = logs.get(0).getTimestamp(); firstTime = logs.get(logs.size() - 1).getTimestamp(); } final CourseObject co = new CourseObject(courseMining.getId(), courseMining.getShortname(), courseMining.getTitle(), userMap.size(), lastTime, firstTime, getCourseHash(courseMining.getId()), StudentHelper.getGenderSupport(courseMining.getId())); results.add(co); } if (results.isEmpty()) { logger.debug("Result List is empty"); } else for(CourseObject co : results) logger.debug("Result Course: "+ co.getDescription()); session.close(); return new ResultListCourseObject(results); }
public ResultListCourseObject getCoursesDetails(@QueryParam(MetaParam.COURSE_IDS) final List<Long> courses) { IDBHandler dbHandler = ServerConfiguration.getInstance().getMiningDbHandler(); final ArrayList<CourseObject> results = new ArrayList<CourseObject>(); if (courses == null || courses.isEmpty()) { logger.debug("Courses List is empty"); return new ResultListCourseObject(results); } else for(Long id : courses) logger.debug("Looking for Course: "+ id); // Set up db-connection final Session session = dbHandler.getMiningSession(); Criteria criteria = session.createCriteria(CourseMining.class, "course"); criteria.add(Restrictions.in("course.id", courses)); @SuppressWarnings("unchecked") final ArrayList<CourseMining> ci = (ArrayList<CourseMining>) criteria.list(); Map<Long, Long> userMap = StudentHelper.getCourseStudentsAliasKeys(courses, new ArrayList<Long>()); for (CourseMining courseMining : ci) { criteria = session.createCriteria(ILogMining.class, "log"); criteria.add(Restrictions.eq("log.course.id", courseMining.getId())); if(userMap.size() > 0) { criteria.add(Restrictions.in("log.user.id", userMap.values())); } //TODO Redefine projection for max id as detachable criteria (Subselect) //DetachedCriteria sub = DetachedCriteria.forClass(ILogMining.class); // sub.setProjection(Projections.max("id")); // //criteria.add(Restrictions.eq("id",sub)); ArrayList<ILogMining> logs = (ArrayList<ILogMining>) criteria.list(); Collections.sort(logs); Long lastTime = 0L; Long firstTime = 0L; if (logs.size() > 0) { lastTime = logs.get(0).getTimestamp(); firstTime = logs.get(logs.size() - 1).getTimestamp(); } final CourseObject co = new CourseObject(courseMining.getId(), courseMining.getShortname(), courseMining.getTitle(), userMap.size(), lastTime, firstTime, getCourseHash(courseMining.getId()), StudentHelper.getGenderSupport(courseMining.getId())); results.add(co); } if (results.isEmpty()) { logger.debug("Result List is empty"); } else for(CourseObject co : results) logger.debug("Result Course: "+ co.getDescription()); session.close(); return new ResultListCourseObject(results); }
diff --git a/src/aiml/classifier/Classifier.java b/src/aiml/classifier/Classifier.java index 3e135c6..257f748 100644 --- a/src/aiml/classifier/Classifier.java +++ b/src/aiml/classifier/Classifier.java @@ -1,113 +1,113 @@ /* jaiml - java AIML library Copyright (C) 2004-2005 Kim Sullivan 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. 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 aiml.classifier; import aiml.classifier.node.EndOfStringNode; import aiml.classifier.node.PatternNodeFactory; import aiml.classifier.node.StringNode; import aiml.classifier.node.WildcardNode; /** * <p>This class encapsulates all AIML pattern matching functionality.</p> * * * @author Kim Sullivan * @version 1.0 */ public class Classifier { /** The root context tree */ private static ContextNode tree; /** The number of paths in the tree */ private static int count = 0; /** * Creates an instance of the aiml matcher. Since this class is meant to be * static, it's hidden. More robust techniques for making it a singleton might * be used in the future. */ private Classifier() { } /** * Match the current context state to the paths in the tree. * @return a complete match state if succesfull; <code>null</code> otherwise */ public static MatchState match() { MatchState m = new MatchState(); if (tree != null && tree.match(m)) { return m; } else { return null; } } /** * Add a path to the matching tree. * @param path the path to be added * @param o the object to be stored * @throws DuplicatePathException */ public static void add(Path path, Object o) throws DuplicatePathException { assert (PatternNodeFactory.getCount()>0) : "You have to register node types"; if (tree == null) { if (path.getLength() != 0) { - tree = new PatternContextNode(path.iterator(), path); + tree = new PatternContextNode(path.iterator(), o); } else { tree = new LeafContextNode(o); } } else { - tree = tree.add(path.iterator(), path); + tree = tree.add(path.iterator(), o); } count++; //this is OK, because if the path isn't added, an exception gets thrown before we reach this } /** * Returns the number of loaded patterns. * @return the number of loaded patterns. */ public static int getCount() { return count; } /** * <p>Resets the whole matching tree. This is usefull when the order of contexts * needs to be changed, because this invalidates the whole data structure.</p> * <p>This must follow after resetting the ContextInfo structure, but can be used * as a stand-alone method to remove all patterns from the matching tree.</p> * @see aiml.context.ContextInfo#reset() */ public static void reset() { tree = null; count = 0; } /** * <p>This is a convenience method to register the default (or hopefully most * optimal) node handler classes. When using this method, you don't have to think * about all the different aiml.classifier.node.* implementations.</p> * @see aiml.classifier.node */ public static void registerDefaultNodeHandlers() { StringNode.register(); EndOfStringNode.register(); WildcardNode.register(); } }
false
true
public static void add(Path path, Object o) throws DuplicatePathException { assert (PatternNodeFactory.getCount()>0) : "You have to register node types"; if (tree == null) { if (path.getLength() != 0) { tree = new PatternContextNode(path.iterator(), path); } else { tree = new LeafContextNode(o); } } else { tree = tree.add(path.iterator(), path); } count++; //this is OK, because if the path isn't added, an exception gets thrown before we reach this }
public static void add(Path path, Object o) throws DuplicatePathException { assert (PatternNodeFactory.getCount()>0) : "You have to register node types"; if (tree == null) { if (path.getLength() != 0) { tree = new PatternContextNode(path.iterator(), o); } else { tree = new LeafContextNode(o); } } else { tree = tree.add(path.iterator(), o); } count++; //this is OK, because if the path isn't added, an exception gets thrown before we reach this }
diff --git a/src/Main.java b/src/Main.java index 303ba4d..09074d2 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,119 +1,119 @@ package apes; import javax.swing.JFrame; import javax.swing.undo.UndoManager; import apes.controllers.ConfigController; import apes.controllers.HelpController; import apes.controllers.InternalFormatController; import apes.controllers.LanguageController; import apes.controllers.PlayerController; import apes.controllers.PluginController; import apes.controllers.TabsController; import apes.controllers.TagsController; import apes.exceptions.UnidentifiedLanguageException; import apes.lib.ApesFile; import apes.lib.Config; import apes.lib.Language; import apes.lib.PlayerHandler; import apes.lib.PluginHandler; import apes.views.ApesError; import apes.views.ApplicationView; /** * This is where it all starts. This creates a basic GUI with a layout * and on it a few components are placed. * * @author Johan Andersson ([email protected]) */ public class Main extends JFrame { /** * Starts the program. * * @param args Files to loaded at startup. */ public Main( String[] args ) throws Exception { // Parse the configuration file and set default values. Config config = Config.getInstance(); config.parse(); // Initialize a player handler. PlayerHandler playerHandler = new PlayerHandler(); // Create the plugin handler - pluginHandler = new PluginHandler("build/apes/plugins"); + PluginHandler pluginHandler = new PluginHandler("build/apes/plugins"); // Set up controllers. ConfigController configController = new ConfigController(); HelpController helpController = new HelpController(); PlayerController playerController = new PlayerController( playerHandler ); TagsController tagsController = new TagsController( playerHandler ); TabsController tabsController = new TabsController( playerHandler ); LanguageController languageController = new LanguageController(); PluginController pluginController = new PluginController(pluginHandler, playerHandler); // Fix language. Language language = Language.getInstance(); try { language.setLanguage( config.getOption( "language" ) ); language.load(); } catch ( Exception e ) { e.printStackTrace(); } // Open all files passed in as arguments. for( int i = 0; i < args.length; i++) { try { ApesFile apesFile = new ApesFile( args[i] ); tabsController.add( apesFile.getInternalFormat(), apesFile.getName() ); } catch( UnidentifiedLanguageException e ) { ApesError.unsupportedFormat(); } catch( Exception e ) { e.printStackTrace(); } } // Create the undo manager. UndoManager undoManager = new UndoManager(); undoManager.setLimit( config.getIntOption( "undo" ) ); // Controller for the internal format. InternalFormatController internalFormatController = new InternalFormatController( undoManager, tabsController, playerHandler ); // Create the application view. new ApplicationView( internalFormatController, tagsController, languageController, configController, pluginController, helpController, playerController, tabsController ); } public static void main( String[] args ) { try { new Main( args ); } catch( Exception e ) { ApesError.unknownErrorOccurred(); System.out.println(); e.printStackTrace(); } } }
true
true
public Main( String[] args ) throws Exception { // Parse the configuration file and set default values. Config config = Config.getInstance(); config.parse(); // Initialize a player handler. PlayerHandler playerHandler = new PlayerHandler(); // Create the plugin handler pluginHandler = new PluginHandler("build/apes/plugins"); // Set up controllers. ConfigController configController = new ConfigController(); HelpController helpController = new HelpController(); PlayerController playerController = new PlayerController( playerHandler ); TagsController tagsController = new TagsController( playerHandler ); TabsController tabsController = new TabsController( playerHandler ); LanguageController languageController = new LanguageController(); PluginController pluginController = new PluginController(pluginHandler, playerHandler); // Fix language. Language language = Language.getInstance(); try { language.setLanguage( config.getOption( "language" ) ); language.load(); } catch ( Exception e ) { e.printStackTrace(); } // Open all files passed in as arguments. for( int i = 0; i < args.length; i++) { try { ApesFile apesFile = new ApesFile( args[i] ); tabsController.add( apesFile.getInternalFormat(), apesFile.getName() ); } catch( UnidentifiedLanguageException e ) { ApesError.unsupportedFormat(); } catch( Exception e ) { e.printStackTrace(); } } // Create the undo manager. UndoManager undoManager = new UndoManager(); undoManager.setLimit( config.getIntOption( "undo" ) ); // Controller for the internal format. InternalFormatController internalFormatController = new InternalFormatController( undoManager, tabsController, playerHandler ); // Create the application view. new ApplicationView( internalFormatController, tagsController, languageController, configController, pluginController, helpController, playerController, tabsController ); }
public Main( String[] args ) throws Exception { // Parse the configuration file and set default values. Config config = Config.getInstance(); config.parse(); // Initialize a player handler. PlayerHandler playerHandler = new PlayerHandler(); // Create the plugin handler PluginHandler pluginHandler = new PluginHandler("build/apes/plugins"); // Set up controllers. ConfigController configController = new ConfigController(); HelpController helpController = new HelpController(); PlayerController playerController = new PlayerController( playerHandler ); TagsController tagsController = new TagsController( playerHandler ); TabsController tabsController = new TabsController( playerHandler ); LanguageController languageController = new LanguageController(); PluginController pluginController = new PluginController(pluginHandler, playerHandler); // Fix language. Language language = Language.getInstance(); try { language.setLanguage( config.getOption( "language" ) ); language.load(); } catch ( Exception e ) { e.printStackTrace(); } // Open all files passed in as arguments. for( int i = 0; i < args.length; i++) { try { ApesFile apesFile = new ApesFile( args[i] ); tabsController.add( apesFile.getInternalFormat(), apesFile.getName() ); } catch( UnidentifiedLanguageException e ) { ApesError.unsupportedFormat(); } catch( Exception e ) { e.printStackTrace(); } } // Create the undo manager. UndoManager undoManager = new UndoManager(); undoManager.setLimit( config.getIntOption( "undo" ) ); // Controller for the internal format. InternalFormatController internalFormatController = new InternalFormatController( undoManager, tabsController, playerHandler ); // Create the application view. new ApplicationView( internalFormatController, tagsController, languageController, configController, pluginController, helpController, playerController, tabsController ); }
diff --git a/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/draw2d/TestLifeCycleWidget.java b/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/draw2d/TestLifeCycleWidget.java index a974661885..41dce0a36e 100644 --- a/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/draw2d/TestLifeCycleWidget.java +++ b/tests/org.bonitasoft.studio.tests/src/org/bonitasoft/studio/tests/draw2d/TestLifeCycleWidget.java @@ -1,163 +1,163 @@ /** * Copyright (C) 2011-2012 BonitaSoft S.A. * BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble * * 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.0 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bonitasoft.studio.tests.draw2d; import org.bonitasoft.engine.bpm.model.ConnectorEvent; import org.bonitasoft.studio.common.widgets.EventCircle; import org.bonitasoft.studio.common.widgets.LifeCycleWidget; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swtbot.eclipse.finder.SWTBotEclipseTestCase; import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; import org.eclipse.swtbot.swt.finder.results.VoidResult; import org.eclipse.swtbot.swt.finder.waits.Conditions; /** * @author Aurelien Pupier * */ public class TestLifeCycleWidget extends SWTBotEclipseTestCase { LifeCycleWidget lcw; /*For Task*/ public void testTaskOnEnterSelectionEvent(){ final String eventType = ConnectorEvent.ON_ENTER.toString(); final ConnectorEvent eventTypeThatShouldBeselected = ConnectorEvent.ON_ENTER; final int taskLifeCycle = LifeCycleWidget.TASK_LIFE_CYCLE; testSelectionEvent(eventType, eventTypeThatShouldBeselected, taskLifeCycle); } public void testTaskDefaultSelectionEvent(){ final String eventType = null; final ConnectorEvent eventTypeThatShouldBeselected = ConnectorEvent.ON_FINISH; final int taskLifeCycle = LifeCycleWidget.TASK_LIFE_CYCLE; testSelectionEvent(eventType, eventTypeThatShouldBeselected, taskLifeCycle); } public void testTaskOnFinishSelectionEvent(){ final String eventType = ConnectorEvent.ON_FINISH.toString(); final ConnectorEvent eventTypeThatShouldBeselected = ConnectorEvent.ON_FINISH; final int taskLifeCycle = LifeCycleWidget.TASK_LIFE_CYCLE; testSelectionEvent(eventType, eventTypeThatShouldBeselected, taskLifeCycle); } /*For Process*/ public void testProcessOnFinishSelectionEvent(){ final String eventType = ConnectorEvent.ON_FINISH.toString(); final ConnectorEvent eventTypeThatShouldBeselected = ConnectorEvent.ON_FINISH; final int taskLifeCycle = LifeCycleWidget.PROCESS_LIFE_CYCLE; testSelectionEvent(eventType, eventTypeThatShouldBeselected, taskLifeCycle); } public void testProcessOnStartSelectionEvent(){ final String eventType = ConnectorEvent.ON_ENTER.toString(); final ConnectorEvent eventTypeThatShouldBeselected = ConnectorEvent.ON_ENTER; final int taskLifeCycle = LifeCycleWidget.PROCESS_LIFE_CYCLE; testSelectionEvent(eventType, eventTypeThatShouldBeselected, taskLifeCycle); } public void testProcessOnDefaultSelectionEvent(){ final String eventType = null; final ConnectorEvent eventTypeThatShouldBeselected = ConnectorEvent.ON_FINISH; final int taskLifeCycle = LifeCycleWidget.PROCESS_LIFE_CYCLE; testSelectionEvent(eventType, eventTypeThatShouldBeselected, taskLifeCycle); } /*For ACTIVITY*/ public void testActivityOnReadySelectionEvent(){ final String eventType = ConnectorEvent.ON_ENTER.toString(); final ConnectorEvent eventTypeThatShouldBeselected = ConnectorEvent.ON_ENTER; final int taskLifeCycle = LifeCycleWidget.TASK_LIFE_CYCLE; testSelectionEvent(eventType, eventTypeThatShouldBeselected, taskLifeCycle); } public void testActivityDefaultSelectionEvent(){ final String eventType = null; final ConnectorEvent eventTypeThatShouldBeselected = ConnectorEvent.ON_FINISH; final int taskLifeCycle = LifeCycleWidget.TASK_LIFE_CYCLE; testSelectionEvent(eventType, eventTypeThatShouldBeselected, taskLifeCycle); } public void testActivityOnFinishSelectionEvent(){ final String eventType = ConnectorEvent.ON_FINISH.toString(); final ConnectorEvent eventTypeThatShouldBeselected = ConnectorEvent.ON_FINISH; final int taskLifeCycle = LifeCycleWidget.TASK_LIFE_CYCLE; testSelectionEvent(eventType, eventTypeThatShouldBeselected, taskLifeCycle); } Dialog dialog; private void testSelectionEvent(final String eventType, final ConnectorEvent eventTypeThatShouldBeselected, final int taskLifeCycle) { UIThreadRunnable.syncExec(new VoidResult() { public void run() { Dialog dialog = new Dialog(Display.getDefault().getActiveShell()){ @Override protected Control createDialogArea(Composite parent) { Control superParent = super.createDialogArea(parent); lcw = new LifeCycleWidget(parent, eventType, null); return superParent; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("Test Life cycle widget: "+eventType+eventTypeThatShouldBeselected+taskLifeCycle); } }; dialog.setBlockOnOpen(false); dialog.open(); bot.waitUntil(Conditions.shellIsActive("Test Life cycle widget: "+eventType+eventTypeThatShouldBeselected+taskLifeCycle),10000); bot.button(IDialogConstants.CANCEL_LABEL).click(); } }); final String eventTypeTheoric = eventTypeThatShouldBeselected.toString(); for(EventCircle eventCircle : lcw.getEventFigures()){ final String event = eventCircle.getEvent(); if(event.equals(eventTypeTheoric)){ assertEquals("The event circle"+event+" should be selected", eventCircle.getLocalForegroundColor().getRed(),73); } else { assertEquals("The event circle"+event+" should not be selected", eventCircle.getLocalForegroundColor().getRed(),235); } } - bot.waitUntil(Conditions.shellIsActive("BonitaBPM")); + bot.waitUntil(Conditions.shellIsActive("Bonita BPM")); } }
true
true
private void testSelectionEvent(final String eventType, final ConnectorEvent eventTypeThatShouldBeselected, final int taskLifeCycle) { UIThreadRunnable.syncExec(new VoidResult() { public void run() { Dialog dialog = new Dialog(Display.getDefault().getActiveShell()){ @Override protected Control createDialogArea(Composite parent) { Control superParent = super.createDialogArea(parent); lcw = new LifeCycleWidget(parent, eventType, null); return superParent; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("Test Life cycle widget: "+eventType+eventTypeThatShouldBeselected+taskLifeCycle); } }; dialog.setBlockOnOpen(false); dialog.open(); bot.waitUntil(Conditions.shellIsActive("Test Life cycle widget: "+eventType+eventTypeThatShouldBeselected+taskLifeCycle),10000); bot.button(IDialogConstants.CANCEL_LABEL).click(); } }); final String eventTypeTheoric = eventTypeThatShouldBeselected.toString(); for(EventCircle eventCircle : lcw.getEventFigures()){ final String event = eventCircle.getEvent(); if(event.equals(eventTypeTheoric)){ assertEquals("The event circle"+event+" should be selected", eventCircle.getLocalForegroundColor().getRed(),73); } else { assertEquals("The event circle"+event+" should not be selected", eventCircle.getLocalForegroundColor().getRed(),235); } } bot.waitUntil(Conditions.shellIsActive("BonitaBPM")); }
private void testSelectionEvent(final String eventType, final ConnectorEvent eventTypeThatShouldBeselected, final int taskLifeCycle) { UIThreadRunnable.syncExec(new VoidResult() { public void run() { Dialog dialog = new Dialog(Display.getDefault().getActiveShell()){ @Override protected Control createDialogArea(Composite parent) { Control superParent = super.createDialogArea(parent); lcw = new LifeCycleWidget(parent, eventType, null); return superParent; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("Test Life cycle widget: "+eventType+eventTypeThatShouldBeselected+taskLifeCycle); } }; dialog.setBlockOnOpen(false); dialog.open(); bot.waitUntil(Conditions.shellIsActive("Test Life cycle widget: "+eventType+eventTypeThatShouldBeselected+taskLifeCycle),10000); bot.button(IDialogConstants.CANCEL_LABEL).click(); } }); final String eventTypeTheoric = eventTypeThatShouldBeselected.toString(); for(EventCircle eventCircle : lcw.getEventFigures()){ final String event = eventCircle.getEvent(); if(event.equals(eventTypeTheoric)){ assertEquals("The event circle"+event+" should be selected", eventCircle.getLocalForegroundColor().getRed(),73); } else { assertEquals("The event circle"+event+" should not be selected", eventCircle.getLocalForegroundColor().getRed(),235); } } bot.waitUntil(Conditions.shellIsActive("Bonita BPM")); }
diff --git a/de.hswt.hrm.contact.ui/src/de/hswt/hrm/contact/ui/part/util/ContactComperator.java b/de.hswt.hrm.contact.ui/src/de/hswt/hrm/contact/ui/part/util/ContactComperator.java index 53664c17..9a016c24 100644 --- a/de.hswt.hrm.contact.ui/src/de/hswt/hrm/contact/ui/part/util/ContactComperator.java +++ b/de.hswt.hrm.contact.ui/src/de/hswt/hrm/contact/ui/part/util/ContactComperator.java @@ -1,77 +1,75 @@ package de.hswt.hrm.contact.ui.part.util; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.swt.SWT; import de.hswt.hrm.contact.model.Contact; public class ContactComperator extends ViewerComparator { private int propertyIndex; private static final int DESCENDING = 1; private int direction = 0; public ContactComperator() { this.propertyIndex = 0; direction = 0; } public int getDirection() { return direction == 0 ? SWT.DOWN : SWT.UP; } public void setColumn(int column) { if (column == this.propertyIndex) { // Same column as last sort; toggle the direction direction = 1 - direction; } else { // New column; do an ascending sort this.propertyIndex = column; direction = DESCENDING; } } @Override public int compare(Viewer viewer, Object e1, Object e2) { Contact c1 = (Contact) e1; Contact c2 = (Contact) e2; int rc = 0; switch (propertyIndex) { case 0: rc = c1.getLastName().compareTo(c2.getLastName()); break; case 1: rc = c1.getFirstName().compareTo(c2.getFirstName()); break; case 2: rc = c1.getStreet().compareTo(c2.getStreet()); break; case 3: - int first = Integer.parseInt(c1.getStreetNo()); - int second = Integer.parseInt(c2.getStreetNo()); - rc = first - second; + rc = c1.getStreetNo().compareTo(c2.getStreetNo()); break; case 4: rc = c1.getPostCode().compareTo(c2.getPostCode()); break; case 5: rc = c1.getCity().compareTo(c2.getCity()); break; case 6: rc = c1.getMobile().get().compareTo(c2.getMobile().get()); break; default: rc = 0; } // If descending order, flip the direction if (direction == DESCENDING) { rc = -rc; } return rc; } }
true
true
public int compare(Viewer viewer, Object e1, Object e2) { Contact c1 = (Contact) e1; Contact c2 = (Contact) e2; int rc = 0; switch (propertyIndex) { case 0: rc = c1.getLastName().compareTo(c2.getLastName()); break; case 1: rc = c1.getFirstName().compareTo(c2.getFirstName()); break; case 2: rc = c1.getStreet().compareTo(c2.getStreet()); break; case 3: int first = Integer.parseInt(c1.getStreetNo()); int second = Integer.parseInt(c2.getStreetNo()); rc = first - second; break; case 4: rc = c1.getPostCode().compareTo(c2.getPostCode()); break; case 5: rc = c1.getCity().compareTo(c2.getCity()); break; case 6: rc = c1.getMobile().get().compareTo(c2.getMobile().get()); break; default: rc = 0; } // If descending order, flip the direction if (direction == DESCENDING) { rc = -rc; } return rc; }
public int compare(Viewer viewer, Object e1, Object e2) { Contact c1 = (Contact) e1; Contact c2 = (Contact) e2; int rc = 0; switch (propertyIndex) { case 0: rc = c1.getLastName().compareTo(c2.getLastName()); break; case 1: rc = c1.getFirstName().compareTo(c2.getFirstName()); break; case 2: rc = c1.getStreet().compareTo(c2.getStreet()); break; case 3: rc = c1.getStreetNo().compareTo(c2.getStreetNo()); break; case 4: rc = c1.getPostCode().compareTo(c2.getPostCode()); break; case 5: rc = c1.getCity().compareTo(c2.getCity()); break; case 6: rc = c1.getMobile().get().compareTo(c2.getMobile().get()); break; default: rc = 0; } // If descending order, flip the direction if (direction == DESCENDING) { rc = -rc; } return rc; }
diff --git a/src/org/antlr/works/parsetree/ParseTreePanel.java b/src/org/antlr/works/parsetree/ParseTreePanel.java index 3a5616a..91a8f73 100644 --- a/src/org/antlr/works/parsetree/ParseTreePanel.java +++ b/src/org/antlr/works/parsetree/ParseTreePanel.java @@ -1,284 +1,284 @@ package org.antlr.works.parsetree; import edu.usfca.xj.appkit.gview.GView; import edu.usfca.xj.appkit.gview.object.GElement; import edu.usfca.xj.appkit.utils.XJAlert; import org.antlr.works.utils.IconManager; import org.antlr.works.utils.TreeUtilities; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /* [The "BSD licence"] Copyright (c) 2005 Jean Bovet All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class ParseTreePanel extends JPanel { protected Component listViewComponent; protected Component graphViewComponent; protected JTree tree; protected DefaultTreeModel treeModel; protected ParseTreeGraphView parseTreeGraphView; protected JScrollPane graphScrollPane; protected ParseTreePanelDelegate delegate; public ParseTreePanel(DefaultTreeModel treeModel) { super(new BorderLayout()); this.treeModel = treeModel; tree = new JTree(treeModel); tree.setRootVisible(false); tree.setShowsRootHandles(true); DefaultTreeCellRenderer treeRenderer = new DefaultTreeCellRenderer(); treeRenderer.setClosedIcon(null); treeRenderer.setLeafIcon(null); treeRenderer.setOpenIcon(null); tree.setCellRenderer(treeRenderer); tree.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { int selRow = tree.getRowForLocation(e.getX(), e.getY()); TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); if(selRow != -1) { if(e.getClickCount() == 2) { displayNodeInfo(selPath.getLastPathComponent()); e.consume(); } } } }); listViewComponent = createListView(); graphViewComponent = createGraphView(); add(graphViewComponent, BorderLayout.CENTER); } public void setDelegate(ParseTreePanelDelegate delegate) { this.delegate = delegate; } public Component createListView() { JPanel panel = new JPanel(new BorderLayout()); JScrollPane scrollPane = new JScrollPane(tree); scrollPane.setWheelScrollingEnabled(true); Box box = Box.createHorizontalBox(); box.add(createExpandAllButton()); box.add(createCollapseAllButton()); box.add(Box.createHorizontalGlue()); box.add(createDisplayAsGraphButton()); panel.add(scrollPane, BorderLayout.CENTER); panel.add(box, BorderLayout.SOUTH); return panel; } public JButton createDisplayAsGraphButton() { JButton button = new JButton(IconManager.shared().getIconGraph()); button.setToolTipText("Display as Graph"); button.setFocusable(false); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { toggleGraph(); } }); return button; } public JButton createExpandAllButton() { JButton button = new JButton(IconManager.shared().getIconExpandAll()); button.setToolTipText("Expand All"); button.setFocusable(false); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { TreeUtilities.expandAll(tree); } }); return button; } public JButton createCollapseAllButton() { JButton button = new JButton(IconManager.shared().getIconCollapseAll()); button.setToolTipText("Collapse All"); button.setFocusable(false); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { TreeUtilities.collapseAll(tree); } }); return button; } public Component createGraphView() { JPanel panel = new JPanel(new BorderLayout()); parseTreeGraphView = new ParseTreeGraphView(this); parseTreeGraphView.setAutoAdjustSize(true); parseTreeGraphView.setBackground(Color.white); parseTreeGraphView.setDrawBorder(false); parseTreeGraphView.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { - GElement elem = parseTreeGraphView.getElementAtPoint(e.getPoint()); + GElement elem = parseTreeGraphView.getElementAtMousePosition(e); if(elem == null || !(elem instanceof ParseTreeGraphView.GElementNode)) return; TreeNode node = parseTreeGraphView.getTreeNode((ParseTreeGraphView.GElementNode)elem); if(node == null) return; delegate.parseTreeDidSelectTreeNode(node); selectNode(node); } }); graphScrollPane = new JScrollPane(parseTreeGraphView); graphScrollPane.setWheelScrollingEnabled(true); Box box = Box.createHorizontalBox(); box.add(new JLabel("Zoom")); box.add(createZoomSlider()); box.add(Box.createHorizontalGlue()); box.add(createDisplayAsListButton()); panel.add(graphScrollPane, BorderLayout.CENTER); panel.add(box, BorderLayout.SOUTH); return panel; } public JButton createDisplayAsListButton() { JButton button = new JButton(IconManager.shared().getIconListTree()); button.setToolTipText("Display as List"); button.setFocusable(false); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { toggleGraph(); } }); return button; } public JSlider createZoomSlider() { JSlider slider = new JSlider(); slider.setFocusable(false); slider.setMinimum(1); slider.setMaximum(200); slider.setValue(100); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent event) { JSlider slider = (JSlider)event.getSource(); parseTreeGraphView.setZoom((float)slider.getValue()/100); parseTreeGraphView.repaint(); parseTreeGraphView.revalidate(); } }); return slider; } public void setRoot(TreeNode node) { treeModel.setRoot(node); parseTreeGraphView.setRoot(node); refresh(); } public Object getRoot() { return treeModel.getRoot(); } public GView getGraphView() { return parseTreeGraphView; } public void refresh() { treeModel.reload(); TreeUtilities.expandAll(tree); parseTreeGraphView.refresh(); } public void toggleGraph() { if(getComponent(0) == listViewComponent) { remove(listViewComponent); add(graphViewComponent, BorderLayout.CENTER); } else { remove(graphViewComponent); add(listViewComponent, BorderLayout.CENTER); } repaint(); revalidate(); } public void selectNode(TreeNode node) { TreePath path = new TreePath(treeModel.getPathToRoot(node)); tree.scrollPathToVisible(path); tree.setSelectionPath(path); parseTreeGraphView.highlightNode(node); } public void scrollNodeToVisible(TreeNode node) { tree.scrollPathToVisible(new TreePath(treeModel.getPathToRoot(node))); parseTreeGraphView.scrollNodeToVisible(node); } public void displayNodeInfo(Object node) { ParseTreeNode n = (ParseTreeNode)node; XJAlert.display(this, "Node info", n.getInfoString()); } public JPopupMenu getContextualMenu() { if(delegate != null) return delegate.getContextualMenu(); else return null; } }
true
true
public Component createGraphView() { JPanel panel = new JPanel(new BorderLayout()); parseTreeGraphView = new ParseTreeGraphView(this); parseTreeGraphView.setAutoAdjustSize(true); parseTreeGraphView.setBackground(Color.white); parseTreeGraphView.setDrawBorder(false); parseTreeGraphView.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { GElement elem = parseTreeGraphView.getElementAtPoint(e.getPoint()); if(elem == null || !(elem instanceof ParseTreeGraphView.GElementNode)) return; TreeNode node = parseTreeGraphView.getTreeNode((ParseTreeGraphView.GElementNode)elem); if(node == null) return; delegate.parseTreeDidSelectTreeNode(node); selectNode(node); } }); graphScrollPane = new JScrollPane(parseTreeGraphView); graphScrollPane.setWheelScrollingEnabled(true); Box box = Box.createHorizontalBox(); box.add(new JLabel("Zoom")); box.add(createZoomSlider()); box.add(Box.createHorizontalGlue()); box.add(createDisplayAsListButton()); panel.add(graphScrollPane, BorderLayout.CENTER); panel.add(box, BorderLayout.SOUTH); return panel; }
public Component createGraphView() { JPanel panel = new JPanel(new BorderLayout()); parseTreeGraphView = new ParseTreeGraphView(this); parseTreeGraphView.setAutoAdjustSize(true); parseTreeGraphView.setBackground(Color.white); parseTreeGraphView.setDrawBorder(false); parseTreeGraphView.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { GElement elem = parseTreeGraphView.getElementAtMousePosition(e); if(elem == null || !(elem instanceof ParseTreeGraphView.GElementNode)) return; TreeNode node = parseTreeGraphView.getTreeNode((ParseTreeGraphView.GElementNode)elem); if(node == null) return; delegate.parseTreeDidSelectTreeNode(node); selectNode(node); } }); graphScrollPane = new JScrollPane(parseTreeGraphView); graphScrollPane.setWheelScrollingEnabled(true); Box box = Box.createHorizontalBox(); box.add(new JLabel("Zoom")); box.add(createZoomSlider()); box.add(Box.createHorizontalGlue()); box.add(createDisplayAsListButton()); panel.add(graphScrollPane, BorderLayout.CENTER); panel.add(box, BorderLayout.SOUTH); return panel; }
diff --git a/xjc/src/com/sun/tools/xjc/reader/xmlschema/bindinfo/BIProperty.java b/xjc/src/com/sun/tools/xjc/reader/xmlschema/bindinfo/BIProperty.java index 7cf00f22..054e52de 100644 --- a/xjc/src/com/sun/tools/xjc/reader/xmlschema/bindinfo/BIProperty.java +++ b/xjc/src/com/sun/tools/xjc/reader/xmlschema/bindinfo/BIProperty.java @@ -1,662 +1,662 @@ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sun.tools.xjc.reader.xmlschema.bindinfo; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.namespace.QName; import com.sun.codemodel.JType; import com.sun.tools.xjc.ErrorReceiver; import com.sun.tools.xjc.generator.bean.field.FieldRenderer; import com.sun.tools.xjc.generator.bean.field.IsSetFieldRenderer; import com.sun.tools.xjc.model.CAttributePropertyInfo; import com.sun.tools.xjc.model.CCustomizations; import com.sun.tools.xjc.model.CElementPropertyInfo; import com.sun.tools.xjc.model.CPropertyInfo; import com.sun.tools.xjc.model.CReferencePropertyInfo; import com.sun.tools.xjc.model.CValuePropertyInfo; import com.sun.tools.xjc.model.TypeUse; import com.sun.tools.xjc.reader.Const; import com.sun.tools.xjc.reader.RawTypeSet; import com.sun.tools.xjc.reader.Ring; import com.sun.tools.xjc.reader.TypeUtil; import com.sun.tools.xjc.reader.xmlschema.BGMBuilder; import com.sun.xml.bind.v2.NameConverter; import com.sun.xml.xsom.XSAnnotation; import com.sun.xml.xsom.XSAttGroupDecl; import com.sun.xml.xsom.XSAttributeDecl; import com.sun.xml.xsom.XSAttributeUse; import com.sun.xml.xsom.XSComplexType; import com.sun.xml.xsom.XSComponent; import com.sun.xml.xsom.XSContentType; import com.sun.xml.xsom.XSElementDecl; import com.sun.xml.xsom.XSFacet; import com.sun.xml.xsom.XSIdentityConstraint; import com.sun.xml.xsom.XSModelGroup; import com.sun.xml.xsom.XSModelGroupDecl; import com.sun.xml.xsom.XSNotation; import com.sun.xml.xsom.XSParticle; import com.sun.xml.xsom.XSSchema; import com.sun.xml.xsom.XSSimpleType; import com.sun.xml.xsom.XSWildcard; import com.sun.xml.xsom.XSXPath; import com.sun.xml.xsom.util.XSFinder; import com.sun.xml.xsom.visitor.XSFunction; import org.xml.sax.Locator; /** * Property customization. * * This customization turns an arbitrary schema component * into a Java property (some restrictions apply.) * * <p> * All the getter methods (such as <code>getBaseType</code> or * <code>getBindStyle</code>) honors the delegation chain of * property customization specified in the spec. Namely, * if two property customizations are attached to an attribute * use and an attribute decl, then anything unspecified in the * attribute use defaults to attribute decl. * * <p> * Property customizations are acknowledged * (1) when they are actually used, and * (2) when they are given at the component, which is mapped to a class. * (so-called "point of declaration" customization) * * @author * Kohsuke Kawaguchi ([email protected]) */ @XmlRootElement(name="property") public final class BIProperty extends AbstractDeclarationImpl { // can be null @XmlAttribute private String name = null; // can be null @XmlElement private String javadoc = null; // can be null @XmlElement private BaseTypeBean baseType = null; // TODO: report 'unsupported' error if this is true @XmlAttribute private boolean generateFailFastSetterMethod = false; public BIProperty(Locator loc, String _propName, String _javadoc, BaseTypeBean _baseType, CollectionTypeAttribute collectionType, Boolean isConst, OptionalPropertyMode optionalProperty, Boolean genElemProp) { super(loc); this.name = _propName; this.javadoc = _javadoc; this.baseType = _baseType; this.collectionType = collectionType; this.isConstantProperty = isConst; this.optionalProperty = optionalProperty; this.generateElementProperty = genElemProp; } protected BIProperty() {} public void setParent( BindInfo parent ) { super.setParent(parent); if(baseType!=null && baseType.conv!=null) baseType.conv.setParent(parent); } /** * Returns the customized property name. * * This method honors the "enableJavaNamingConvention" customization * and formats the property name accordingly if necessary. * * Thus the caller should <em>NOT</em> apply the XML-to-Java name * conversion algorithm to the value returned from this method. * * @param forConstant * If the property name is intended for a constant property name, * set to true. This will change the result * * @return * This method can return null if the customization doesn't * specify the name. */ public String getPropertyName( boolean forConstant ) { if(name!=null) { BIGlobalBinding gb = getBuilder().getGlobalBinding(); if( gb.isJavaNamingConventionEnabled() && !forConstant ) // apply XML->Java conversion return gb.nameConverter.toPropertyName(name); else return name; // ... or don't change the value } BIProperty next = getDefault(); if(next!=null) return next.getPropertyName(forConstant); else return null; } /** * Gets the associated javadoc. * * @return * null if none is specfieid. */ public String getJavadoc() { return javadoc; } // can be null public JType getBaseType() { if(baseType!=null && baseType.name!=null) { return TypeUtil.getType(getCodeModel(), baseType.name, Ring.get(ErrorReceiver.class),getLocation()); } BIProperty next = getDefault(); if(next!=null) return next.getBaseType(); else return null; } // can be null @XmlAttribute private CollectionTypeAttribute collectionType = null; /** * Gets the realization of this field. * @return Always return non-null. */ CollectionTypeAttribute getCollectionType() { if(collectionType!=null) return collectionType; return getDefault().getCollectionType(); } @XmlAttribute private OptionalPropertyMode optionalProperty = null; // virtual property for @generateIsSetMethod @XmlAttribute void setGenerateIsSetMethod(boolean b) { optionalProperty = b ? OptionalPropertyMode.ISSET : OptionalPropertyMode.WRAPPER; } public OptionalPropertyMode getOptionalPropertyMode() { if(optionalProperty!=null) return optionalProperty; return getDefault().getOptionalPropertyMode(); } // null if delegated @XmlAttribute private Boolean generateElementProperty = null; /** * If true, the property will automatically be a reference property. * (Talk about confusing names!) */ public boolean generateElementProperty() { if(generateElementProperty!=null) return generateElementProperty; BIProperty next = getDefault(); if(next!=null) return next.generateElementProperty(); // globalBinding always has true or false in this property, // so this can't happen throw new AssertionError(); } // true, false, or null (which means the value should be inherited.) @XmlAttribute(name="fixedAttributeAsConstantProperty") private Boolean isConstantProperty; /** * Gets the inherited value of the "fixedAttrToConstantProperty" customization. * * <p> * Note that returning true from this method doesn't necessarily mean * that a property needs to be mapped to a constant property. * It just means that it's mapped to a constant property * <b>if an attribute use carries a fixed value.</b> * * <p> * I don't like this semantics but that's what the spec implies. */ public boolean isConstantProperty() { if(isConstantProperty!=null) return isConstantProperty; BIProperty next = getDefault(); if(next!=null) return next.isConstantProperty(); // globalBinding always has true or false in this property, // so this can't happen throw new AssertionError(); } public CValuePropertyInfo createValueProperty(String defaultName,boolean forConstant, XSComponent source,TypeUse tu) { markAsAcknowledged(); constantPropertyErrorCheck(); String name = getPropertyName(forConstant); if(name==null) name = defaultName; return wrapUp(new CValuePropertyInfo(name, getCustomizations(source),source.getLocator(), tu ),source); } public CAttributePropertyInfo createAttributeProperty( XSAttributeUse use, TypeUse tu ) { boolean forConstant = getCustomization(use).isConstantProperty() && use.getFixedValue()!=null; String name = getPropertyName(forConstant); if(name==null) { NameConverter conv = getBuilder().getNameConverter(); if(forConstant) name = conv.toConstantName(use.getDecl().getName()); else name = conv.toPropertyName(use.getDecl().getName()); } QName n = new QName(use.getDecl().getTargetNamespace(),use.getDecl().getName()); markAsAcknowledged(); constantPropertyErrorCheck(); return wrapUp(new CAttributePropertyInfo(name,getCustomizations(use),use.getLocator(), n, tu, use.isRequired() ),use); } /** * * * @param defaultName * If the name is not customized, this name will be used * as the default. Note that the name conversion <b>MUST</b> * be applied before this method is called if necessary. * @param source * Source schema component from which a field is built. */ public CElementPropertyInfo createElementProperty(String defaultName, boolean forConstant, XSParticle source, RawTypeSet types) { if(!types.refs.isEmpty()) // if this property is empty, don't acknowleedge the customization // this allows pointless property customization to be reported as an error markAsAcknowledged(); constantPropertyErrorCheck(); String name = getPropertyName(forConstant); if(name==null) name = defaultName; CElementPropertyInfo prop = wrapUp( new CElementPropertyInfo( name, types.getCollectionMode(), types.id(), types.getExpectedMimeType(), getCustomizations(source), source.getLocator(), types.isRequired()), source); types.addTo(prop); return prop; } public CReferencePropertyInfo createReferenceProperty( String defaultName, boolean forConstant, XSComponent source, RawTypeSet types, boolean isNillable, boolean isMixed ) { if(!types.refs.isEmpty()) // if this property is empty, don't acknowleedge the customization // this allows pointless property customization to be reported as an error markAsAcknowledged(); constantPropertyErrorCheck(); String name = getPropertyName(forConstant); if(name==null) name = defaultName; CReferencePropertyInfo prop = wrapUp( new CReferencePropertyInfo( name, types.getCollectionMode().isRepeated()||isMixed, isMixed, getCustomizations(source), source.getLocator() ), source); types.addTo(prop); return prop; } public CPropertyInfo createElementOrReferenceProperty( String defaultName, boolean forConstant, XSParticle source, RawTypeSet types, boolean isNillable ) { if(!types.canBeTypeRefs || generateElementProperty()) { return createReferenceProperty(defaultName,forConstant,source,types,isNillable,false); } else { return createElementProperty(defaultName,forConstant,source,types); } } /** * Common finalization of {@link CPropertyInfo} for the create***Property methods. */ private <T extends CPropertyInfo> T wrapUp(T prop, XSComponent source) { prop.javadoc = concat(javadoc, getBuilder().getBindInfo(source).getDocumentation()); if(prop.javadoc==null) prop.javadoc=""; // decide the realization. FieldRenderer r; OptionalPropertyMode opm = getOptionalPropertyMode(); if(prop.isCollection()) { CollectionTypeAttribute ct = getCollectionType(); r = ct.get(getBuilder().model); } else { if(prop.isOptionalPrimitive()) { // the property type can be primitive type if we are to ignore absence switch(opm) { case PRIMITIVE: r = FieldRenderer.REQUIRED_UNBOXED; break; case WRAPPER: // force the wrapper type r = FieldRenderer.SINGLE; break; case ISSET: r = FieldRenderer.SINGLE_PRIMITIVE_ACCESS; break; default: throw new Error(); } } else { r = FieldRenderer.DEFAULT; } } if(opm==OptionalPropertyMode.ISSET) { // only isSet is allowed on a collection. these 3 modes aren't really symmetric. // if the property is a primitive type, we need an explicit unset because // we can't overload the meaning of set(null). // if it's a collection, we need to be able to unset it so that we can distinguish // null list and empty list. - r = new IsSetFieldRenderer( r, prop.isUnboxable()||prop.isCollection(), true ); + r = new IsSetFieldRenderer( r, prop.isOptionalPrimitive()||prop.isCollection(), true ); } prop.realization = r; JType bt = getBaseType(); if(bt!=null) prop.baseType = bt; return prop; } private CCustomizations getCustomizations( XSComponent src ) { return getBuilder().getBindInfo(src).toCustomizationList(); } private CCustomizations getCustomizations( XSComponent... src ) { CCustomizations c = null; for (XSComponent s : src) { CCustomizations r = getCustomizations(s); if(c==null) c = r; else c = CCustomizations.merge(c,r); } return c; } private CCustomizations getCustomizations( XSAttributeUse src ) { // customizations for an attribute use should include those defined in the local attribute. // this is so that the schema like: // // <xs:attribute name="foo" type="xs:int"> // <xs:annotation><xs:appinfo> // <hyperjaxb:... /> // // would be picked up if(src.getDecl().isLocal()) return getCustomizations(src,src.getDecl()); else return getCustomizations((XSComponent)src); } private CCustomizations getCustomizations( XSParticle src ) { // customizations for a particle should include those defined in the term unless it's global // this is so that the schema like: // // <xs:sequence> // <xs:element name="foo" type="xs:int"> // <xs:annotation><xs:appinfo> // <hyperjaxb:... /> // // would be picked up if(src.getTerm().isElementDecl()) { XSElementDecl xed = src.getTerm().asElementDecl(); if(xed.isGlobal()) return getCustomizations((XSComponent)src); } return getCustomizations(src,src.getTerm()); } public void markAsAcknowledged() { if( isAcknowledged() ) return; // mark the parent as well. super.markAsAcknowledged(); BIProperty def = getDefault(); if(def!=null) def.markAsAcknowledged(); } private void constantPropertyErrorCheck() { if( isConstantProperty!=null && getOwner()!=null ) { // run additional check on the isCOnstantProperty value. // this value is not allowed if the schema component doesn't have // a fixed value constraint. // // the setParent method associates a customization with the rest of // XSOM object graph, so this is the earliest possible moment where // we can test this. if( !hasFixedValue.find(getOwner()) ) { Ring.get(ErrorReceiver.class).error( getLocation(), Messages.format(ERR_ILLEGAL_FIXEDATTR) ); // set this value to null to avoid the same error to be reported more than once. isConstantProperty = null; } } } /** * Function object that returns true if a component has * a fixed value constraint. */ private final XSFinder hasFixedValue = new XSFinder() { public Boolean attributeDecl(XSAttributeDecl decl) { return decl.getFixedValue()!=null; } public Boolean attributeUse(XSAttributeUse use) { return use.getFixedValue()!=null; } public Boolean schema(XSSchema s) { // we allow globalBindings to have isConstantProperty==true, // so this method returns true to allow this. return true; } }; /** * Finds a BIProperty which this object should delegate to. * * @return * always return non-null for normal BIProperties. * If this object is contained in the BIGlobalBinding, then * this method returns null to indicate that there's no more default. */ protected BIProperty getDefault() { if(getOwner()==null) return null; BIProperty next = getDefault(getBuilder(),getOwner()); if(next==this) return null; // global. else return next; } private static BIProperty getDefault( BGMBuilder builder, XSComponent c ) { while(c!=null) { c = c.apply(defaultCustomizationFinder); if(c!=null) { BIProperty prop = builder.getBindInfo(c).get(BIProperty.class); if(prop!=null) return prop; } } // default to the global one return builder.getGlobalBinding().getDefaultProperty(); } /** * Finds a property customization that describes how the given * component should be mapped to a property (if it's mapped to * a property at all.) * * <p> * Consider an attribute use that does NOT carry a property * customization. This schema component is nonetheless considered * to carry a (sort of) implicit property customization, whose values * are defaulted. * * <p> * This method can be think of the method that returns this implied * property customization. * * <p> * Note that this doesn't mean the given component needs to be * mapped to a property. But if it does map to a property, it needs * to follow this customization. * * I think this semantics is next to non-sense but I couldn't think * of any other way to follow the spec. * * @param c * A customization effective on this component will be returned. * Can be null just to get the global customization. * @return * Always return non-null valid object. */ public static BIProperty getCustomization( XSComponent c ) { BGMBuilder builder = Ring.get(BGMBuilder.class); // look for a customization on this component if( c!=null ) { BIProperty prop = builder.getBindInfo(c).get(BIProperty.class); if(prop!=null) return prop; } // if no such thing exists, defeault. return getDefault(builder,c); } private final static XSFunction<XSComponent> defaultCustomizationFinder = new XSFunction<XSComponent>() { public XSComponent attributeUse(XSAttributeUse use) { return use.getDecl(); // inherit from the declaration } public XSComponent particle(XSParticle particle) { return particle.getTerm(); // inherit from the term } public XSComponent schema(XSSchema schema) { // no more delegation return null; } // delegates to the context schema object public XSComponent attributeDecl(XSAttributeDecl decl) { return decl.getOwnerSchema(); } public XSComponent wildcard(XSWildcard wc) { return wc.getOwnerSchema(); } public XSComponent modelGroupDecl(XSModelGroupDecl decl) { return decl.getOwnerSchema(); } public XSComponent modelGroup(XSModelGroup group) { return group.getOwnerSchema(); } public XSComponent elementDecl(XSElementDecl decl) { return decl.getOwnerSchema(); } public XSComponent complexType(XSComplexType type) { return type.getOwnerSchema(); } public XSComponent simpleType(XSSimpleType st) { return st.getOwnerSchema(); } // property customizations are not allowed on these components. public XSComponent attGroupDecl(XSAttGroupDecl decl) { throw new IllegalStateException(); } public XSComponent empty(XSContentType empty) { throw new IllegalStateException(); } public XSComponent annotation(XSAnnotation xsAnnotation) { throw new IllegalStateException(); } public XSComponent facet(XSFacet xsFacet) { throw new IllegalStateException(); } public XSComponent notation(XSNotation xsNotation) { throw new IllegalStateException(); } public XSComponent identityConstraint(XSIdentityConstraint x) { throw new IllegalStateException(); } public XSComponent xpath(XSXPath xsxPath) { throw new IllegalStateException(); } }; private static String concat( String s1, String s2 ) { if(s1==null) return s2; if(s2==null) return s1; return s1+"\n\n"+s2; } public QName getName() { return NAME; } /** Name of this declaration. */ public static final QName NAME = new QName( Const.JAXB_NSURI, "property" ); private static final String ERR_ILLEGAL_FIXEDATTR = "BIProperty.IllegalFixedAttributeAsConstantProperty"; public BIConversion.User getConv() { if(baseType!=null) return baseType.conv; else return null; } private static final class BaseTypeBean { /** * If there's a nested javaType customization, this field * will keep that customization. Otherwise null. * * This customization, if present, is used to customize * the simple type mapping at the point of reference. */ @XmlElementRef BIConversion.User conv; /** * Java type name. */ @XmlAttribute String name; } }
true
true
private <T extends CPropertyInfo> T wrapUp(T prop, XSComponent source) { prop.javadoc = concat(javadoc, getBuilder().getBindInfo(source).getDocumentation()); if(prop.javadoc==null) prop.javadoc=""; // decide the realization. FieldRenderer r; OptionalPropertyMode opm = getOptionalPropertyMode(); if(prop.isCollection()) { CollectionTypeAttribute ct = getCollectionType(); r = ct.get(getBuilder().model); } else { if(prop.isOptionalPrimitive()) { // the property type can be primitive type if we are to ignore absence switch(opm) { case PRIMITIVE: r = FieldRenderer.REQUIRED_UNBOXED; break; case WRAPPER: // force the wrapper type r = FieldRenderer.SINGLE; break; case ISSET: r = FieldRenderer.SINGLE_PRIMITIVE_ACCESS; break; default: throw new Error(); } } else { r = FieldRenderer.DEFAULT; } } if(opm==OptionalPropertyMode.ISSET) { // only isSet is allowed on a collection. these 3 modes aren't really symmetric. // if the property is a primitive type, we need an explicit unset because // we can't overload the meaning of set(null). // if it's a collection, we need to be able to unset it so that we can distinguish // null list and empty list. r = new IsSetFieldRenderer( r, prop.isUnboxable()||prop.isCollection(), true ); } prop.realization = r; JType bt = getBaseType(); if(bt!=null) prop.baseType = bt; return prop; }
private <T extends CPropertyInfo> T wrapUp(T prop, XSComponent source) { prop.javadoc = concat(javadoc, getBuilder().getBindInfo(source).getDocumentation()); if(prop.javadoc==null) prop.javadoc=""; // decide the realization. FieldRenderer r; OptionalPropertyMode opm = getOptionalPropertyMode(); if(prop.isCollection()) { CollectionTypeAttribute ct = getCollectionType(); r = ct.get(getBuilder().model); } else { if(prop.isOptionalPrimitive()) { // the property type can be primitive type if we are to ignore absence switch(opm) { case PRIMITIVE: r = FieldRenderer.REQUIRED_UNBOXED; break; case WRAPPER: // force the wrapper type r = FieldRenderer.SINGLE; break; case ISSET: r = FieldRenderer.SINGLE_PRIMITIVE_ACCESS; break; default: throw new Error(); } } else { r = FieldRenderer.DEFAULT; } } if(opm==OptionalPropertyMode.ISSET) { // only isSet is allowed on a collection. these 3 modes aren't really symmetric. // if the property is a primitive type, we need an explicit unset because // we can't overload the meaning of set(null). // if it's a collection, we need to be able to unset it so that we can distinguish // null list and empty list. r = new IsSetFieldRenderer( r, prop.isOptionalPrimitive()||prop.isCollection(), true ); } prop.realization = r; JType bt = getBaseType(); if(bt!=null) prop.baseType = bt; return prop; }
diff --git a/Evoting/src/com/rau/evoting/beans/OpenElection.java b/Evoting/src/com/rau/evoting/beans/OpenElection.java index c8ea8a5..bdaea8e 100644 --- a/Evoting/src/com/rau/evoting/beans/OpenElection.java +++ b/Evoting/src/com/rau/evoting/beans/OpenElection.java @@ -1,279 +1,279 @@ package com.rau.evoting.beans; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.mail.MessagingException; import com.rau.evoting.ElGamal.ElGamalHelper; import com.rau.evoting.data.ElectionDP; import com.rau.evoting.data.ElectionTrusteeDP; import com.rau.evoting.data.ElectionVoterDP; import com.rau.evoting.data.ElectonAnswerDP; import com.rau.evoting.data.SqlDataProvider; import com.rau.evoting.models.Answer; import com.rau.evoting.models.Election; import com.rau.evoting.models.Trustee; import com.rau.evoting.utils.MailService; import com.rau.evoting.utils.Util; import com.restfb.types.Group; public class OpenElection { private Election election; private ArrayList<Answer> answers; private ArrayList<Trustee> trustees; private String trusteeEmail; private String answer; private boolean showRemove; private boolean canOpen; private String openningMessage; private String selectedGroup; private String selectedVoteMode; private List<Group> groups; private String accessToken; public OpenElection() { // trustees = new ArrayList<Trustee>(); // selectedVoteMode = "all"; // answers = new ArrayList<Answer>(); accessToken = (String) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get("accessToken"); } public String navigateAnswers() { answers = ElectonAnswerDP.getElectionAnswers(election.getId()); answer = ""; return "Answers?faces-redirect=true"; } public String navigateTrustees() { return "Trustees?faces-redirect=true"; } public String createElection(String name, String description) { int userId = (int) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get("userId"); int elId = ElectionDP .insert(new Election(0, name, description), userId); election = new Election(elId, name, description); answers = new ArrayList<Answer>(); trustees = new ArrayList<Trustee>(); selectedVoteMode = "all"; selectedGroup = null; return "next"; } public void addAnswer(AjaxBehaviorEvent even) { if (!answer.equals("")) { answers.add(new Answer(answers.size() + 1, answer)); answer = ""; } return; } public void removeAnswer(AjaxBehaviorEvent even) { if (answers.size() > 0) { answers.remove(answers.size() - 1); } answer = ""; return; } public String cancelAnswers() { return "OpenElection?faces-redirect=true"; } public String addAnswers() { ElectonAnswerDP.insertAnswers(election.getId(), answers); return "OpenElection?faces-redirect=true"; } public String addTrustee() { if (trusteeEmail.equals("")) return ""; for (Trustee trustee : trustees) { if (trustee.getEmail().equals(trusteeEmail)) return ""; } String message = "Hello, you are chosen trustee for " + election.getName() + " election\n Please, generate your key: \n"; String token = Util.generateRandomToken(); int trId = ElectionTrusteeDP.insertTrustee(election.getId(), new Trustee(0, trusteeEmail, false, token)); String url = "http://localhost:8080/Evoting/TrusteeHome.xhtml?trId=" + trId + "&token=" + token; String encodedUrl = url; try { encodedUrl = URLEncoder.encode(url, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } message += url; // or encoded try { MailService.sendMessage(trusteeEmail, "Trustee for " + election.getName() + " election", message); } catch (MessagingException e) { e.printStackTrace(); ElectionTrusteeDP.deleteTrustee(trId); } trusteeEmail = ""; - return ""; + return "Trustees?faces-redirect=true"; } public String setElection(int id) { election = ElectionDP.getElection(id); answers = ElectonAnswerDP.getElectionAnswers(election.getId()); trustees = ElectionTrusteeDP.getElectionTrustees(election.getId()); selectedGroup = ElectionVoterDP.getElectionVoterByGroup(election .getId()); if (selectedGroup == null) { selectedVoteMode = "all"; } else { selectedVoteMode = ""; } return "OpenElection?faces-redirect=true"; } public String open() { String pbKey = ElGamalHelper.getElectionPublicKey(ElectionTrusteeDP .getElectionTrusteesPublicKeys(election.getId())); ElectionDP.openElection(election.getId(), pbKey); return "Elections?faces-redirect=true"; } public String fromVoters() { ElectionVoterDP.deleteElectionVoters(election.getId()); if (!selectedVoteMode.equals("all")) { ElectionVoterDP.setElectionVotersByGroup(election.getId(), selectedGroup); } return "OpenElection?faces-redirect=true"; } public Election getElection() { return election; } public void setElection(Election election) { this.election = election; } public ArrayList<Answer> getAnswers() { return answers; } public void setAnswers(ArrayList<Answer> answers) { this.answers = answers; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public ArrayList<Trustee> getTrustees() { trustees = ElectionTrusteeDP.getElectionTrustees(election.getId()); // fix return trustees; } public void setTrustees(ArrayList<Trustee> trustees) { this.trustees = trustees; } public String getTrusteeEmail() { return trusteeEmail; } public void setTrusteeEmail(String trusteeEmail) { this.trusteeEmail = trusteeEmail; } public String getSelectedGroup() { return selectedGroup; } public void setSelectedGroup(String selectedGroup) { this.selectedGroup = selectedGroup; } public String getSelectedVoteMode() { return selectedVoteMode; } public void setSelectedVoteMode(String selectedVoteMode) { this.selectedVoteMode = selectedVoteMode; } public List<Group> getGroups() { // FacebookClient fbClient = new DefaultFacebookClient(accessToken); // Connection<Group> gr = fbClient.fetchConnection("me/groups", // Group.class); // groups = gr.getData(); groups = (List<Group>) FacesContext.getCurrentInstance() .getExternalContext().getSessionMap().get("userGroups"); return groups; } public void setGroups(ArrayList<Group> groups) { this.groups = groups; } public boolean isShowRemove() { return answers.size() > 0; } public void setShowRemove(boolean showRemove) { this.showRemove = showRemove; } public boolean isCanOpen() { boolean allGenerated = true; for (Trustee tr : trustees) { allGenerated &= tr.isGenerated(); if (!allGenerated) break; } canOpen = allGenerated & (answers.size() > 0); return canOpen; } public void setCanOpen(boolean canOpen) { this.canOpen = canOpen; } public String getOpenningMessage() { boolean allGenerated = true; for (Trustee tr : trustees) { allGenerated &= tr.isGenerated(); if (!allGenerated) break; } if (answers.size() == 0) { openningMessage = "You have no answers "; if (!allGenerated) { openningMessage += "and not all trustees generate their keys."; } } else if (!allGenerated) { openningMessage = "Not all trustees generated their keys."; } return openningMessage; } public void setOpenningMessage(String openningMessage) { this.openningMessage = openningMessage; } }
true
true
public String addTrustee() { if (trusteeEmail.equals("")) return ""; for (Trustee trustee : trustees) { if (trustee.getEmail().equals(trusteeEmail)) return ""; } String message = "Hello, you are chosen trustee for " + election.getName() + " election\n Please, generate your key: \n"; String token = Util.generateRandomToken(); int trId = ElectionTrusteeDP.insertTrustee(election.getId(), new Trustee(0, trusteeEmail, false, token)); String url = "http://localhost:8080/Evoting/TrusteeHome.xhtml?trId=" + trId + "&token=" + token; String encodedUrl = url; try { encodedUrl = URLEncoder.encode(url, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } message += url; // or encoded try { MailService.sendMessage(trusteeEmail, "Trustee for " + election.getName() + " election", message); } catch (MessagingException e) { e.printStackTrace(); ElectionTrusteeDP.deleteTrustee(trId); } trusteeEmail = ""; return ""; }
public String addTrustee() { if (trusteeEmail.equals("")) return ""; for (Trustee trustee : trustees) { if (trustee.getEmail().equals(trusteeEmail)) return ""; } String message = "Hello, you are chosen trustee for " + election.getName() + " election\n Please, generate your key: \n"; String token = Util.generateRandomToken(); int trId = ElectionTrusteeDP.insertTrustee(election.getId(), new Trustee(0, trusteeEmail, false, token)); String url = "http://localhost:8080/Evoting/TrusteeHome.xhtml?trId=" + trId + "&token=" + token; String encodedUrl = url; try { encodedUrl = URLEncoder.encode(url, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } message += url; // or encoded try { MailService.sendMessage(trusteeEmail, "Trustee for " + election.getName() + " election", message); } catch (MessagingException e) { e.printStackTrace(); ElectionTrusteeDP.deleteTrustee(trId); } trusteeEmail = ""; return "Trustees?faces-redirect=true"; }
diff --git a/src/card/CardData.java b/src/card/CardData.java index e5d1c4c..a9fe22f 100644 --- a/src/card/CardData.java +++ b/src/card/CardData.java @@ -1,610 +1,610 @@ package card; import javafx.scene.image.Image; import javafx.scene.image.ImageView; /** * User: Erick * Date: 8/30/13 * Time: 3:09 AM */ public class CardData { public static int WIADEC = 1910; public static int MERC_DECK = 5244; public static int WIA_ART_DECK = 191010; /** * Card Numbers used to get cards from [] */ public static final int THE_FOOL = 0; public static final int THE_MAGUS = 1; public static final int THE_HIGH_PRIESTESS = 2; public static final int THE_EMPRESS = 3; public static final int THE_EMPEROR = 4; public static final int THE_HEIROPHANT = 5; public static final int THE_LOVER = 6; public static final int THE_CHARIOT = 7; public static final int STRENGTH = 8; public static final int THE_HERMIT = 9; public static final int WHEEL_OF_FORTUNE = 10; public static final int JUSTICE = 11; public static final int THE_HANGED_MAN = 12; public static final int DEATH = 13; public static final int TEMPERANCE = 14; public static final int THE_DEVIL = 15; public static final int THE_TOWER = 16; public static final int THE_STAR = 17; public static final int THE_MOON = 18; public static final int THE_SUN = 19; public static final int JUDGEMENT = 20; public static final int THE_WORLD = 21; public static final int ACE_OF_SWORDS = 22; public static final int TWO_OF_SWORDS = 23; public static final int THREE_OF_SWORDS = 24; public static final int FOUR_OF_SWORDS = 25; public static final int FIVE_OF_SWORDS = 26; public static final int SIX_OF_SWORDS = 27; public static final int SEVEN_OF_SWORDS = 28; public static final int EIGHT_OF_SWORDS = 29; public static final int NINE_OF_SWORDS = 30; public static final int TEN_OF_SWORDS = 31; public static final int PAGE_OF_SWORDS = 32; public static final int KNIGHT_OF_SWORDS = 33; public static final int KING_OF_SWORDS = 34; public static final int QUEEN_OF_SWORDS = 35; public static final int ACE_OF_WANDS = 36; public static final int TWO_OF_WANDS = 37; public static final int THREE_OF_WANDS = 38; public static final int FOUR_OF_WANDS = 39; public static final int FIVE_OF_WANDS = 40; public static final int SIX_OF_WANDS = 41; public static final int SEVEN_OF_WANDS = 42; public static final int EIGHT_OF_WANDS = 43; public static final int NINE_OF_WANDS = 44; public static final int TEN_OF_WANDS = 45; public static final int PAGE_OF_WANDS = 46; public static final int KNIGHT_OF_WANDS = 47; public static final int KING_OF_WANDS = 48; public static final int QUEEN_OF_WANDS = 49; public static final int ACE_OF_CUPS = 50; public static final int TWO_OF_CUPS = 51; public static final int THREE_OF_CUPS = 52; public static final int FOUR_OF_CUPS = 53; public static final int FIVE_OF_CUPS = 54; public static final int SIX_OF_CUPS = 55; public static final int SEVEN_OF_CUPS = 56; public static final int EIGHT_OF_CUPS = 57; public static final int NINE_OF_CUPS = 58; public static final int TEN_OF_CUPS = 59; public static final int PAGE_OF_CUPS = 60; public static final int KNIGHT_OF_CUPS = 61; public static final int KING_OF_CUPS = 62; public static final int QUEEN_OF_CUPS = 63; public static final int ACE_OF_PENTACLES = 64; public static final int TWO_OF_PENTACLES = 65; public static final int THREE_OF_PENTACLES = 66; public static final int FOUR_OF_PENTACLES = 67; public static final int FIVE_OF_PENTACLES = 68; public static final int SIX_OF_PENTACLES = 69; public static final int SEVEN_OF_PENTACLES = 70; public static final int EIGHT_OF_PENTACLES = 71; public static final int NINE_OF_PENTACLES = 72; public static final int TEN_OF_PENTACLES = 73; public static final int PAGE_OF_PENTACLES = 74; public static final int KNIGHT_OF_PENTACLES = 75; public static final int KING_OF_PENTACLES = 76; public static final int QUEEN_OF_PENTACLES = 77; public static final int BACK_GROUND = 78; /** * Card In Depth Meaning */ //Card Meanings static final String[] CARD_MEANINGS = new String[]{ "With light step, as if earth and its trammels had little power to restrain him, a young man in gorgeous vestments pauses at the brink of a precipice among the great heights of the world; he surveys the blue distance before him-its expanse of sky rather than the prospect below. His act of eager walking is still indicated, though he is stationary at the given moment; his dog is still bounding. The edge which opens on the depth has no terror; it is as if angels were waiting to uphold him, if it came about that he leaped from the height. His countenance is full of intelligence and expectant dream. He has a rose in one hand and in the other a costly wand, from which depends over his right shoulder a wallet curiously embroidered. He is a prince of the other world on his travels through this one-all amidst the morning glory, in the keen air. The sun, which shines behind him, knows whence he came, whither he is going, and how he will return by another path after many days. He is the spirit in search of experience. Many symbols of the Instituted Mysteries are summarized in this card, which reverses, under high warrants, all the confusions that have preceded it. In his Manual of Cartomancy, Grand Orient has a curious suggestion of the office of Mystic Fool, as apart of his process in higher divination; but it might call for more than ordinary gifts to put it into operation. We shall see how the card fares according to the common arts of fortune-telling, and it will be an example, to those who can discern, of the fact, otherwise so evident, that the Trumps Major had no place originally in the arts of psychic gambling, when cards are used as the counters and pretexts. Of the circumstances under which this art arose we know, however, very little. The conventional explanations say that the Fool signifies the flesh, the sensitive life, and by a peculiar satire its subsidiary name was at one time the alchemist, as depicting folly at the most insensate stage.", "A youthful figure in the robe of a magician, having the countenance of divine Apollo, with smile of confidence and shining eyes. Above his head is the mysterious sign of the Holy Spirit, the sign of life, like an endless cord, forming the figure 8 in a horizontal position {infinity symbol}. About his waist is a serpent-cincture, the serpent appearing to devour its own tail. This is familiar to most as a conventional symbol of eternity, but here it indicates more especially the eternity of attainment in the spirit. In the Magician's right hand is a wand raised towards heaven, while the left hand is pointing to the earth. This dual sign is known in very high grades of the Instituted Mysteries; it shews the descent of grace, virtue and light, drawn from things above and derived to things below. The suggestion throughout is therefore the possession and communication of the Powers and Gifts of the Spirit. On the table in front of the Magician are the symbols of the four Tarot suits, signifying the elements of natural life, which lie like counters before the adept, and he adapts them as he wills. Beneath are roses and lilies, the flos campi and lilium convallium, changed into garden flowers, to shew the culture of aspiration. This card signifies the divine motive in man, reflecting God, the will in the liberation of its union with that which is above. It is also the unity of individual being on all planes, and in a very high sense it is thought, in the fixation thereof. With further reference to what I have called the sign of life and its connexion with the number 8, it may be remembered that Christian Gnosticism speaks of rebirth in Christ as a change 'unto the Ogdoad.' The mystic number is termed Jerusalem above, the Land flowing with Milk and Honey, the Holy Spirit and the Land of the Lord. According to Martinism, 8 is the number of Christ.", "She has the lunar crescent at her feet, a horned diadem on her head, with a globe in the middle place, and a large solar cross on her breast. The scroll in her hands is inscribed with the word Tora, signifying the Greater Law, the Secret Law and the second sense of the Word. It is partly covered by her mantle, to shew that some things are implied and some spoken. She is seated between the white and black pillars--J. and B.--of the mystic Temple, and the veil of the Temple is behind her: it is embroidered with palms and pomegranates. The vestments are flowing and gauzy, and the mantle suggests light--a shimmering radiance. She has been called occult Science on the threshold of the Sanctuary of Isis, but she is really the Secret Church, the House which is of God and man. She represents also the Second Marriage of the Prince who is no longer of this world; she is the spiritual Bride and Mother, the daughter of the stars and the Higher Garden of Eden. She is, in fine, the Queen of the borrowed light, but this is the light of all. She is the Moon nourished by the milk of the Supernal Mother. In a manner, she is also the Supernal Mother herself--that is to say, she is the bright reflection. It is in this sense of reflection that her truest and highest name in bolism is Shekinah--the co-habiting glory. According to Kabalism, there is a Shekinah both above and below. In the superior world it is called Binah, the Supernal Understanding which reflects to the emanations that are beneath. In the lower world it is MaIkuth--that world being, for this purpose, understood as a blessed Kingdom that with which it is made blessed being the Indwelling Glory. Mystically speaking, the Shekinah is the Spiritual Bride of the just man, and when he reads the Law she gives the Divine meaning. There are some respects in which this card is the highest and holiest of the Greater Arcana.", "A stately figure, seated, having rich vestments and royal aspect, as of a daughter of heaven and earth. Her diadem is of twelve stars, gathered in a cluster. The symbol of Venus is on the shield which rests near her. A field of corn is ripening in front of her, and beyond there is a fall of water. The sceptre which she bears is surmounted by the globe of this world. She is the inferior Garden of Eden, the Earthly Paradise, all that is symbolized by the visible house of man. She is not Regina coeli, but she is still refugium peccatorum, the fruitful mother of thousands. There are also certain aspects in which she has been correctly described as desire and the wings thereof, as the woman clothed with the sun, as Gloria Mundi and the veil of the Sanctum Sanctorum; but she is not, I may add, the soul that has attained wings, unless all the symbolism is counted up another and unusual way. She is above all things universal fecundity and the outer sense of the Word. This is obvious, because there is no direct message which has been given to man like that which is borne by woman; but she does not herself carry its interpretation. In another order of ideas, the card of the Empress signifies the door or gate by which an entrance is obtained into this life, as into the Garden of Venus; and then the way which leads out therefrom, into that which is beyond, is the secret known to the High Priestess: it is communicated by her to the elect. Most old attributions of this card are completely wrong on the symbolism--as, for example, its identification with the Word, Divine Nature, the Triad, and so forth.", "He has a form of the Crux ansata for his sceptre and a globe in his left hand. He is a crowned monarch--commanding, stately, seated on a throne, the arms of which axe fronted by rams' heads. He is executive and realization, the power of this world, here clothed with the highest of its natural attributes. He is occasionally represented as seated on a cubic stone, which, however, confuses some of the issues. He is the virile power, to which the Empress responds, and in this sense is he who seeks to remove the Veil of Isis; yet she remains virgo intacta. It should be understood that this card and that of the Empress do not precisely represent the condition of married life, though this state is implied. On the surface, as I have indicated, they stand for mundane royalty, uplifted on the seats of the mighty; but above this there is the suggestion of another presence. They signify also--and the male figure especially--the higher kingship, occupying the intellectual throne. Hereof is the lordship of thought rather than of the animal world. Both personalities, after their own manner, are 'full of strange experience,' but theirs is not consciously the wisdom which draws from a higher world. The Emperor has been described as (a) will in its embodied form, but this is only one of its applications, and (b) as an expression of virtualities contained in the Absolute Being--but this is fantasy.", "He wears the triple crown and is seated between two pillars, but they are not those of the Temple which is guarded by the High Priestess. In his left hand he holds a sceptre terminating in the triple cross, and with his right hand he gives the well-known ecclesiastical sign which is called that of esotericism, distinguishing between the manifest and concealed part of doctrine. It is noticeable in this connexion that the High Priestess makes no sign. At his feet are the crossed keys, and two priestly ministers in albs kneel before him. He has been usually called the Pope, which is a particular application of the more general office that he symbolizes. He is the ruling power of external religion, as the High Priestess is the prevailing genius of the esoteric, withdrawn power. The proper meanings of this card have suffered woeful admixture from nearly all hands. Grand Orient says truly that the Hierophant is the power of the keys, exoteric orthodox doctrine, and the outer side of the life which leads to the doctrine; but he is certainly not the prince of occult doctrine, as another commentator has suggested. He is rather the summa totius theologiæ, when it has passed into the utmost rigidity of expression; but he symbolizes also all things that are righteous and sacred on the manifest side. As such, he is the channel of grace belonging to the world of institution as distinct from that of Nature, and he is the leader of salvation for the human race at large. He is the order and the head of the recognized hierarchy, which is the reflection of another and greater hierarchic order; but it may so happen that the pontiff forgets the significance of this his symbolic state and acts as if he contained within his proper measures all that his sign signifies or his symbol seeks to shew forth. He is not, as it has been thought, philosophy-except on the theological side; he is not inspiration; and he is not religion, although he is a mode of its expression.", "The sun shines in the zenith, and beneath is a great winged figure with arms extended, pouring down influences. In the foreground are two human figures, male and female, unveiled before each other, as if Adam and Eve when they first occupied the paradise of the earthly body. Behind the man is the Tree of Life, bearing twelve fruits, and the Tree of the Knowledge of Good and Evil is behind the woman; the serpent is twining round it. The figures suggest youth, virginity, innocence and love before it is contaminated by gross material desire. This is in all simplicity the card of human love, here exhibited as part of the way, the truth and the life. It replaces, by recourse to first principles, the old card of marriage, which I have described previously, and the later follies which depicted man between vice and virtue. In a very high sense, the card is a mystery of the Covenant and Sabbath. The suggestion in respect of the woman is that she signifies that attraction towards the sensitive life which carries within it the idea of the Fall of Man, but she is rather the working of a Secret Law of Providence than a willing and conscious temptress. It is through her imputed lapse that man shall arise ultimately, and only by her can he complete himself. The card is therefore in its way another intimation concerning the great mystery of womanhood. The old meanings fall to pieces of necessity with the old pictures, but even as interpretations of the latter, some of them were of the order of commonplace and others were false in symbolism.", "An erect and princely figure carrying a drawn sword and corresponding, broadly speaking. On the shoulders of the victorious hero are supposed to be the Urim and Thummim. He has led captivity captive; he is conquest on all planes--in the mind, in science, in progress, in certain trials of initiation. He has thus replied to the sphinx, and it is on this account that I have accepted the variation of Éliphas Lévi; two sphinxes thus draw his chariot. He is above all things triumph in the mind. It is to be understood for this reason (a) that the question of the sphinx is concerned with a Mystery of Nature and not of the world of Grace, to which the charioteer could offer no answer; (b) that the planes of his conquest are manifest or external and not within himself; (c) that the liberation which he effects may leave himself in the bondage of the logical understanding; (d) that the tests of initiation through which he has passed in triumph are to be understood physically or rationally; and (e) that if he came to the pillars of that Temple between which the High Priestess is seated, he could not open the scroll called Tora, nor if she questioned him could he answer. He is not hereditary royalty and he is not priesthood.", "A woman, over whose head there broods the same symbol of life which we have seen in the card of the Magician, is closing the jaws of a lion. The only point in which this design differs from the conventional presentations is that her beneficent fortitude has already subdued the lion, which is being led by a chain of flowers. For reasons which satisfy myself, this card has been interchanged with that of justice, which is usually numbered eight. As the variation carries nothing with it which will signify to the reader, there is no cause for explanation. Fortitude, in one of its most exalted aspects, is connected with the Divine Mystery of Union; the virtue, of course, operates in all planes, and hence draws on all in its symbolism. It connects also with innocentia inviolata, and with the strength which resides in contemplation. These higher meanings are, however, matters of inference, and I do not suggest that they are transparent on the surface of the card. They are intimated in a concealed manner by the chain of flowers, which signifies, among many other things, the sweet yoke and the light burden of Divine Law, when it has been taken into the heart of hearts. The card has nothing to do with self-confidence in the ordinary sense, though this has been suggested--but it concerns the confidence of those whose strength is God, who have found their refuge in Him. There is one aspect in which the lion signifies the passions, and she who is called Strength is the higher nature in its liberation. It has walked upon the asp and the basilisk and has trodden down the lion and the dragon.", "The variation from the conventional models in this card is only that the lamp is not enveloped partially in the mantle of its bearer, who blends the idea of the Ancient of Days with the Light of the World It is a star which shines in the lantern. I have said that this is a card of attainment, and to extend this conception the figure is seen holding up his beacon on an eminence. Therefore the Hermit is not, as Court de Gebelin explained, a wise man in search of truth and justice; nor is he, as a later explanation proposes, an especial example of experience. His beacon intimates that 'where I am, you also may be.' It is further a card which is understood quite incorrectly when it is connected with the idea of occult isolation, as the protection of personal magnetism against admixture. This is one of the frivolous renderings which we owe to Éliphas Lévi. It has been adopted by the French Order of Martinism and some of us have heard a great getCards of the Silent and Unknown Philosophy enveloped by his mantle from the knowledge of the profane. In true Martinism, the significance of the term Philosophe inconnu was of another order. It did not refer to the intended concealment of the Instituted Mysteries, much less of their substitutes, but--like the card itself--to the truth that the Divine Mysteries secure their own protection from those who are unprepared.", "In this symbol I have again followed the reconstruction of Éliphas Lévi, who has furnished several variants. It is legitimate--as I have intimated--to use Egyptian symbolism when this serves our purpose, provided that no theory of origin is implied therein. I have, however, presented Typhon in his serpent form. The symbolism is, of course, not exclusively Egyptian, as the four Living Creatures of Ezekiel occupy the angles of the card, and the wheel itself follows other indications of Lévi in respect of Ezekiel's vision, as illustrative of the particular Tarot Key. With the French occultist, and in the design itself, the symbolic picture stands for the perpetual motion of a fluidic universe and for the flux of human life. The Sphinx is the equilibrium therein. The transliteration of Taro as Rota is inscribed on the wheel, counterchanged with the letters of the Divine Name--to shew that Providence is imphed through all. But this is the Divine intention within, and the similar intention without is exemplified by the four Living Creatures. Sometimes the sphinx is represented couchant on a pedestal above, which defrauds the symbolism by stultifying the essential idea of stability amidst movement. Behind the general notion expressed in the symbol there lies the denial of chance and the fatality which is implied therein. It may be added that, from the days of Lévi onward, the occult explanations of this card are--even for occultism itself--of a singularly fatuous kind. It has been said to mean principle, fecundity, virile honour, ruling authority, etc. The findings of common fortune-telling are better than this on their own plane.", "As this card follows the traditional symbolism and carries above all its obvious meanings, there is little to say regarding it outside the few considerations collected in the first part, to which the reader is referred. It will be seen, however, that the figure is seated between pillars, like the High Priestess, and on this account it seems desirable to indicate that the moral principle which deals unto every man according to his works--while, of course, it is in strict analogy with higher things;--differs in its essence from the spiritual justice which is involved in the idea of election. The latter belongs to a mysterious order of Providence, in virtue of which it is possible for certain men to conceive the idea of dedication to the highest things. The operation of this is like the breathing of the Spirit where it wills, and we have no canon of criticism or ground of explanation concerning it. It is analogous to the possession of the fairy gifts and the high gifts and the gracious gifts of the poet: we have them or have not, and their presence is as much a mystery as their absence. The law of Justice is not however involved by either alternative. In conclusion, the pillars of Justice open into one world and the pillars of the High Priestess into another.", "The gallows from which he is suspended forms a Tau cross, while the figure--from the position of the legs--forms a fylfot cross. There is a nimbus about the head of the seeming martyr. It should be noted (1) that the tree of sacrifice is living wood, with leaves thereon; (2) that the face expresses deep entrancement, not suffering; (3) that the figure, as a whole, suggests life in suspension, but life and not death. It is a card of profound significance, but all the significance is veiled. One of his editors suggests that Éliphas Lévi did not know the meaning, which is unquestionable nor did the editor himself. It has been called falsely a card of martyrdom, a card a of prudence, a card of the Great Work, a card of duty; but we may exhaust all published interpretations and find only vanity. I will say very simply on my own part that it expresses the relation, in one of its aspects, between the Divine and the Universe. He who can understand that the story of his higher nature is imbedded in this symbolism will receive intimations concerning a great awakening that is possible, and will know that after the sacred Mystery of Death there is a glorious Mystery of Resurrection.", "The veil or mask of life is perpetuated in change, transformation and passage from lower to higher, and this is more fitly represented in the rectified Tarot by one of the apocalyptic visions than by the crude notion of the reaping skeleton. Behind it lies the whole world of ascent in the spirit. The mysterious horseman moves slowly, bearing a black banner emblazoned with the Mystic Rose, which signifies life. Between two pillars on the verge of the horizon there shines the sun of immortality. The horseman carries no visible weapon, but king and child and maiden fall before him, while a prelate with clasped hands awaits his end. There should be no need to point out that the suggestion of death which I have made in connection with the previous card is, of course, to be understood mystically, but this is not the case in the present instance. The natural transit of man to the next stage of his being either is or may be one form of his progress, but the exotic and almost unknown entrance, while still in this life, into the state of mystical death is a change in the form of consciousness and the passage into a state to which ordinary death is neither the path nor gate. The existing occult explanations of the 13th card are, on the whole, better than usual, rebirth, creation, destination, renewal, and the rest.", "A winged angel, with the sign of the sun upon his forehead and on his breast the square and triangle of the septenary. I speak of him in the masculine sense, but the figure is neither male nor female. It is held to be pouring the essences of life from chalice to chalice. It has one foot upon the earth and one upon waters, thus illustrating the nature of the essences. A direct path goes up to certain heights on the verge of the horizon, and above there is a great light, through which a crown is seen vaguely. Hereof is some part of the Secret of Eternal Life, as it is possible to man in his incarnation. All the conventional emblems are renounced herein. So also are the conventional meanings, which refer to changes in the seasons, perpetual movement of life and even the combination of ideas. It is, moreover, untrue to say that the figure symbolizes the genius of the sun, though it is the analogy of solar light, realized in the third part of our human triplicity. It is called Temperance fantastically, because, when the rule of it obtains in our consciousness, it tempers, combines and harmonises the psychic and material natures. Under that rule we know in our rational part something of whence we came and whither we are going.", "The design is an accommodation, mean or harmony, between several motives mentioned in the first part. The Horned Goat of Mendes, with wings like those of a bat, is standing on an altar. At the pit of the stomach there is the sign of Mercury. The right hand is upraised and extended, being the reverse of that benediction which is given by the Hierophant in the fifth card. In the left hand there is a great flaming torch, inverted towards the earth. A reversed pentagram is on the forehead. There is a ring in front of the altar, from which two chains are carried to the necks of two figures, male and female. These are analogous with those of the fifth card, as if Adam and Eve after the Fall. Hereof is the chain and fatality of the material life. The figures are tailed, to signify the animal nature, but there is human intelligence in the faces, and he who is exalted above them is not to be their master for ever. Even now, he is also a bondsman, sustained by the evil that is in him and blind to the liberty of service. With more than his usual derision for the arts which he pretended to respect and interpret as a master therein, Éliphas Lévi affirms that the Baphometic figure is occult science and magic. Another commentator says that in the Divine world it signifies predestination, but there is no correspondence in that world with the things which below are of the brute. What it does signify is the Dweller on the Threshold without the Mystical Garden when those are driven forth therefrom who have eaten the forbidden fruit.", "Occult explanations attached to this card are meagre and mostly disconcerting. It is idle to indicate that it depicts min in all its aspects, because it bears this evidence on the surface. It is said further that it contains the first allusion to a material building, but I do not conceive that the Tower is more or less material than the pillars which we have met with in three previous cases. I see nothing to warrant Papus in supposing that it is literally the fall of Adam, but there is more in favour of his alternative--that it signifies the materialization of the spiritual word. The bibliographer Christian imagines that it is the downfall of the mind, seeking to penetrate the mystery of God. I agree rather with Grand Orient that it is the ruin of the House of We, when evil has prevailed therein, and above all that it is the rending of a House of Doctrine. I understand that the reference is, however, to a House of Falsehood. It illustrates also in the most comprehensive way the old truth that 'except the Lord build the house, they labour in vain that build it.' There is a sense in which the catastrophe is a reflection from the previous card, but not on the side of the symbolism which I have tried to indicate therein. It is more correctly a question of analogy; one is concerned with the fall into the material and animal state, while the other signifies destruction on the intellectual side. The Tower has been spoken of as the chastisement of pride and the intellect overwhelmed in the attempt to penetrate the Mystery of God; but in neither case do these explanations account for the two persons who are the living sufferers. The one is the literal word made void and the other its false interpretation. In yet a deeper sense, it may signify also the end of a dispensation, but there is no possibility here for the consideration of this involved question.", "A great, radiant star of eight rays, surrounded by seven lesser stars--also of eight rays. The female figure in the foreground is entirely naked. Her left knee is on the land and her right foot upon the water. She pours Water of Life from two great ewers, irrigating sea and land. Behind her is rising ground and on the right a shrub or tree, whereon a bird alights. The figure expresses eternal youth and beauty. The star is l'étoile flamboyante, which appears in Masonic symbolism, but has been confused therein. That which the figure communicates to the living scene is the substance of the heavens and the elements. It has been said truly that the mottoes of this card are 'Waters of Life freely' and 'Gifts of the Spirit.' The summary of several tawdry explanations says that it is a card of hope. On other planes it has been certified as immortality and interior light. For the majority of prepared minds, the figure will appear as the type of Truth unveiled, glorious in undying beauty, pouring on the waters of the soul some part and measure of her priceless possession. But she is in reality the Great Mother in the Kabalistic Sephira Binah, which is supernal Understanding, who communicates to the Sephiroth that are below in the measure that they can receive her influx.", "The distinction between this card and some of the conventional types is that the moon is increasing on what is called the side of mercy, to the right of the observer. It has sixteen chief and sixteen secondary rays. The card represents life of the imagination apart from life of the spirit. The path between the towers is the issue into the unknown. The dog and wolf are the fears of the natural mind in the presence of that place of exit, when there is only reflected light to guide it. The last reference is a key to another form of symbolism. The intellectual light is a reflection and beyond it is the unknown mystery which it cannot shew forth. It illuminates our animal nature, types of which are represented below--the dog, the wolf and that which comes up out of the deeps, the nameless and hideous tendency which is lower than the savage beast. It strives to attain manifestation, symbolized by crawling from the abyss of water to the land, but as a rule it sinks back whence it came. The face of the mind directs a calm gaze upon the unrest below; the dew of thought falls; the message is: Peace, be still; and it may be that there shall come a calm upon the animal nature, while the abyss beneath shall cease from giving up a form.", "The naked child mounted on a white horse and displaying a red standard has been mentioned already as the better symbolism connected with this card. It is the destiny of the Supernatural East and the great and holy light which goes before the endless procession of humanity, coming out from the walled garden of the sensitive life and passing on the journey home. The card signifies, therefore, the transit from the manifest light of this world, represented by the glorious sun of earth, to the light of the world to come, which goes before aspiration and is typified by the heart of a child. But the last allusion is again the key to a different form or aspect of the symbolism. The sun is that of consciousness in the spirit - the direct as the antithesis of the reflected light. The characteristic type of humanity has become a little child therein--a child in the sense of simplicity and innocence in the sense of wisdom. In that simplicity, he bears the seal of Nature and of Art; in that innocence, he signifies the restored world. When the self-knowing spirit has dawned in the consciousness above the natural mind, that mind in its renewal leads forth the animal nature in a state of perfect conformity.", "I have said that this symbol is essentially invariable in all Tarot sets, or at least the variations do not alter its character. The great angel is here encompassed by clouds, but he blows his bannered trumpet, and the cross as usual is displayed on the banner. The dead are rising from their tombs--a woman on the right, a man on the left hand, and between them their child, whose back is turned. But in this card there are more than three who are restored, and it has been thought worth while to make this variation as illustrating the insufficiency of current explanations. It should be noted that all the figures are as one in the wonder, adoration and ecstacy expressed by their attitudes. It is the card which registers the accomplishment of the great work of transformation in answer to the summons of the Supernal--which summons is heard and answered from within. Herein is the intimation of a significance which cannot well be carried further in the present place. What is that within us which does sound a trumpet and all that is lower in our nature rises in response--almost in a moment, almost in the twinkling of an eye? Let the card continue to depict, for those who can see no further, the Last judgment and the resurrection in the natural body; but let those who have inward eyes look and discover therewith. They will understand that it has been called truly in the past a card of eternal life, and for this reason it may be compared with that which passes under the name of Temperance.", "As this final message of the Major Trumps is unchanged--and indeed unchangeable--in respect of its design, it has been partly described already regarding its deeper sense. It represents also the perfection and end of the Cosmos, the secret which is within it, the rapture of the universe when it understands itself in God. It is further the state of the soul in the consciousness of Divine Vision, reflected from the self-knowing spirit. But these meanings are without prejudice to that which I have said concerning it on the material side. It has more than one message on the macrocosmic side and is, for example, the state of the restored world when the law of manifestation shall have been carried to the highest degree of natural perfection. But it is perhaps more especially a story of the past, referring to that day when all was declared to be good, when the morning stars sang together and all the Sons of God shouted for joy. One of the worst explanations concerning it is that the figure symbolizes the Magus when he has reached the highest degree of initiation; another account says that it represents the absolute, which is ridiculous. The figure has been said to stand for Truth, which is, however, more properly allocated to the seventeenth card. Lastly, it has been called the Crown of the Magi.", "A hand issues from a cloud, grasping as word, the point of which is encircled by a crown. Divinatory Meanings: Triumph, the excessive degree in everything, conquest, triumph of force. It is a card of great force, in love as well as in hatred. The crown may carry a much higher significance than comes usually within the sphere of fortune-telling. Reversed: The same, but the results are disastrous; another account says--conception, childbirth, augmentation, multiplicity.", "A hoodwinked female figure balances two swords upon her shoulders. Divinatory Meanings: Conformity and the equipoise which it suggests, courage, friendship, concord in a state of arms; another reading gives tenderness, affection, intimacy. The suggestion of harmony and other favourable readings must be considered in a qualified manner, as Swords generally are not symbolical of beneficent forces in human affairs. Reversed: Imposture, falsehood, duplicity, disloyalty.", "Three swords piercing a heart; cloud and rain behind. Divinatory Meanings: Removal, absence, delay, division, rupture, dispersion, and all that the design signifies naturally, being too simple and obvious to call for specific enumeration. Reversed: Mental alienation, error, loss, distraction, disorder, confusion.", "The effigy of a knight in the attitude of prayer, at full length upon his tomb. Divinatory Meanings: Vigilance, retreat, solitude, hermit's repose, exile, tomb and coffin. It is these last that have suggested the design. Reversed: Wise administration, circumspection, economy, avarice, precaution, testament.", "A disdainful man looks after two retreating and dejected figures. Their swords lie upon the ground. He carries two others on his left shoulder, and a third sword is in his right hand, point to earth. He is the master in possession of the field. Divinatory Meanings: Degradation, destruction, revocation, infamy, dishonour, loss, with the variants and analogues of these. Reversed: The same; burial and obsequies.", "A ferryman carrying passengers in his punt to the further shore. The course is smooth, and seeing that the freight is light, it may be noted that the work is not beyond his strength. Divinatory Meanings: journey by water, route, way, envoy, commissionary, expedient. Reversed: Declaration, confession, publicity; one account says that it is a proposal of love.", "A man in the act of carrying away five swords rapidly; the two others of the card remain stuck in the ground. A camp is close at hand. Divinatory Meanings: Design, attempt, wish, hope, confidence; also quarrelling, a plan that may fail, annoyance. The design is uncertain in its import, because the significations are widely at variance with each other. Reversed: Good advice, counsel, instruction, slander, babbling.", "A woman, bound and hoodwinked, with the swords of the card about her. Yet it is rather a card of temporary durance than of irretrievable bondage. Divinatory Meanings: Bad news, violent chagrin, crisis, censure, power in trammels, conflict, calumny; also sickness. Reversed: Disquiet, difficulty, opposition, accident, treachery; what is unforeseen; fatality.", "One seated on her couch in lamentation, with the swords over her. She is as one who knows no sorrow which is like unto hers. It is a card of utter desolation. Divinatory Meanings: Death, failure, miscarriage, delay, deception, disappointment, despair. Reversed: Imprisonment, suspicion, doubt, reasonable fear, shame.", "A prostrate figure, pierced by all the swords belonging to the card. Divinatory Meanings: Whatsoever is intimated by the design; also pain, affliction, tears, sadness, desolation. It is not especially a card of violent death. Reversed: Advantage, profit, success, favour, but none of these are permanent; also power and authority.", "A lithe, active figure holds a sword upright in both hands, while in the act of swift walking. He is passing over rugged land, and about his way the clouds are collocated wildly. He is alert and lithe, looking this way and that, as if an expected enemy might appear at any moment. Divinatory Meanings: Authority, overseeing, secret service, vigilance, spying, examination, and the qualities thereto belonging. Reversed: More evil side of these qualities; what is unforeseen, unprepared state; sickness is also intimated.", "He is riding in full course, as if scattering his enemies. In the design he is really a prototypical hero of romantic chivalry. He might almost be Galahad, whose sword is swift and sure because he is clean of heart. Divinatory Meanings: Skill, bravery, capacity, defence, address, enmity, wrath, war, destruction, opposition, resistance, ruin. There is therefore a sense in which the card signifies death, but it carries this meaning only in its proximity to other cards of fatality. Reversed: Imprudence, incapacity, extravagance.", "He sits in judgment, holding the unsheathed sign of his suit. He recalls, of course, the conventional Symbol of justice in the Trumps Major, and he may represent this virtue, but he is rather the power of life and death, in virtue of his office. Divinatory Meanings: Whatsoever arises out of the idea of judgment and all its connexions-power, command, authority, militant intelligence, law, offices of the crown, and so forth. Reversed: Cruelty, perversity, barbarity, perfidy, evil intention.", "Her right hand raises the weapon vertically and the hilt rests on an arm of her royal chair the left hand is extended, the arm raised her countenance is severe but chastened; it suggests familiarity with sorrow. It does not represent mercy, and, her sword notwithstanding, she is scarcely a symbol of power. Divinatory Meanings: Widowhood, female sadness and embarrassment, absence, sterility, mourning, privation, separation. Reversed: Malice, bigotry, artifice, prudery, bale, deceit.", "A hand issuing from a cloud grasps a stout wand or club. Divinatory Meanings: Creation, invention, enterprise, the powers which result in these; principle, beginning, source; birth, family, origin, and in a sense the virility which is behind them; the starting point of enterprises; according to another account, money, fortune, inheritance. Reversed: Fall, decadence, ruin, perdition, to perish also a certain clouded joy.", "A tall man looks from a battlemented roof over sea and shore; he holds a globe in his right hand, while a staff in his left rests on the battlement; another is fixed in a ring. The Rose and Cross and Lily should be noticed on the left side. Divinatory Meanings: Between the alternative readings there is no marriage possible; on the one hand, riches, fortune, magnificence; on the other, physical suffering, disease, chagrin, sadness, mortification. The design gives one suggestion; here is a lord overlooking his dominion and alternately contemplating a globe; it looks like the malady, the mortification, the sadness of Alexander amidst the grandeur of this world's wealth. Reversed: Surprise, wonder, enchantment, emotion, trouble, fear.", "A calm, stately personage, with his back turned, looking from a cliff's edge at ships passing over the sea. Three staves are planted in the ground, and he leans slightly on one of them. Divinatory Meanings: He symbolizes established strength, enterprise, effort, trade, commerce, discovery; those are his ships, bearing his merchandise, which are sailing over the sea. The card also signifies able co-operation in business, as if the successful merchant prince were looking from his side towards yours with a view to help you. Reversed: The end of troubles, suspension or cessation of adversity, toil and disappointment.", "From the four great staves planted in the foreground there is a great garland suspended; two female figures uplift nosegays; at their side is a bridge over a moat, leading to an old manorial house. Divinatory Meanings: They are for once almost on the surface--country life, haven of refuge, a species of domestic harvest-home, repose, concord, harmony, prosperity, peace, and the perfected work of these. Reversed: The meaning remains unaltered; it is prosperity, increase, felicity, beauty, embellishment.", "A posse of youths, who are brandishing staves, as if in sport or strife. It is mimic warfare, and hereto correspond the Divinatory Meanings: Imitation, as, for example, sham fight, but also the strenuous competition and struggle of the search after riches and fortune. In this sense it connects with the battle of life. Hence some attributions say that it is a card of gold, gain, opulence. Reversed: Litigation, disputes, trickery, contradiction.", "A laurelled horseman bears one staff adorned with a laurel crown; footmen with staves are at his side. Divinatory Meanings: The card has been so designed that it can cover several significations; on the surface, it is a victor triumphing, but it is also great news, such as might be carried in state by the King's courier; it is expectation crowned with its own desire, the crown of hope, and so forth. Reversed: Apprehension, fear, as of a victorious enemy at the gate; treachery, disloyalty, as of gates being opened to the enemy; also indefinite delay.", "A young man on a craggy eminence brandishing a staff; six other staves are raised towards him from below. Divinatory Meanings: It is a card of valour, for, on the surface, six are attacking one, who has, however, the vantage position. On the intellectual plane, it signifies discussion, wordy strife; in business--negotiations, war of trade, barter, competition. It is further a card of success, for the combatant is on the top and his enemies may be unable to reach him. Reversed: Perplexity, embarrassments, anxiety. It is also a caution against indecision.", "The card represents motion through the immovable-a flight of wands through an open country; but they draw to the term of their course. That which they signify is at hand; it may be even on the threshold. Divinatory Meanings: Activity in undertakings, the path of such activity, swiftness, as that of an express messenger; great haste, great hope, speed towards an end which promises assured felicity; generally, that which is on the move; also the arrows of love. Reversed: Arrows of jealousy, internal dispute, stingings of conscience, quarrels; and domestic disputes for persons who are married.", "The figure leans upon his staff and has an expectant look, as if awaiting an enemy. Behind are eight other staves--erect, in orderly disposition, like a palisade. Divinatory Meanings: The card signifies strength in opposition. If attacked, the person will meet an onslaught boldly; and his build shews, that he may prove a formidable antagonist. With this main significance there are all its possible adjuncts--delay, suspension, adjournment. Reversed: Obstacles, adversity, calamity.", "A man oppressed by the weight of the ten staves which he is carrying. Divinatory Meanings: A card of many significances, and some of the readings cannot be harmonized. I set aside that which connects it with honour and good faith. The chief meaning is oppression simply, but it is also fortune, gain, any kind of success, and then it is the oppression of these things. It is also a card of false-seeming, disguise, perfidy. The place which the figure is approaching may suffer from the rods that he carries. Success is stultified if the Nine of Swords follows, and if it is a question of a lawsuit, there will be certain loss. Reversed: Contrarieties, difficulties, intrigues, and their analogies.", "In a scene similar to the former, a young man stands in the act of proclamation. He is unknown but faithful, and his tidings are strange. Divinatory Meanings: Dark young man, faithful, a lover, an envoy, a postman. Beside a man, he will bear favourable testimony concerning him. A dangerous rival, if followed by the Page of Cups. Has the chief qualities of his suit. He may signify family intelligence. Reversed: Anecdotes, announcements, evil news. Also indecision and the instability which accompanies it.", "He is shewn as if upon a journey, armed with a short wand, and although mailed is not on a warlike errand. He is passing mounds or pyramids. The motion of the horse is a key to the character of its rider, and suggests the precipitate mood, or things connected therewith. Divinatory Meanings: Departure, absence, flight, emigration. A dark young man, friendly. Change of residence. Reversed: Rupture, division, interruption, discord,", "He is shewn as if upon a journey, armed with a short wand, and although mailed is not on a warlike errand. He is passing mounds or pyramids. The motion of the horse is a key to the character of its rider, and suggests the precipitate mood, or things connected therewith. Divinatory Meanings: Departure, absence, flight, emigration. A dark young man, friendly. Change of residence. Reversed: Rupture, division, interruption, discord,", "The WandsSuit throughout this suit are always in leaf, as it is a suit of life and animation. Emotionally and otherwise, the Queen's personality corresponds to that of the King, but is more magnetic. Divinatory Meanings: A dark woman, countrywoman, friendly, chaste, loving, honourable. If the card beside her signifies a man, she is well disposed towards him; if a woman, she is interested in the Querent. Also, love of money, or a certain success in business. Reversed: Good, economical, obliging, serviceable. Signifies also--but in certain positions and in the neighbourhood of other cards tending in such directions--opposition, jealousy, even deceit and infidelity.", "The waters are beneath, and thereon are water-lilies; the hand issues from the cloud, holding in its palm the cup, from which four streams are pouring; a dove, bearing in its bill a cross-marked Host, descends to place the Wafer in the Cup; the dew of water is falling on all sides. It is an intimation of that which may lie behind the Lesser Arcana. Divinatory Meanings: House of the true heart, joy, content, abode, nourishment, abundance, fertility; Holy Table, felicity hereof. Reversed: House of the false heart, mutation, instability, revolution.", "A youth and maiden are pledging one another, and above their cups rises the Caduceus of Hermes, between the great wings of which there appears a lion's head. It is a variant of a sign which is found in a few old examples of this card. Some curious emblematical meanings are attached to it, but they do not concern us in this place. Divinatory Meanings: Love, passion, friendship, affinity, union, concord, sympathy, the interrelation of the sexes, and--as a suggestion apart from all offices of divination--that desire which is not in Nature, but by which Nature is sanctified.", "Maidens in a garden-ground with cups uplifted, as if pledging one another. Divinatory Meanings: The conclusion of any matter in plenty, perfection and merriment; happy issue, victory, fulfilment, solace, healing, Reversed: Expedition, dispatch, achievement, end. It signifies also the side of excess in physical enjoyment, and the pleasures of the senses.", "A young man is seated under a tree and contemplates three cups set on the grass before him; an arm issuing from a cloud offers him another cup. His expression notwithstanding is one of discontent with his environment. Divinatory Meanings: Weariness, disgust, aversion, imaginary vexations, as if the wine of this world had caused satiety only; another wine, as if a fairy gift, is now offered the wastrel, but he sees no consolation therein. This is also a card of blended pleasure. Reversed: Novelty, presage, new instruction, new relations.", "A dark, cloaked figure, looking sideways at three prone cups two others stand upright behind him; a bridge is in the background, leading to a small keep or holding. Divanatory Meanings: It is a card of loss, but something remains over; three have been taken, but two are left; it is a card of inheritance, patrimony, transmission, but not corresponding to expectations; with some interpreters it is a card of marriage, but not without bitterness or frustration. Reversed: News, alliances, affinity, consanguinity, ancestry, return, false projects.", "Children in an old garden, their cups filled with flowers. Divinatory Meanings: A card of the past and of memories, looking back, as--for example--on childhood; happiness, enjoyment, but coming rather from the past; things that have vanished. Another reading reverses this, giving new relations, new knowledge, new environment, and then the children are disporting in an unfamiliar precinct. Reversed: The future, renewal, that which will come to pass presently.", "Strange chalices of vision, but the images are more especially those of the fantastic spirit. Divinatory Meanings: Fairy favours, images of reflection, sentiment, imagination, things seen in the glass of contemplation; some attainment in these degrees, but nothing permanent or substantial is suggested. Reversed: Desire, will, determination, project.", "A man of dejected aspect is deserting the cups of his felicity, enterprise, undertaking or previous concern. Divinatory Meanings: The card speaks for itself on the surface, but other readings are entirely antithetical--giving joy, mildness, timidity, honour, modesty. In practice, it is usually found that the card shews the decline of a matter, or that a matter which has been thought to be important is really of slight consequence--either for good or evil. Reversed: Great joy, happiness, feasting.", "A goodly personage has feasted to his heart's content, and abundant refreshment of wine is on the arched counter behind him, seeming to indicate that the future is also assured. The picture offers the material side only, but there are other aspects. Divinatory Meanings: Concord, contentment, physical bien-être; also victory, success, advantage; satisfaction for the Querent or person for whom the consultation is made. Reversed: Truth, loyalty, liberty; but the readings vary and include mistakes, imperfections, etc.", "Appearance of Cups in a rainbow; it is contemplated in wonder and ecstacy by a man and woman below, evidently husband and wife. His right arm is about her; his left is raised upward; she raises her right arm. The two children dancing near them have not observed the prodigy but are happy after their own manner. There is a home-scene beyond. Divinatory Meanings: Contentment, repose of the entire heart; the perfection of that state; also perfection of human love and friendship; if with several picture-cards, a person who is taking charge of the Querent's interests; also the town, village or country inhabited by the Querent. Reversed: Repose of the false heart, indignation, violence.", "A fair, pleasing, somewhat effeminate page, of studious and intent aspect, contemplates a fish rising from a cup to look at him. It is the pictures of the mind taking form. Divinatory Meanings: Fair young man, one impelled to render service and with whom the Querent will be connected; a studious youth; news, message; application, reflection, meditation; also these things directed to business. Reversed: Taste, inclination, attachment, seduction, deception, artifice.", "Graceful, but not warlike; riding quietly, wearing a winged helmet, referring to those higher graces of the imagination which sometimes characterize this card. He too is a dreamer, but the images of the side of sense haunt him in his vision. Divinatory Meanings: Arrival, approach--sometimes that of a messenger; advances, proposition, demeanour, invitation, incitement. Reversed: Trickery, artifice, subtlety, swindling, duplicity, fraud.", "He holds a short sceptre in his left hand and a great cup in his right; his throne is set upon the sea; on one side a ship is riding and on the other a dolphin is leaping. The implicit is that the Sign of the Cup naturally refers to water, which appears in all the court cards. Divinatory Meanings: Fair man, man of business, law, or divinity; responsible, disposed to oblige the Querent; also equity, art and science, including those who profess science, law and art; creative intelligence. Reversed: Dishonest, double-dealing man; roguery, exaction, injustice, vice, scandal, pillage, considerable loss.", "Beautiful, fair, dreamy--as one who sees visions in a cup. This is, however, only one of her aspects; she sees, but she also acts, and her activity feeds her dream. Divinatory Meanings: Good, fair woman; honest, devoted woman, who will do service to the Querent; loving intelligence, and hence the gift of vision; success, happiness, pleasure; also wisdom, virtue; a perfect spouse and a good mother. Reversed: The accounts vary; good woman; otherwise, distinguished woman but one not to be trusted; perverse woman; vice, dishonour, depravity.", "A hand--issuing, as usual, from a cloud--holds up a pentacle. Divinatory Meanings: Perfect contentment, felicity, ecstasy; also speedy intelligence; gold. Reversed: The evil side of wealth, bad intelligence; also great riches. In any case it shews prosperity, comfortable material conditions, but whether these are of advantage to the possessor will depend on whether the card is reversed or not.", "A young man, in the act of dancing, has a pentacle in either hand, and they are joined by that endless cord which is like the number 8 reversed. Divinatory Meanings: On the one hand it is represented as a card of gaiety, recreation and its connexions, which is the subject of the design; but it is read also as news and messages in writing, as obstacles, agitation, trouble, embroilment. Reversed: Enforced gaiety, simulated enjoyment, literal sense, handwriting, composition, letters of exchange.", "A sculptor at his work in a monastery. Compare the design which illustrates the Eight of Pentacles. The apprentice or amateur therein has received his reward and is now at work in earnest. Divinatory Meanings: Métier, trade, skilled labour; usually, however, regarded as a card of nobility, aristocracy, renown, glory. Reversed: Mediocrity, in work and otherwise, puerility, pettiness, weakness.", "A crowned figure, having a pentacle over his crown, clasps another with hands and arms; two pentacles are under his feet. He holds to that which he has. Divinatory Meanings: The surety of possessions, cleaving to that which one has, gift, legacy, inheritance. Reversed: Suspense, delay, opposition.", "Two mendicants in a snow-storm pass a lighted casement. Divinatory Meanings: The card foretells material trouble above all, whether in the form illustrated--that is, destitution--or otherwise. For some cartomancists, it is a card of love and lovers-wife, husband, friend, mistress; also concordance, affinities. These alternatives cannot be harmonized. Reversed: Disorder, chaos, ruin, discord, profligacy.", "A person in the guise of a merchant weighs money in a pair of scales and distributes it to the needy and distressed. It is a testimony to his own success in life, as well as to his goodness of heart. Divinatory Meanings: Presents, gifts, gratification another account says attention, vigilance now is the accepted time, present prosperity, etc. Reversed: Desire, cupidity, envy, jealousy, illusion.", "A young man, leaning on his staff, looks intently at seven pentacles attached to a clump of greenery on his right; one would say that these were his treasures and that his heart was there. Divinatory Meanings: These are exceedingly contradictory; in the main, it is a card of money, business, barter; but one reading gives altercation, quarrels--and another innocence, ingenuity, purgation. Reversed: Cause for anxiety regarding money which it may be proposed to lend.", "An artist in stone at his work, which he exhibits in the form of trophies. Divinatory Meanings: Work, employment, commission, craftsmanship, skill in craft and business, perhaps in the preparatory stage. Reversed: Voided ambition, vanity, cupidity, exaction, usury. It may also signify the possession of skill, in the sense of the ingenious mind turned to cunning and intrigue.", "A woman, with a bird upon her wrist, stands amidst a great abundance of grapevines in the garden of a manorial house. It is a wide domain, suggesting plenty in all things. Possibly it is her own possession and testifies to material well-being. Divinatory Meanings: Prudence, safety, success, accomplishment, certitude, discernment. Reversed: Roguery, deception, voided project, bad faith.", "A man and woman beneath an archway which gives entrance to a house and domain. They are accompanied by a child, who looks curiously at two dogs accosting an ancient personage seated in the foreground. The child's hand is on one of them. Divinatory Meanings: Gain, riches; family matters, archives, extraction, the abode of a family. Reversed: Chance, fatality, loss, robbery, games of hazard; sometimes gift, dowry, pension.", "A youthful figure, looking intently at the pentacle which hovers over his raised hands. He moves slowly, insensible of that which is about him. Divinatory Meanings: Application, study, scholarship, reflection another reading says news, messages and the bringer thereof; also rule, management. Reversed: Prodigality, dissipation, liberality, luxury; unfavourable news.", "He rides a slow, enduring, heavy horse, to which his own aspect corresponds. He exhibits his symbol, but does not look therein. Divinatory Meanings: Utility, serviceableness, interest, responsibility, rectitude-all on the normal and external plane. Reversed: inertia, idleness, repose of that kind, stagnation; also placidity, discouragement, carelessness.", "The figure calls for no special description the face is rather dark, suggesting also courage, but somewhat lethargic in tendency. The bull's head should be noted as a recurrent symbol on the throne. The sign of this suit is represented throughout as engraved or blazoned with the pentagram, typifying the correspondence of the four elements in human nature and that by which they may be governed. In many old Tarot packs this suit stood for current coin, money, deniers. I have not invented the substitution of pentacles and I have no special cause to sustain in respect of the alternative. But the consensus of divinatory meanings is on the side of some change, because the cards do not happen to getCards especially with questions of money. Divinatory Meanings: Valour, realizing intelligence, business and normal intellectual aptitude, sometimes mathematical gifts and attainments of this kind; success in these paths. Reversed: Vice, weakness, ugliness, perversity, corruption, peril.", "The face suggests that of a dark woman, whose qualities might be summed up in the idea of greatness of soul; she has also the serious cast of intelligence; she contemplates her symbol and may see worlds therein. Divinatory Meanings: Opulence, generosity, magnificence, security, liberty. Reversed: Evil, suspicion, suspense, fear, mistrust.", " " }; /** * Major Arcana card names */ public static String[] CARD_TITLE = new String[]{ "0 - The Fool", "1 - The Magus", "2 - The High Priestess", "3 - The Empress", "4 - The Emperor", "5 - The Hierophant", "6 - The Lover(s)", "7 - The Charoit", "8 - Strength", "9 - The Hermit", "10 - Wheel of Fortune", "11 - Justice", "12 - The Hanged Man", "13 - Death", "14 - Temperance", "15 - The Devil", "16 - The Tower", "17 - The Star", "18 - The Moon", "19 - The Sun", "20 - Judgement", "21 - The World", //s,w,c,p //SWORDS "Ace of Swords", "Two of Swords", "Three of Sword", "Four of Swords", "Five of Swords", "Six of Swords", "Seven of Swords", "Eight of Swords", "Nine of Swords", "Ten of Swords", "Page of Swords", "Knight of Swords", "King of Swords", "Queen of Swords", //WANDS "Ace of Wands", "Two of Wands", "Three of Wands", "Four of Wands", "Five of Wands", "Six of Wands", "Seven of Wands", "Eight of Wands", "Nine of Wands", "Ten of Wands", "Page of Wands", "Knight of Wands", "King of Wands", "Queen of wands", //CUPS "Ace of Cups", "Two of Cups", "Three of Cups", "Four of Cups", "Five of Cups", "Six of Cups", "Seven of Cups", "Eight of Cups", "Nine of Cups", "Ten of Cups", "Page of Cups", "Knight of Cups", "King of Cups", "Queen of Cups", //COINS "Ace of Pentacles", "Two of Pentacles", "Three of Pentacles", "Four of Pentacles", "Five of Pentacles", "Six of Pentacles", "Seven of Pentacles", "Eight of Pentacles", "Nine of Pentacles", "Ten of Pentacles", "Page of Pentacles", "Knight of Pentacles", "King of Pentacles", "Queen of Pentacles" }; /** * Card Images */ static final ImageView[] MERC = new ImageView[]{ new ImageView(new Image(getImageFile(THE_FOOL, MERC_DECK))), new ImageView(new Image(getImageFile(THE_MAGUS, MERC_DECK))), new ImageView(new Image(getImageFile(THE_HIGH_PRIESTESS, MERC_DECK))), new ImageView(new Image(getImageFile(THE_EMPRESS, MERC_DECK))), new ImageView(new Image(getImageFile(THE_EMPEROR, MERC_DECK))), new ImageView(new Image(getImageFile(THE_HEIROPHANT, MERC_DECK))), new ImageView(new Image(getImageFile(THE_LOVER, MERC_DECK))), new ImageView(new Image(getImageFile(THE_CHARIOT, MERC_DECK))), new ImageView(new Image(getImageFile(STRENGTH, MERC_DECK))), new ImageView(new Image(getImageFile(THE_HERMIT, MERC_DECK))), new ImageView(new Image(getImageFile(WHEEL_OF_FORTUNE, MERC_DECK))), new ImageView(new Image(getImageFile(JUSTICE, MERC_DECK))), new ImageView(new Image(getImageFile(THE_HANGED_MAN, MERC_DECK))), new ImageView(new Image(getImageFile(DEATH, MERC_DECK))), new ImageView(new Image(getImageFile(TEMPERANCE, MERC_DECK))), new ImageView(new Image(getImageFile(THE_DEVIL, MERC_DECK))), new ImageView(new Image(getImageFile(THE_TOWER, MERC_DECK))), new ImageView(new Image(getImageFile(THE_STAR, MERC_DECK))), new ImageView(new Image(getImageFile(THE_MOON, MERC_DECK))), new ImageView(new Image(getImageFile(THE_SUN, MERC_DECK))), new ImageView(new Image(getImageFile(JUDGEMENT, MERC_DECK))), new ImageView(new Image(getImageFile(THE_WORLD, MERC_DECK))), //Sword Images new ImageView(new Image(getImageFile(ACE_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(TWO_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(THREE_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(FOUR_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(FIVE_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(SIX_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(SEVEN_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(EIGHT_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(NINE_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(TEN_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(PAGE_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(KNIGHT_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(KING_OF_SWORDS, MERC_DECK))), new ImageView(new Image(getImageFile(QUEEN_OF_SWORDS, MERC_DECK))), //Wand Images new ImageView(new Image(getImageFile(ACE_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(TWO_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(THREE_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(FOUR_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(FIVE_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(SIX_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(SEVEN_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(EIGHT_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(NINE_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(TEN_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(PAGE_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(KNIGHT_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(KING_OF_WANDS, MERC_DECK))), new ImageView(new Image(getImageFile(QUEEN_OF_WANDS, MERC_DECK))), //Cups Images new ImageView(new Image(getImageFile(ACE_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(TWO_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(THREE_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(FOUR_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(FIVE_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(SIX_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(SEVEN_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(EIGHT_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(NINE_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(TEN_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(PAGE_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(KNIGHT_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(KING_OF_CUPS, MERC_DECK))), new ImageView(new Image(getImageFile(QUEEN_OF_CUPS, MERC_DECK))), //pent Images new ImageView(new Image(getImageFile(ACE_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(TWO_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(THREE_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(FOUR_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(FIVE_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(SIX_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(SEVEN_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(EIGHT_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(NINE_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(TEN_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(PAGE_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(KNIGHT_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(KING_OF_PENTACLES, MERC_DECK))), new ImageView(new Image(getImageFile(QUEEN_OF_PENTACLES, MERC_DECK))), new ImageView(new Image("/card/image/ZSpBack.gif"))}; /** * Card Images */ static final ImageView[] WD = new ImageView[]{ new ImageView(new Image(getImageFile(THE_FOOL, WIADEC))), new ImageView(new Image(getImageFile(THE_MAGUS, WIADEC))), new ImageView(new Image(getImageFile(THE_HIGH_PRIESTESS, WIADEC))), new ImageView(new Image(getImageFile(THE_EMPRESS, WIADEC))), new ImageView(new Image(getImageFile(THE_EMPEROR, WIADEC))), new ImageView(new Image(getImageFile(THE_HEIROPHANT, WIADEC))), new ImageView(new Image(getImageFile(THE_LOVER, WIADEC))), new ImageView(new Image(getImageFile(THE_CHARIOT, WIADEC))), new ImageView(new Image(getImageFile(STRENGTH, WIADEC))), new ImageView(new Image(getImageFile(THE_HERMIT, WIADEC))), new ImageView(new Image(getImageFile(WHEEL_OF_FORTUNE, WIADEC))), new ImageView(new Image(getImageFile(JUSTICE, WIADEC))), new ImageView(new Image(getImageFile(THE_HANGED_MAN, WIADEC))), new ImageView(new Image(getImageFile(DEATH, WIADEC))), new ImageView(new Image(getImageFile(TEMPERANCE, WIADEC))), new ImageView(new Image(getImageFile(THE_DEVIL, WIADEC))), new ImageView(new Image(getImageFile(THE_TOWER, WIADEC))), new ImageView(new Image(getImageFile(THE_STAR, WIADEC))), new ImageView(new Image(getImageFile(THE_MOON, WIADEC))), new ImageView(new Image(getImageFile(THE_SUN, WIADEC))), new ImageView(new Image(getImageFile(JUDGEMENT, WIADEC))), new ImageView(new Image(getImageFile(THE_WORLD, WIADEC))), //Sword Images new ImageView(new Image(getImageFile(ACE_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(TWO_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(THREE_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(FOUR_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(FIVE_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(SIX_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(SEVEN_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(EIGHT_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(NINE_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(TEN_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(PAGE_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(KNIGHT_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(KING_OF_SWORDS, WIADEC))), new ImageView(new Image(getImageFile(QUEEN_OF_SWORDS, WIADEC))), //Wand Images new ImageView(new Image(getImageFile(ACE_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(TWO_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(THREE_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(FOUR_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(FIVE_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(SIX_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(SEVEN_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(EIGHT_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(NINE_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(TEN_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(PAGE_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(KNIGHT_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(KING_OF_WANDS, WIADEC))), new ImageView(new Image(getImageFile(QUEEN_OF_WANDS, WIADEC))), //Cups Images new ImageView(new Image(getImageFile(ACE_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(TWO_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(THREE_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(FOUR_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(FIVE_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(SIX_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(SEVEN_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(EIGHT_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(NINE_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(TEN_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(PAGE_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(KNIGHT_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(KING_OF_CUPS, WIADEC))), new ImageView(new Image(getImageFile(QUEEN_OF_CUPS, WIADEC))), //pent Images new ImageView(new Image(getImageFile(ACE_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(TWO_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(THREE_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(FOUR_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(FIVE_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(SIX_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(SEVEN_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(EIGHT_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(NINE_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(TEN_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(PAGE_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(KNIGHT_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(KING_OF_PENTACLES, WIADEC))), new ImageView(new Image(getImageFile(QUEEN_OF_PENTACLES, WIADEC))), new ImageView(new Image("/card/image/ZSpBack.gif"))}; /** * Card Images */ static final ImageView[] ART_DECK = new ImageView[]{ new ImageView(new Image(getImageFile(THE_FOOL, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_MAGUS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_HIGH_PRIESTESS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_EMPRESS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_EMPEROR, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_HEIROPHANT, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_LOVER, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_CHARIOT, WIA_ART_DECK))), new ImageView(new Image(getImageFile(STRENGTH, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_HERMIT, WIA_ART_DECK))), new ImageView(new Image(getImageFile(WHEEL_OF_FORTUNE, WIA_ART_DECK))), new ImageView(new Image(getImageFile(JUSTICE, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_HANGED_MAN, WIA_ART_DECK))), new ImageView(new Image(getImageFile(DEATH, WIA_ART_DECK))), new ImageView(new Image(getImageFile(TEMPERANCE, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_DEVIL, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_TOWER, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_STAR, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_MOON, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_SUN, WIA_ART_DECK))), new ImageView(new Image(getImageFile(JUDGEMENT, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THE_WORLD, WIA_ART_DECK))), //Sword Images new ImageView(new Image(getImageFile(ACE_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(TWO_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THREE_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(FOUR_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(FIVE_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(SIX_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(SEVEN_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(EIGHT_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(NINE_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(TEN_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(PAGE_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(KNIGHT_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(KING_OF_SWORDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(QUEEN_OF_SWORDS, WIA_ART_DECK))), //Wand Images new ImageView(new Image(getImageFile(ACE_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(TWO_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THREE_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(FOUR_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(FIVE_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(SIX_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(SEVEN_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(EIGHT_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(NINE_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(TEN_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(PAGE_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(KNIGHT_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(KING_OF_WANDS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(QUEEN_OF_WANDS, WIA_ART_DECK))), //Cups Images new ImageView(new Image(getImageFile(ACE_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(TWO_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THREE_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(FOUR_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(FIVE_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(SIX_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(SEVEN_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(EIGHT_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(NINE_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(TEN_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(PAGE_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(KNIGHT_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(KING_OF_CUPS, WIA_ART_DECK))), new ImageView(new Image(getImageFile(QUEEN_OF_CUPS, WIA_ART_DECK))), //pent Images new ImageView(new Image(getImageFile(ACE_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(TWO_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(THREE_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(FOUR_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(FIVE_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(SIX_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(SEVEN_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(EIGHT_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(NINE_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(TEN_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(PAGE_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(KNIGHT_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(KING_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image(getImageFile(QUEEN_OF_PENTACLES, WIA_ART_DECK))), new ImageView(new Image("/card/image/ZSpBack.gif"))}; //Keep track of which way the card is facing, prob going to use this in DealingLogic.initAnimation private boolean hasBeenFlipped = false; public boolean isHasBeenFlipped() { return hasBeenFlipped; } public void setHasBeenFlipped(boolean b) { } /** * @param card card requested * @return the URL of requested card Image */ public static String getImageFile(int card, int deck) { if (deck == WIADEC) { - return "/card/image/decks/wiate/" + card + ".gif"; + return "/card/image/decks/1910/" + card + ".jpg"; } if (deck == MERC_DECK) { return "/card/image/decks/merc/" + card + ".jpg"; } if (deck == WIA_ART_DECK) { return "/card/image/decks/artdeck/" + card + ".jpg"; } else { return null; } } /** * @param card card Number * @return the Image View of requested card */ public static ImageView getImageView(int card, int deck) { if (deck == MERC_DECK) { return MERC[card]; } if (deck == WIADEC) { return WD[card]; } if (deck == WIA_ART_DECK) { return ART_DECK[card]; } else { return null; } } /** * @param card card number * @return The in depth meaning of the card */ public static String getCardMeaning(int card) { return CARD_MEANINGS[card]; } /** * @param card the requested card * @return Title of the Card */ public static String getCardTitle(int card) { return CARD_TITLE[card]; } }
true
true
public static String getImageFile(int card, int deck) { if (deck == WIADEC) { return "/card/image/decks/wiate/" + card + ".gif"; } if (deck == MERC_DECK) { return "/card/image/decks/merc/" + card + ".jpg"; } if (deck == WIA_ART_DECK) { return "/card/image/decks/artdeck/" + card + ".jpg"; } else { return null; } }
public static String getImageFile(int card, int deck) { if (deck == WIADEC) { return "/card/image/decks/1910/" + card + ".jpg"; } if (deck == MERC_DECK) { return "/card/image/decks/merc/" + card + ".jpg"; } if (deck == WIA_ART_DECK) { return "/card/image/decks/artdeck/" + card + ".jpg"; } else { return null; } }
diff --git a/src/com/zavteam/plugins/RunnableMessager.java b/src/com/zavteam/plugins/RunnableMessager.java index 3950926..bb15a2a 100644 --- a/src/com/zavteam/plugins/RunnableMessager.java +++ b/src/com/zavteam/plugins/RunnableMessager.java @@ -1,79 +1,79 @@ package com.zavteam.plugins; import java.util.Random; import org.bukkit.ChatColor; import org.bukkit.util.ChatPaginator; public class RunnableMessager implements Runnable { public ZavAutoMessager plugin; public RunnableMessager(ZavAutoMessager plugin) { this.plugin = plugin; } private int previousMessage; private static ChatColor[] COLOR_LIST = {ChatColor.AQUA, ChatColor.BLACK, ChatColor.BLUE, ChatColor.DARK_AQUA, ChatColor.DARK_BLUE, ChatColor.DARK_GRAY, ChatColor.DARK_GREEN, ChatColor.DARK_PURPLE, ChatColor.DARK_RED, ChatColor.GOLD, ChatColor.GRAY, ChatColor.GREEN, ChatColor.LIGHT_PURPLE, ChatColor.RED, ChatColor.YELLOW}; @Override public void run() { boolean messageRandom = (Boolean) plugin.mainConfig.get("messageinrandomorder", false); - if ((Boolean) plugin.mainConfig.get("messageinrandomorder", false)) { + if ((Boolean) plugin.mainConfig.get("enabled", true)) { String[] cutMessageList = new String[10]; if (plugin.messages.size() == 1) { plugin.messageIt = 0; } else { if (messageRandom) { plugin.messageIt = getRandomMessage(); } } ChatMessage cm = null; try { cm = plugin.messages.get(plugin.messageIt); } catch (Exception e) { e.printStackTrace(); ZavAutoMessager.log.severe("Cannot load messages. There is most likely an error with your config. Please check"); ZavAutoMessager.log.severe("Shutting down plugin."); plugin.disableZavAutoMessager(); } cutMessageList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cm.getMessage()); cutMessageList[0] = cutMessageList[0].replace("&random", getRandomChatColor()); cutMessageList[0] = ChatColor.translateAlternateColorCodes('&', cutMessageList[0]); if ((Boolean) plugin.mainConfig.get("wordwrap", true)) { cutMessageList = cutMessageList[0].split("%n"); } else { cutMessageList = ChatPaginator.wordWrap(cutMessageList[0], 59); } plugin.MessagesHandler.handleMessage(cutMessageList, cm); if (plugin.messageIt == plugin.messages.size() - 1) { plugin.messageIt = 0; } else { plugin.messageIt = plugin.messageIt + 1; } } } private String getRandomChatColor() { Random random = new Random(); return COLOR_LIST[random.nextInt(COLOR_LIST.length)].toString(); } private int getRandomMessage() { Random random = new Random(); if ((Boolean) plugin.mainConfig.get("dontrepeatrandommessages", true)) { int i = random.nextInt(plugin.messages.size()); if (!(i == previousMessage)) { previousMessage = i; return i; } return getRandomMessage(); } return random.nextInt(plugin.messages.size()); } }
true
true
public void run() { boolean messageRandom = (Boolean) plugin.mainConfig.get("messageinrandomorder", false); if ((Boolean) plugin.mainConfig.get("messageinrandomorder", false)) { String[] cutMessageList = new String[10]; if (plugin.messages.size() == 1) { plugin.messageIt = 0; } else { if (messageRandom) { plugin.messageIt = getRandomMessage(); } } ChatMessage cm = null; try { cm = plugin.messages.get(plugin.messageIt); } catch (Exception e) { e.printStackTrace(); ZavAutoMessager.log.severe("Cannot load messages. There is most likely an error with your config. Please check"); ZavAutoMessager.log.severe("Shutting down plugin."); plugin.disableZavAutoMessager(); } cutMessageList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cm.getMessage()); cutMessageList[0] = cutMessageList[0].replace("&random", getRandomChatColor()); cutMessageList[0] = ChatColor.translateAlternateColorCodes('&', cutMessageList[0]); if ((Boolean) plugin.mainConfig.get("wordwrap", true)) { cutMessageList = cutMessageList[0].split("%n"); } else { cutMessageList = ChatPaginator.wordWrap(cutMessageList[0], 59); } plugin.MessagesHandler.handleMessage(cutMessageList, cm); if (plugin.messageIt == plugin.messages.size() - 1) { plugin.messageIt = 0; } else { plugin.messageIt = plugin.messageIt + 1; } } }
public void run() { boolean messageRandom = (Boolean) plugin.mainConfig.get("messageinrandomorder", false); if ((Boolean) plugin.mainConfig.get("enabled", true)) { String[] cutMessageList = new String[10]; if (plugin.messages.size() == 1) { plugin.messageIt = 0; } else { if (messageRandom) { plugin.messageIt = getRandomMessage(); } } ChatMessage cm = null; try { cm = plugin.messages.get(plugin.messageIt); } catch (Exception e) { e.printStackTrace(); ZavAutoMessager.log.severe("Cannot load messages. There is most likely an error with your config. Please check"); ZavAutoMessager.log.severe("Shutting down plugin."); plugin.disableZavAutoMessager(); } cutMessageList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cm.getMessage()); cutMessageList[0] = cutMessageList[0].replace("&random", getRandomChatColor()); cutMessageList[0] = ChatColor.translateAlternateColorCodes('&', cutMessageList[0]); if ((Boolean) plugin.mainConfig.get("wordwrap", true)) { cutMessageList = cutMessageList[0].split("%n"); } else { cutMessageList = ChatPaginator.wordWrap(cutMessageList[0], 59); } plugin.MessagesHandler.handleMessage(cutMessageList, cm); if (plugin.messageIt == plugin.messages.size() - 1) { plugin.messageIt = 0; } else { plugin.messageIt = plugin.messageIt + 1; } } }
diff --git a/src/aor/SimplePlugin/Spells/RapidfireArrowSpell.java b/src/aor/SimplePlugin/Spells/RapidfireArrowSpell.java index ca3e27a..e81fcce 100644 --- a/src/aor/SimplePlugin/Spells/RapidfireArrowSpell.java +++ b/src/aor/SimplePlugin/Spells/RapidfireArrowSpell.java @@ -1,65 +1,65 @@ package aor.SimplePlugin.Spells; import org.bukkit.entity.Player; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.ItemStack; import org.bukkit.Material; import org.bukkit.Location; import org.bukkit.util.Vector; import org.bukkit.block.Block; import org.bukkit.entity.Arrow; import aor.SimplePlugin.SimplePlugin; import aor.SimplePlugin.Spell; public class RapidfireArrowSpell extends Spell { public static SimplePlugin plugin; private static final int MAXDISTANCE = 200; // Sets the maximum distance. public RapidfireArrowSpell() // Constructor. { spellName = "Rapidfire Arrow"; spellDescription = "Quickly fires off eight arrows. Needs four redstone."; } public void castSpell(Player player) { PlayerInventory inventory = player.getInventory(); // REQUIRED ITEMS ItemStack[] requiredItems = new ItemStack[2]; // The requireditems itemstack. requiredItems[0] = new ItemStack(Material.ARROW, 8); // We need 8 arrows. requiredItems[1] = new ItemStack(Material.REDSTONE, 4); // We need 2 redstone. // REQUIRED ITEMS if (checkInventoryRequirements(inventory, requiredItems)) { removeRequiredItemsFromInventory(inventory, requiredItems); // Remove the items. player.shootArrow(); for (int i = 0; i < 7; i++) // Fire off 7 more. { - try { Thread.sleep(150); } //Question: Is this really a good idea? Do we know if all the spells run on the same thread? Do all instances of this spell run on the same one? This could be basically causing the plugin to stop and start over and over again... Shouldn't we be making a new thread for each player's spellbook or something? or running it in the thread that already exists for each player? -Josh + try { Thread.sleep(150); } // See online Issues page about this. catch(InterruptedException ae) { System.out.println(ae); } // If sleep fails player.shootArrow(); } player.sendMessage("Rapidfire!"); // They have the proper items. } else { player.sendMessage("Could not cast! Spell requires 4 redstone, 8 arrow!"); } // They don't have the proper items. } }
true
true
public void castSpell(Player player) { PlayerInventory inventory = player.getInventory(); // REQUIRED ITEMS ItemStack[] requiredItems = new ItemStack[2]; // The requireditems itemstack. requiredItems[0] = new ItemStack(Material.ARROW, 8); // We need 8 arrows. requiredItems[1] = new ItemStack(Material.REDSTONE, 4); // We need 2 redstone. // REQUIRED ITEMS if (checkInventoryRequirements(inventory, requiredItems)) { removeRequiredItemsFromInventory(inventory, requiredItems); // Remove the items. player.shootArrow(); for (int i = 0; i < 7; i++) // Fire off 7 more. { try { Thread.sleep(150); } //Question: Is this really a good idea? Do we know if all the spells run on the same thread? Do all instances of this spell run on the same one? This could be basically causing the plugin to stop and start over and over again... Shouldn't we be making a new thread for each player's spellbook or something? or running it in the thread that already exists for each player? -Josh catch(InterruptedException ae) { System.out.println(ae); } // If sleep fails player.shootArrow(); } player.sendMessage("Rapidfire!"); // They have the proper items. } else { player.sendMessage("Could not cast! Spell requires 4 redstone, 8 arrow!"); } // They don't have the proper items. }
public void castSpell(Player player) { PlayerInventory inventory = player.getInventory(); // REQUIRED ITEMS ItemStack[] requiredItems = new ItemStack[2]; // The requireditems itemstack. requiredItems[0] = new ItemStack(Material.ARROW, 8); // We need 8 arrows. requiredItems[1] = new ItemStack(Material.REDSTONE, 4); // We need 2 redstone. // REQUIRED ITEMS if (checkInventoryRequirements(inventory, requiredItems)) { removeRequiredItemsFromInventory(inventory, requiredItems); // Remove the items. player.shootArrow(); for (int i = 0; i < 7; i++) // Fire off 7 more. { try { Thread.sleep(150); } // See online Issues page about this. catch(InterruptedException ae) { System.out.println(ae); } // If sleep fails player.shootArrow(); } player.sendMessage("Rapidfire!"); // They have the proper items. } else { player.sendMessage("Could not cast! Spell requires 4 redstone, 8 arrow!"); } // They don't have the proper items. }
diff --git a/src/org/openstreetmap/josm/plugins/scripting/ui/RunScriptAction.java b/src/org/openstreetmap/josm/plugins/scripting/ui/RunScriptAction.java index 6743d8e..bdb1013 100644 --- a/src/org/openstreetmap/josm/plugins/scripting/ui/RunScriptAction.java +++ b/src/org/openstreetmap/josm/plugins/scripting/ui/RunScriptAction.java @@ -1,35 +1,35 @@ package org.openstreetmap.josm.plugins.scripting.ui; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.actions.JosmAction; import org.openstreetmap.josm.gui.help.HelpUtil; import org.openstreetmap.josm.tools.Shortcut; public class RunScriptAction extends JosmAction { private static final long serialVersionUID = 1L; public RunScriptAction() { super(tr("Run..."), // title "run", // icon name tr("Run a script"), // tooltip Shortcut.registerShortcut("scripting:runScript", tr("Scripting: Run a Script"), KeyEvent.VK_R, Shortcut.NONE // don't assign an action group, let the // the user assign in the preferences ), false, // don't register toolbar item - "scripting:toggleConsole", false // don't install adapters + "scripting:runScript", false // don't install adapters ); putValue("help", HelpUtil.ht("/Plugin/Scripting")); } @Override public void actionPerformed(ActionEvent evt) { RunScriptDialog dialog = new RunScriptDialog(Main.parent); dialog.setVisible(true); } }
true
true
public RunScriptAction() { super(tr("Run..."), // title "run", // icon name tr("Run a script"), // tooltip Shortcut.registerShortcut("scripting:runScript", tr("Scripting: Run a Script"), KeyEvent.VK_R, Shortcut.NONE // don't assign an action group, let the // the user assign in the preferences ), false, // don't register toolbar item "scripting:toggleConsole", false // don't install adapters ); putValue("help", HelpUtil.ht("/Plugin/Scripting")); }
public RunScriptAction() { super(tr("Run..."), // title "run", // icon name tr("Run a script"), // tooltip Shortcut.registerShortcut("scripting:runScript", tr("Scripting: Run a Script"), KeyEvent.VK_R, Shortcut.NONE // don't assign an action group, let the // the user assign in the preferences ), false, // don't register toolbar item "scripting:runScript", false // don't install adapters ); putValue("help", HelpUtil.ht("/Plugin/Scripting")); }
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllExplanation.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllExplanation.java index 9c0c1302f..87a58247d 100644 --- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllExplanation.java +++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/planner/AllExplanation.java @@ -1,33 +1,33 @@ /******************************************************************************* * Copyright (c) 2005, 2009 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.equinox.p2.tests.planner; import junit.framework.*; public class AllExplanation extends TestCase { public static Test suite() { - TestSuite suite = new TestSuite(AllTests.class.getName()); + TestSuite suite = new TestSuite(AllExplanation.class.getName()); suite.addTestSuite(ExplanationDeepConflict.class); suite.addTestSuite(ExplanationForOptionalDependencies.class); suite.addTestSuite(ExplanationForPartialInstallation.class); suite.addTestSuite(ExplanationLargeConflict.class); suite.addTestSuite(ExplanationSeveralConflictingRoots.class); suite.addTestSuite(MissingDependency.class); suite.addTestSuite(MissingNonGreedyRequirement.class); suite.addTestSuite(MissingNonGreedyRequirement2.class); suite.addTestSuite(MultipleSingleton.class); suite.addTestSuite(PatchTest10.class); suite.addTestSuite(PatchTest12.class); return suite; } }
true
true
public static Test suite() { TestSuite suite = new TestSuite(AllTests.class.getName()); suite.addTestSuite(ExplanationDeepConflict.class); suite.addTestSuite(ExplanationForOptionalDependencies.class); suite.addTestSuite(ExplanationForPartialInstallation.class); suite.addTestSuite(ExplanationLargeConflict.class); suite.addTestSuite(ExplanationSeveralConflictingRoots.class); suite.addTestSuite(MissingDependency.class); suite.addTestSuite(MissingNonGreedyRequirement.class); suite.addTestSuite(MissingNonGreedyRequirement2.class); suite.addTestSuite(MultipleSingleton.class); suite.addTestSuite(PatchTest10.class); suite.addTestSuite(PatchTest12.class); return suite; }
public static Test suite() { TestSuite suite = new TestSuite(AllExplanation.class.getName()); suite.addTestSuite(ExplanationDeepConflict.class); suite.addTestSuite(ExplanationForOptionalDependencies.class); suite.addTestSuite(ExplanationForPartialInstallation.class); suite.addTestSuite(ExplanationLargeConflict.class); suite.addTestSuite(ExplanationSeveralConflictingRoots.class); suite.addTestSuite(MissingDependency.class); suite.addTestSuite(MissingNonGreedyRequirement.class); suite.addTestSuite(MissingNonGreedyRequirement2.class); suite.addTestSuite(MultipleSingleton.class); suite.addTestSuite(PatchTest10.class); suite.addTestSuite(PatchTest12.class); return suite; }
diff --git a/devel/web/web-commons/src/main/java/net/contextfw/web/commons/minifier/ContentServlet.java b/devel/web/web-commons/src/main/java/net/contextfw/web/commons/minifier/ContentServlet.java index 96d856a..c4a5cab 100644 --- a/devel/web/web-commons/src/main/java/net/contextfw/web/commons/minifier/ContentServlet.java +++ b/devel/web/web-commons/src/main/java/net/contextfw/web/commons/minifier/ContentServlet.java @@ -1,121 +1,125 @@ package net.contextfw.web.commons.minifier; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.contextfw.web.application.ResourceCleaner; import net.contextfw.web.application.WebApplicationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; abstract class ContentServlet extends HttpServlet { private static final int SECOND = 1000; private static final long serialVersionUID = 1L; Logger logger = LoggerFactory.getLogger(ContentServlet.class); private ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); } }; private volatile String content; private final String host; private final String minifiedPath; private final String version; private final long started; private static final long EXPIRATION = 60 * 60 * 1000 * 8; private ResourceCleaner cleaner; protected ContentServlet(String host, String minifiedPath, long started, String version) { this.host = host; this.started = started; this.version = version; this.minifiedPath = minifiedPath; this.modifiedSince = new Date(started); } protected URL getUrl(String src) { try { return new URL(host + src); } catch (MalformedURLException e) { throw new WebApplicationException(e); } } String getMinifiedPath() { return minifiedPath.replaceFirst("<version>", version); } private final Date modifiedSince; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (content == null) { - cleaner.clean(); + synchronized (this) { + if (content == null) { + cleaner.clean(); + } + } } resp.setContentType(getContentType()); String modifiedHeader = req.getHeader("If-Modified-Since"); Date mod = null; if (modifiedHeader != null) { try { mod = format.get().parse(modifiedHeader); } catch (ParseException e) { logger.error("Error while parsing", e); } } HttpServletResponse httpResponse = (HttpServletResponse) resp; httpResponse.setDateHeader("Expires", started + EXPIRATION); httpResponse.setDateHeader("Date", started); httpResponse.setDateHeader("Last-Modified", started+SECOND); httpResponse.setHeader("Cache-Control", "max-age=2246400, must-revalidate"); httpResponse.setHeader("Pragma", "cache"); if (content != null && mod != null && modifiedSince.before(mod)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { resp.getWriter().print(content); } } protected abstract String getContentType(); public void setContent(String content) { this.content = content; } @Inject public void setCleaner(ResourceCleaner cleaner) { this.cleaner = cleaner; } }
true
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (content == null) { cleaner.clean(); } resp.setContentType(getContentType()); String modifiedHeader = req.getHeader("If-Modified-Since"); Date mod = null; if (modifiedHeader != null) { try { mod = format.get().parse(modifiedHeader); } catch (ParseException e) { logger.error("Error while parsing", e); } } HttpServletResponse httpResponse = (HttpServletResponse) resp; httpResponse.setDateHeader("Expires", started + EXPIRATION); httpResponse.setDateHeader("Date", started); httpResponse.setDateHeader("Last-Modified", started+SECOND); httpResponse.setHeader("Cache-Control", "max-age=2246400, must-revalidate"); httpResponse.setHeader("Pragma", "cache"); if (content != null && mod != null && modifiedSince.before(mod)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { resp.getWriter().print(content); } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (content == null) { synchronized (this) { if (content == null) { cleaner.clean(); } } } resp.setContentType(getContentType()); String modifiedHeader = req.getHeader("If-Modified-Since"); Date mod = null; if (modifiedHeader != null) { try { mod = format.get().parse(modifiedHeader); } catch (ParseException e) { logger.error("Error while parsing", e); } } HttpServletResponse httpResponse = (HttpServletResponse) resp; httpResponse.setDateHeader("Expires", started + EXPIRATION); httpResponse.setDateHeader("Date", started); httpResponse.setDateHeader("Last-Modified", started+SECOND); httpResponse.setHeader("Cache-Control", "max-age=2246400, must-revalidate"); httpResponse.setHeader("Pragma", "cache"); if (content != null && mod != null && modifiedSince.before(mod)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { resp.getWriter().print(content); } }
diff --git a/src/main/java/net/robbytu/banjoserver/bungee/perms/Permissions.java b/src/main/java/net/robbytu/banjoserver/bungee/perms/Permissions.java index 19424fa..212a948 100644 --- a/src/main/java/net/robbytu/banjoserver/bungee/perms/Permissions.java +++ b/src/main/java/net/robbytu/banjoserver/bungee/perms/Permissions.java @@ -1,35 +1,35 @@ package net.robbytu.banjoserver.bungee.perms;/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ import net.robbytu.banjoserver.bungee.Main; import net.robbytu.banjoserver.bungee.mail.Mail; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class Permissions { public static String getPrefixForUser(String user) { Connection conn = Main.conn; try { // Create a new select statement PreparedStatement statement = conn.prepareStatement("SELECT `bs_perm_groups`.`prefix` AS `group_name` " + "FROM `bs_perm_groups` " + - "INNER JOIN `bs_perm_members` " + + "INNER JOIN `bs_perm_members` ON `bs_perm_members`.`group` = `bs_perm_groups`.`id`" + "WHERE bs_perm_members.user LIKE ? " + "LIMIT 1"); statement.setString(1, user); ResultSet result = statement.executeQuery(); // If this user is a member of a group... if(result.next()) return result.getString(1); } catch (SQLException e) { e.printStackTrace(); } return "§3Speler"; } }
true
true
public static String getPrefixForUser(String user) { Connection conn = Main.conn; try { // Create a new select statement PreparedStatement statement = conn.prepareStatement("SELECT `bs_perm_groups`.`prefix` AS `group_name` " + "FROM `bs_perm_groups` " + "INNER JOIN `bs_perm_members` " + "WHERE bs_perm_members.user LIKE ? " + "LIMIT 1"); statement.setString(1, user); ResultSet result = statement.executeQuery(); // If this user is a member of a group... if(result.next()) return result.getString(1); } catch (SQLException e) { e.printStackTrace(); } return "§3Speler"; }
public static String getPrefixForUser(String user) { Connection conn = Main.conn; try { // Create a new select statement PreparedStatement statement = conn.prepareStatement("SELECT `bs_perm_groups`.`prefix` AS `group_name` " + "FROM `bs_perm_groups` " + "INNER JOIN `bs_perm_members` ON `bs_perm_members`.`group` = `bs_perm_groups`.`id`" + "WHERE bs_perm_members.user LIKE ? " + "LIMIT 1"); statement.setString(1, user); ResultSet result = statement.executeQuery(); // If this user is a member of a group... if(result.next()) return result.getString(1); } catch (SQLException e) { e.printStackTrace(); } return "§3Speler"; }
diff --git a/src/com/dmdirc/ui/swing/components/StandardInputDialog.java b/src/com/dmdirc/ui/swing/components/StandardInputDialog.java index 6c8458364..3800f470b 100644 --- a/src/com/dmdirc/ui/swing/components/StandardInputDialog.java +++ b/src/com/dmdirc/ui/swing/components/StandardInputDialog.java @@ -1,223 +1,223 @@ /* * Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes * * 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 com.dmdirc.ui.swing.components; import com.dmdirc.config.prefs.validator.ValidationResponse; import com.dmdirc.ui.swing.components.validating.ValidatingJTextField; import com.dmdirc.config.prefs.validator.Validator; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import net.miginfocom.swing.MigLayout; /** * Standard input dialog. */ public abstract class StandardInputDialog extends StandardDialog { /** Validator. */ private Validator<String> validator; /** Text field. */ private ValidatingJTextField textField; /** Blurb label. */ private TextLabel blurb; /** Message. */ private String message; /** * Instantiates a new standard input dialog. * * @param owner Dialog owner * @param modal modal? * @param title Dialog title * @param message Dialog message */ public StandardInputDialog(Frame owner, boolean modal, final String title, final String message) { this(owner, modal, title, message, new Validator<String>() { /** {@inheritDoc} */ @Override public ValidationResponse validate(final String object) { return new ValidationResponse(); } }); } /** * Instantiates a new standard input dialog. * * @param owner Dialog owner * @param modal modal? * @param validator Textfield validator * @param title Dialog title * @param message Dialog message */ public StandardInputDialog(Frame owner, boolean modal, final String title, final String message, final Validator<String> validator) { super(owner, modal); this.validator = validator; this.message = message; setTitle(title); initComponents(); addListeners(); layoutComponents(); } /** * Called when the dialog's OK button is clicked. * * @return whether the dialog can close */ public abstract boolean save(); /** * Called when the dialog's cancel button is clicked, or otherwise closed. */ public abstract void cancelled(); /** * Initialises the components. */ private final void initComponents() { orderButtons(new JButton(), new JButton()); textField = new ValidatingJTextField(validator); blurb = new TextLabel(message); validateText(); } /** * Adds the listeners */ private final void addListeners() { getOkButton().addActionListener(new ActionListener() { /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (save()) { dispose(); } } }); getCancelButton().addActionListener(new ActionListener() { /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { cancelled(); dispose(); } }); addWindowListener(new WindowAdapter() { /** {@inheritDoc} */ @Override public void windowClosed(WindowEvent e) { cancelled(); - dispose(); + //dispose(); } }); textField.getDocument().addDocumentListener(new DocumentListener() { /** {@inheritDoc} */ @Override public void insertUpdate(DocumentEvent e) { validateText(); } /** {@inheritDoc} */ @Override public void removeUpdate(DocumentEvent e) { validateText(); } /** {@inheritDoc} */ @Override public void changedUpdate(DocumentEvent e) { //Ignore } }); } /** * Validates the change. */ private void validateText() { getOkButton().setEnabled(!validator.validate(getText()).isFailure()); } /** * Lays out the components. */ private final void layoutComponents() { setLayout(new MigLayout("fill, wrap 1")); blurb.setMaximumSize(new Dimension(400, 0)); add(blurb, "growx"); add(textField, "growx"); add(getLeftButton(), "split 2, right"); add(getRightButton(), "right"); } /** * Displays the input dialog. */ public final void display() { pack(); setLocationRelativeTo(getParent()); setVisible(true); } /** * Returns the text in the input field. * * @return Input text */ public final String getText() { return textField.getText(); } /** * Sets the dialogs text to the specified text. * * @param text New test */ public final void setText(final String text) { textField.setText(text); } }
true
true
private final void addListeners() { getOkButton().addActionListener(new ActionListener() { /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (save()) { dispose(); } } }); getCancelButton().addActionListener(new ActionListener() { /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { cancelled(); dispose(); } }); addWindowListener(new WindowAdapter() { /** {@inheritDoc} */ @Override public void windowClosed(WindowEvent e) { cancelled(); dispose(); } }); textField.getDocument().addDocumentListener(new DocumentListener() { /** {@inheritDoc} */ @Override public void insertUpdate(DocumentEvent e) { validateText(); } /** {@inheritDoc} */ @Override public void removeUpdate(DocumentEvent e) { validateText(); } /** {@inheritDoc} */ @Override public void changedUpdate(DocumentEvent e) { //Ignore } }); }
private final void addListeners() { getOkButton().addActionListener(new ActionListener() { /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { if (save()) { dispose(); } } }); getCancelButton().addActionListener(new ActionListener() { /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { cancelled(); dispose(); } }); addWindowListener(new WindowAdapter() { /** {@inheritDoc} */ @Override public void windowClosed(WindowEvent e) { cancelled(); //dispose(); } }); textField.getDocument().addDocumentListener(new DocumentListener() { /** {@inheritDoc} */ @Override public void insertUpdate(DocumentEvent e) { validateText(); } /** {@inheritDoc} */ @Override public void removeUpdate(DocumentEvent e) { validateText(); } /** {@inheritDoc} */ @Override public void changedUpdate(DocumentEvent e) { //Ignore } }); }
diff --git a/xstream/src/java/com/thoughtworks/xstream/converters/reflection/FieldDictionary.java b/xstream/src/java/com/thoughtworks/xstream/converters/reflection/FieldDictionary.java index 1f370751..2f8a2363 100644 --- a/xstream/src/java/com/thoughtworks/xstream/converters/reflection/FieldDictionary.java +++ b/xstream/src/java/com/thoughtworks/xstream/converters/reflection/FieldDictionary.java @@ -1,186 +1,186 @@ /* * Copyright (C) 2004, 2005, 2006 Joe Walnes. * Copyright (C) 2006, 2007, 2008, 2009, 2010 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 14. May 2004 by Joe Walnes */ package com.thoughtworks.xstream.converters.reflection; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.core.util.OrderRetainingMap; /** * A field dictionary instance caches information about classes fields. * * @author Joe Walnes * @author J&ouml;rg Schaible * @author Guilherme Silveira */ public class FieldDictionary { private transient Map keyedByFieldNameCache; private transient Map keyedByFieldKeyCache; private final FieldKeySorter sorter; public FieldDictionary() { this(new ImmutableFieldKeySorter()); } public FieldDictionary(FieldKeySorter sorter) { this.sorter = sorter; init(); } private void init() { keyedByFieldNameCache = new HashMap(); keyedByFieldKeyCache = new HashMap(); keyedByFieldNameCache.put(Object.class, Collections.EMPTY_MAP); keyedByFieldKeyCache.put(Object.class, Collections.EMPTY_MAP); } /** * Returns an iterator for all fields for some class * * @param cls the class you are interested on * @return an iterator for its fields * @deprecated As of 1.3, use {@link #fieldsFor(Class)} instead */ public Iterator serializableFieldsFor(Class cls) { return fieldsFor(cls); } /** * Returns an iterator for all fields for some class * * @param cls the class you are interested on * @return an iterator for its fields */ public Iterator fieldsFor(final Class cls) { return buildMap(cls, true).values().iterator(); } /** * Returns an specific field of some class. If definedIn is null, it searches for the field * named 'name' inside the class cls. If definedIn is different than null, tries to find the * specified field name in the specified class cls which should be defined in class * definedIn (either equals cls or a one of it's superclasses) * * @param cls the class where the field is to be searched * @param name the field name * @param definedIn the superclass (or the class itself) of cls where the field was defined * @return the field itself * @throws ObjectAccessException if no field can be found */ public Field field(Class cls, String name, Class definedIn) { Field field = fieldOrNull(cls, name, definedIn); if (field == null) { throw new ObjectAccessException("No such field " + cls.getName() + "." + name); } else { return field; } } /** * Returns an specific field of some class. If definedIn is null, it searches for the field * named 'name' inside the class cls. If definedIn is different than null, tries to find the * specified field name in the specified class cls which should be defined in class * definedIn (either equals cls or a one of it's superclasses) * * @param cls the class where the field is to be searched * @param name the field name * @param definedIn the superclass (or the class itself) of cls where the field was defined * @return the field itself or <code>null</code> * @since upcoming */ public Field fieldOrNull(Class cls, String name, Class definedIn) { Map fields = buildMap(cls, definedIn != null); Field field = (Field)fields.get(definedIn != null ? (Object)new FieldKey(name, definedIn, 0) : (Object)name); return field; } private Map buildMap(final Class type, boolean tupleKeyed) { final Map result; Class cls = type; synchronized (this) { if (!keyedByFieldNameCache.containsKey(type)) { final List superClasses = new ArrayList(); while (!Object.class.equals(cls)) { superClasses.add(0, cls); cls = cls.getSuperclass(); } Map lastKeyedByFieldName = Collections.EMPTY_MAP; Map lastKeyedByFieldKey = Collections.EMPTY_MAP; for (final Iterator iter = superClasses.iterator(); iter.hasNext();) { cls = (Class)iter.next(); if (!keyedByFieldNameCache.containsKey(cls)) { final Map keyedByFieldName = new HashMap(lastKeyedByFieldName); final Map keyedByFieldKey = new OrderRetainingMap(lastKeyedByFieldKey); Field[] fields = cls.getDeclaredFields(); if (JVM.reverseFieldDefinition()) { for (int i = fields.length >> 1; i-- > 0;) { final int idx = fields.length - i - 1; final Field field = fields[i]; fields[i] = fields[idx]; fields[idx] = field; } } for (int i = 0; i < fields.length; i++ ) { Field field = fields[i]; if (!field.isAccessible()) { field.setAccessible(true); } FieldKey fieldKey = new FieldKey( field.getName(), field.getDeclaringClass(), i); - Map existent = (Map)keyedByFieldName.get(field.getName()); + Field existent = (Field)keyedByFieldName.get(field.getName()); if (existent == null // do overwrite statics - || ((((Field)((WeakReference)existent).get()).getModifiers() & Modifier.STATIC) != 0) + || ((existent.getModifiers() & Modifier.STATIC) != 0) // overwrite non-statics with non-statics only || (existent != null && ((field.getModifiers() & Modifier.STATIC) == 0))) { keyedByFieldName.put(field.getName(), field); } keyedByFieldKey.put(fieldKey, field); } final Map sortedFieldKeys = sorter.sort(type, keyedByFieldKey); keyedByFieldNameCache.put(cls, keyedByFieldName); keyedByFieldKeyCache.put(cls, sortedFieldKeys); lastKeyedByFieldName = keyedByFieldName; lastKeyedByFieldKey = sortedFieldKeys; } else { lastKeyedByFieldName = (Map)keyedByFieldNameCache.get(cls); lastKeyedByFieldKey = (Map)keyedByFieldKeyCache.get(cls); } } result = tupleKeyed ? lastKeyedByFieldKey : lastKeyedByFieldName; } else { result = (Map)(tupleKeyed ? keyedByFieldKeyCache.get(type) : keyedByFieldNameCache.get(type)); } } return result; } protected Object readResolve() { init(); return this; } }
false
true
private Map buildMap(final Class type, boolean tupleKeyed) { final Map result; Class cls = type; synchronized (this) { if (!keyedByFieldNameCache.containsKey(type)) { final List superClasses = new ArrayList(); while (!Object.class.equals(cls)) { superClasses.add(0, cls); cls = cls.getSuperclass(); } Map lastKeyedByFieldName = Collections.EMPTY_MAP; Map lastKeyedByFieldKey = Collections.EMPTY_MAP; for (final Iterator iter = superClasses.iterator(); iter.hasNext();) { cls = (Class)iter.next(); if (!keyedByFieldNameCache.containsKey(cls)) { final Map keyedByFieldName = new HashMap(lastKeyedByFieldName); final Map keyedByFieldKey = new OrderRetainingMap(lastKeyedByFieldKey); Field[] fields = cls.getDeclaredFields(); if (JVM.reverseFieldDefinition()) { for (int i = fields.length >> 1; i-- > 0;) { final int idx = fields.length - i - 1; final Field field = fields[i]; fields[i] = fields[idx]; fields[idx] = field; } } for (int i = 0; i < fields.length; i++ ) { Field field = fields[i]; if (!field.isAccessible()) { field.setAccessible(true); } FieldKey fieldKey = new FieldKey( field.getName(), field.getDeclaringClass(), i); Map existent = (Map)keyedByFieldName.get(field.getName()); if (existent == null // do overwrite statics || ((((Field)((WeakReference)existent).get()).getModifiers() & Modifier.STATIC) != 0) // overwrite non-statics with non-statics only || (existent != null && ((field.getModifiers() & Modifier.STATIC) == 0))) { keyedByFieldName.put(field.getName(), field); } keyedByFieldKey.put(fieldKey, field); } final Map sortedFieldKeys = sorter.sort(type, keyedByFieldKey); keyedByFieldNameCache.put(cls, keyedByFieldName); keyedByFieldKeyCache.put(cls, sortedFieldKeys); lastKeyedByFieldName = keyedByFieldName; lastKeyedByFieldKey = sortedFieldKeys; } else { lastKeyedByFieldName = (Map)keyedByFieldNameCache.get(cls); lastKeyedByFieldKey = (Map)keyedByFieldKeyCache.get(cls); } } result = tupleKeyed ? lastKeyedByFieldKey : lastKeyedByFieldName; } else { result = (Map)(tupleKeyed ? keyedByFieldKeyCache.get(type) : keyedByFieldNameCache.get(type)); } } return result; }
private Map buildMap(final Class type, boolean tupleKeyed) { final Map result; Class cls = type; synchronized (this) { if (!keyedByFieldNameCache.containsKey(type)) { final List superClasses = new ArrayList(); while (!Object.class.equals(cls)) { superClasses.add(0, cls); cls = cls.getSuperclass(); } Map lastKeyedByFieldName = Collections.EMPTY_MAP; Map lastKeyedByFieldKey = Collections.EMPTY_MAP; for (final Iterator iter = superClasses.iterator(); iter.hasNext();) { cls = (Class)iter.next(); if (!keyedByFieldNameCache.containsKey(cls)) { final Map keyedByFieldName = new HashMap(lastKeyedByFieldName); final Map keyedByFieldKey = new OrderRetainingMap(lastKeyedByFieldKey); Field[] fields = cls.getDeclaredFields(); if (JVM.reverseFieldDefinition()) { for (int i = fields.length >> 1; i-- > 0;) { final int idx = fields.length - i - 1; final Field field = fields[i]; fields[i] = fields[idx]; fields[idx] = field; } } for (int i = 0; i < fields.length; i++ ) { Field field = fields[i]; if (!field.isAccessible()) { field.setAccessible(true); } FieldKey fieldKey = new FieldKey( field.getName(), field.getDeclaringClass(), i); Field existent = (Field)keyedByFieldName.get(field.getName()); if (existent == null // do overwrite statics || ((existent.getModifiers() & Modifier.STATIC) != 0) // overwrite non-statics with non-statics only || (existent != null && ((field.getModifiers() & Modifier.STATIC) == 0))) { keyedByFieldName.put(field.getName(), field); } keyedByFieldKey.put(fieldKey, field); } final Map sortedFieldKeys = sorter.sort(type, keyedByFieldKey); keyedByFieldNameCache.put(cls, keyedByFieldName); keyedByFieldKeyCache.put(cls, sortedFieldKeys); lastKeyedByFieldName = keyedByFieldName; lastKeyedByFieldKey = sortedFieldKeys; } else { lastKeyedByFieldName = (Map)keyedByFieldNameCache.get(cls); lastKeyedByFieldKey = (Map)keyedByFieldKeyCache.get(cls); } } result = tupleKeyed ? lastKeyedByFieldKey : lastKeyedByFieldName; } else { result = (Map)(tupleKeyed ? keyedByFieldKeyCache.get(type) : keyedByFieldNameCache.get(type)); } } return result; }
diff --git a/src/test/java/org/apache/ws/security/common/SAMLElementCallbackHandler.java b/src/test/java/org/apache/ws/security/common/SAMLElementCallbackHandler.java index 3d8a2f5d2..f4721bdbd 100644 --- a/src/test/java/org/apache/ws/security/common/SAMLElementCallbackHandler.java +++ b/src/test/java/org/apache/ws/security/common/SAMLElementCallbackHandler.java @@ -1,81 +1,81 @@ /** * 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.ws.security.common; import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.ws.security.saml.ext.AssertionWrapper; import org.apache.ws.security.saml.ext.SAMLCallback; import org.apache.ws.security.saml.ext.SAMLParms; import org.apache.ws.security.saml.ext.builder.SAML1Constants; import org.w3c.dom.Element; /** * A Callback Handler implementation for a SAML 1.1 assertion. Rather than create a set of beans * that AssertionWrapper will use to create a SAML Assertion, it sets a DOM Element directly on * the SAMLCallback object. */ public class SAMLElementCallbackHandler extends AbstractSAMLCallbackHandler { public SAMLElementCallbackHandler() { subjectName = "uid=joe,ou=people,ou=saml-demo,o=example.com"; subjectQualifier = "www.example.com"; confirmationMethod = SAML1Constants.CONF_SENDER_VOUCHES; } public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof SAMLCallback) { SAMLCallback callback = (SAMLCallback) callbacks[i]; Element assertionElement; try { assertionElement = getSAMLAssertion(); } catch (Exception e) { - throw new IOException(e); + throw new IOException(e.getMessage()); } callback.setAssertionElement(assertionElement); } else { throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); } } } /** * Mock up a SAML Assertion by using another SAMLCallbackHandler * @throws Exception */ private Element getSAMLAssertion() throws Exception { SAMLParms parms = new SAMLParms(); SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setIssuer(issuer); parms.setCallbackHandler(callbackHandler); AssertionWrapper assertionWrapper = new AssertionWrapper(parms); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); return assertionWrapper.toDOM(factory.newDocumentBuilder().newDocument()); } }
true
true
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof SAMLCallback) { SAMLCallback callback = (SAMLCallback) callbacks[i]; Element assertionElement; try { assertionElement = getSAMLAssertion(); } catch (Exception e) { throw new IOException(e); } callback.setAssertionElement(assertionElement); } else { throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); } } }
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof SAMLCallback) { SAMLCallback callback = (SAMLCallback) callbacks[i]; Element assertionElement; try { assertionElement = getSAMLAssertion(); } catch (Exception e) { throw new IOException(e.getMessage()); } callback.setAssertionElement(assertionElement); } else { throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); } } }
diff --git a/PLWebStart/src/main/java/org/plweb/suite/webstart/PLWebEnvironment.java b/PLWebStart/src/main/java/org/plweb/suite/webstart/PLWebEnvironment.java index 8e8ccc7..9f13756 100644 --- a/PLWebStart/src/main/java/org/plweb/suite/webstart/PLWebEnvironment.java +++ b/PLWebStart/src/main/java/org/plweb/suite/webstart/PLWebEnvironment.java @@ -1,171 +1,171 @@ package org.plweb.suite.webstart; import java.io.File; import java.util.ArrayList; import java.util.List; public class PLWebEnvironment { private static PLWebEnvironment instance = null; public static PLWebEnvironment getInstance() { if (instance == null) { return instance = new PLWebEnvironment(); } else { return instance; } } public PLWebEnvironment() { - setDiskRoot(new File(System.getProperty("plweb.diskroot")).getPath()); - setUrlPackage(System.getProperty("plweb.urlpackage")); - setUrlPackageAsc(System.getProperty("plweb.urlpackage_asc")); - setUrlLesson(System.getProperty("plweb.urllesson")); - setLessonId(System.getProperty("plweb.lessonid")); - setLessonPath(System.getProperty("plweb.lessonpath")); - setLessonFile(System.getProperty("plweb.lessonfile")); - setJEditPath(System.getProperty("plweb.jeditpath")); - setPluginPath(System.getProperty("plweb.pluginpath")); - setAdImage(System.getProperty("plweb.adimage")); - setAdUrl(System.getProperty("plweb.adurl")); + setDiskRoot(new File(System.getProperty("javaws.plweb.diskroot")).getPath()); + setUrlPackage(System.getProperty("javaws.plweb.urlpackage")); + setUrlPackageAsc(System.getProperty("javaws.plweb.urlpackage_asc")); + setUrlLesson(System.getProperty("javaws.plweb.urllesson")); + setLessonId(System.getProperty("javaws.plweb.lessonid")); + setLessonPath(System.getProperty("javaws.plweb.lessonpath")); + setLessonFile(System.getProperty("javaws.plweb.lessonfile")); + setJEditPath(System.getProperty("javaws.plweb.jeditpath")); + setPluginPath(System.getProperty("javaws.plweb.pluginpath")); + setAdImage(System.getProperty("javaws.plweb.adimage")); + setAdUrl(System.getProperty("javaws.plweb.adurl")); List<String> plugins = new ArrayList<String>(); List<String> pluginsAsc = new ArrayList<String>(); for (Object okey : System.getProperties().keySet()) { if (okey instanceof String) { String key = (String) okey; - if (key.startsWith("plweb.plugins.")) { + if (key.startsWith("javaws.plweb.plugins.")) { plugins.add(System.getProperty(key)); pluginsAsc.add(System.getProperty(key.replace(".plugins.", ".plugins_asc."))); } } } this.plugins = new String[plugins.size()]; for (int i = 0; i < plugins.size(); i++) { this.plugins[i] = plugins.get(i); } this.pluginsAsc = new String[pluginsAsc.size()]; for (int i = 0; i < pluginsAsc.size(); i++) { this.pluginsAsc[i] = pluginsAsc.get(i); } } private String diskRoot; private String urlPackage; private String urlPackageAsc; private String urlLesson; private String lessonId; private String lessonPath; private String lessonFile; private String jEditPath; private String pluginPath; private String[] plugins; private String[] pluginsAsc; private String adImage; private String adUrl; public String getAdImage() { return adImage; } public void setAdImage(String adImage) { this.adImage = adImage; } public String getAdUrl() { return adUrl; } public void setAdUrl(String adUrl) { this.adUrl = adUrl; } public String getUrlPackageAsc() { return urlPackageAsc; } public void setUrlPackageAsc(String urlPackageAsc) { this.urlPackageAsc = urlPackageAsc; } public String[] getPluginsAsc() { return pluginsAsc; } public void setPluginsAsc(String[] pluginsAsc) { this.pluginsAsc = pluginsAsc; } public String getPluginPath() { return pluginPath; } public void setPluginPath(String pluginPath) { this.pluginPath = pluginPath; } public String[] getPlugins() { return plugins; } public void setPlugins(String[] plugins) { this.plugins = plugins; } public String getJEditPath() { return jEditPath; } public void setJEditPath(String editPath) { jEditPath = editPath; } public String getLessonFile() { return lessonFile; } public void setLessonFile(String lessonFile) { this.lessonFile = lessonFile; } public String getLessonPath() { return lessonPath; } public void setLessonPath(String lessonPath) { this.lessonPath = lessonPath; } public String getLessonId() { return lessonId; } public void setLessonId(String lessonId) { this.lessonId = lessonId; } public String getUrlLesson() { return urlLesson; } public void setUrlLesson(String urlLesson) { this.urlLesson = urlLesson; } public String getUrlPackage() { return urlPackage; } public void setUrlPackage(String urlPackage) { this.urlPackage = urlPackage; } public String getDiskRoot() { return diskRoot; } public void setDiskRoot(String diskRoot) { this.diskRoot = diskRoot; } }
false
true
public PLWebEnvironment() { setDiskRoot(new File(System.getProperty("plweb.diskroot")).getPath()); setUrlPackage(System.getProperty("plweb.urlpackage")); setUrlPackageAsc(System.getProperty("plweb.urlpackage_asc")); setUrlLesson(System.getProperty("plweb.urllesson")); setLessonId(System.getProperty("plweb.lessonid")); setLessonPath(System.getProperty("plweb.lessonpath")); setLessonFile(System.getProperty("plweb.lessonfile")); setJEditPath(System.getProperty("plweb.jeditpath")); setPluginPath(System.getProperty("plweb.pluginpath")); setAdImage(System.getProperty("plweb.adimage")); setAdUrl(System.getProperty("plweb.adurl")); List<String> plugins = new ArrayList<String>(); List<String> pluginsAsc = new ArrayList<String>(); for (Object okey : System.getProperties().keySet()) { if (okey instanceof String) { String key = (String) okey; if (key.startsWith("plweb.plugins.")) { plugins.add(System.getProperty(key)); pluginsAsc.add(System.getProperty(key.replace(".plugins.", ".plugins_asc."))); } } } this.plugins = new String[plugins.size()]; for (int i = 0; i < plugins.size(); i++) { this.plugins[i] = plugins.get(i); } this.pluginsAsc = new String[pluginsAsc.size()]; for (int i = 0; i < pluginsAsc.size(); i++) { this.pluginsAsc[i] = pluginsAsc.get(i); } }
public PLWebEnvironment() { setDiskRoot(new File(System.getProperty("javaws.plweb.diskroot")).getPath()); setUrlPackage(System.getProperty("javaws.plweb.urlpackage")); setUrlPackageAsc(System.getProperty("javaws.plweb.urlpackage_asc")); setUrlLesson(System.getProperty("javaws.plweb.urllesson")); setLessonId(System.getProperty("javaws.plweb.lessonid")); setLessonPath(System.getProperty("javaws.plweb.lessonpath")); setLessonFile(System.getProperty("javaws.plweb.lessonfile")); setJEditPath(System.getProperty("javaws.plweb.jeditpath")); setPluginPath(System.getProperty("javaws.plweb.pluginpath")); setAdImage(System.getProperty("javaws.plweb.adimage")); setAdUrl(System.getProperty("javaws.plweb.adurl")); List<String> plugins = new ArrayList<String>(); List<String> pluginsAsc = new ArrayList<String>(); for (Object okey : System.getProperties().keySet()) { if (okey instanceof String) { String key = (String) okey; if (key.startsWith("javaws.plweb.plugins.")) { plugins.add(System.getProperty(key)); pluginsAsc.add(System.getProperty(key.replace(".plugins.", ".plugins_asc."))); } } } this.plugins = new String[plugins.size()]; for (int i = 0; i < plugins.size(); i++) { this.plugins[i] = plugins.get(i); } this.pluginsAsc = new String[pluginsAsc.size()]; for (int i = 0; i < pluginsAsc.size(); i++) { this.pluginsAsc[i] = pluginsAsc.get(i); } }
diff --git a/gdx/src/com/badlogic/gdx/math/Polygon.java b/gdx/src/com/badlogic/gdx/math/Polygon.java index a366da147..8823cf060 100644 --- a/gdx/src/com/badlogic/gdx/math/Polygon.java +++ b/gdx/src/com/badlogic/gdx/math/Polygon.java @@ -1,209 +1,209 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.math; public class Polygon { private final float[] localVertices; private float[] worldVertices; private float x, y; private float originX, originY; private float rotation; private float scaleX = 1, scaleY = 1; private boolean dirty = true; private Rectangle bounds; public Polygon (float[] vertices) { if (vertices.length < 6) throw new IllegalArgumentException("polygons must contain at least 3 points."); this.localVertices = vertices; } /** Returns vertices without scaling or rotation and without being offset by the polygon position. */ public float[] getLocalVertices () { return localVertices; } /** Returns vertices scaled, rotated, and offset by the polygon position. */ public float[] getWorldVertices () { - if (!dirty) return localVertices; + if (!dirty) return worldVertices; dirty = false; final float[] localVertices = this.localVertices; if (worldVertices == null || worldVertices.length < localVertices.length) worldVertices = new float[localVertices.length]; final float[] worldVertices = this.worldVertices; final float positionX = x; final float positionY = y; final float originX = this.originX; final float originY = this.originY; final float scaleX = this.scaleX; final float scaleY = this.scaleY; final boolean scale = scaleX != 1 || scaleY != 1; final float rotation = this.rotation; final float cos = MathUtils.cosDeg(rotation); final float sin = MathUtils.sinDeg(rotation); for (int i = 0, n = localVertices.length; i < n; i += 2) { float x = localVertices[i] - originX; float y = localVertices[i + 1] - originY; // scale if needed if (scale) { x *= scaleX; y *= scaleY; } // rotate if needed if (rotation != 0) { float oldX = x; x = cos * x - sin * y; y = sin * oldX + cos * y; } worldVertices[i] = positionX + x + originX; worldVertices[i + 1] = positionY + y + originY; } return worldVertices; } public void setOrigin (float originX, float originY) { this.originX = originX; this.originY = originY; dirty = true; } public void setPosition (float x, float y) { this.x = x; this.y = y; dirty = true; } public void translate (float x, float y) { this.x += x; this.y += y; dirty = true; } public void setRotation (float degrees) { this.rotation = degrees; dirty = true; } public void rotate (float degrees) { rotation += degrees; dirty = true; } public void setScale (float scaleX, float scaleY) { this.scaleX = scaleX; this.scaleY = scaleY; dirty = true; } public void scale (float amount) { this.scaleX += amount; this.scaleY += amount; dirty = true; } public float area () { float area = 0; float[] vertices = getWorldVertices(); final int numFloats = vertices.length; int x1, y1, x2, y2; for (int i = 0; i < numFloats; i += 2) { x1 = i; y1 = i + 1; x2 = (i + 2) % numFloats; y2 = (i + 3) % numFloats; area += vertices[x1] * vertices[y2]; area -= vertices[x2] * vertices[y1]; } area *= 0.5f; return area; } public Rectangle getBoundingRectangle () { float[] vertices = getWorldVertices(); float minX = vertices[0]; float minY = vertices[1]; float maxX = vertices[0]; float maxY = vertices[1]; final int numFloats = vertices.length; for (int i = 2; i < numFloats; i += 2) { minX = minX > vertices[i] ? vertices[i] : minX; minY = minY > vertices[i + 1] ? vertices[i + 1] : minY; maxX = maxX < vertices[i] ? vertices[i] : maxX; maxY = maxY < vertices[i + 1] ? vertices[i + 1] : maxY; } if (bounds == null) bounds = new Rectangle(); bounds.x = minX; bounds.y = minY; bounds.width = maxX - minX; bounds.height = maxY - minY; return bounds; } public boolean contains (float x, float y) { final float[] vertices = getWorldVertices(); final int numFloats = vertices.length; int intersects = 0; for (int i = 0; i < numFloats; i += 2) { float x1 = vertices[i]; float y1 = vertices[i + 1]; float x2 = vertices[(i + 2) % numFloats]; float y2 = vertices[(i + 3) % numFloats]; if (((y1 <= y && y < y2) || (y2 <= y && y < y1)) && x < ((x2 - x1) / (y2 - y1) * (y - y1) + x1)) intersects++; } return (intersects & 1) == 1; } public float getX () { return x; } public float getY () { return y; } public float getOriginX () { return originX; } public float getOriginY () { return originY; } public float getRotation () { return rotation; } public float getScaleX () { return scaleX; } public float getScaleY () { return scaleY; } }
true
true
public float[] getWorldVertices () { if (!dirty) return localVertices; dirty = false; final float[] localVertices = this.localVertices; if (worldVertices == null || worldVertices.length < localVertices.length) worldVertices = new float[localVertices.length]; final float[] worldVertices = this.worldVertices; final float positionX = x; final float positionY = y; final float originX = this.originX; final float originY = this.originY; final float scaleX = this.scaleX; final float scaleY = this.scaleY; final boolean scale = scaleX != 1 || scaleY != 1; final float rotation = this.rotation; final float cos = MathUtils.cosDeg(rotation); final float sin = MathUtils.sinDeg(rotation); for (int i = 0, n = localVertices.length; i < n; i += 2) { float x = localVertices[i] - originX; float y = localVertices[i + 1] - originY; // scale if needed if (scale) { x *= scaleX; y *= scaleY; } // rotate if needed if (rotation != 0) { float oldX = x; x = cos * x - sin * y; y = sin * oldX + cos * y; } worldVertices[i] = positionX + x + originX; worldVertices[i + 1] = positionY + y + originY; } return worldVertices; }
public float[] getWorldVertices () { if (!dirty) return worldVertices; dirty = false; final float[] localVertices = this.localVertices; if (worldVertices == null || worldVertices.length < localVertices.length) worldVertices = new float[localVertices.length]; final float[] worldVertices = this.worldVertices; final float positionX = x; final float positionY = y; final float originX = this.originX; final float originY = this.originY; final float scaleX = this.scaleX; final float scaleY = this.scaleY; final boolean scale = scaleX != 1 || scaleY != 1; final float rotation = this.rotation; final float cos = MathUtils.cosDeg(rotation); final float sin = MathUtils.sinDeg(rotation); for (int i = 0, n = localVertices.length; i < n; i += 2) { float x = localVertices[i] - originX; float y = localVertices[i + 1] - originY; // scale if needed if (scale) { x *= scaleX; y *= scaleY; } // rotate if needed if (rotation != 0) { float oldX = x; x = cos * x - sin * y; y = sin * oldX + cos * y; } worldVertices[i] = positionX + x + originX; worldVertices[i + 1] = positionY + y + originY; } return worldVertices; }
diff --git a/whois-query/src/test/java/net/ripe/db/whois/query/query/QueryTest.java b/whois-query/src/test/java/net/ripe/db/whois/query/query/QueryTest.java index 7dd5d0517..6c09a12e6 100644 --- a/whois-query/src/test/java/net/ripe/db/whois/query/query/QueryTest.java +++ b/whois-query/src/test/java/net/ripe/db/whois/query/query/QueryTest.java @@ -1,964 +1,964 @@ package net.ripe.db.whois.query.query; import com.google.common.collect.Sets; import net.ripe.db.whois.common.rpsl.AttributeType; import net.ripe.db.whois.common.rpsl.ObjectType; import net.ripe.db.whois.query.domain.QueryCompletionInfo; import net.ripe.db.whois.query.domain.QueryException; import net.ripe.db.whois.query.domain.QueryMessages; import org.hamcrest.Matchers; import org.junit.Test; import java.util.Set; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class QueryTest { private Query subject; private Query parseWithNewline(String input) { // [EB]: userinput will always be newline terminated return Query.parse(input + "\n"); } private void parse(String input) { subject = parseWithNewline(input); } @Test public void empty() { try { parse(""); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.noSearchKeySpecified())); } } @Test public void query_with_searchValue() { parse("foo"); assertTrue(subject.isFiltered()); assertTrue(subject.isGrouping()); assertTrue(subject.isProxyValid()); assertTrue(subject.isReturningReferencedObjects()); assertThat(subject.getSearchValue(), is("foo")); assertThat(subject.queryLength(), is(3)); } @Test public void query_with_space() { parse("foo "); assertThat(subject.getSearchValue(), is("foo")); assertThat(subject.queryLength(), is(3)); } @Test public void query_ignores_C() { parse("-C test"); assertThat(subject.hasOptions(), is(true)); assertThat(subject.getSearchValue(), is("test")); } @Test public void deprecated_R() { try { parse("-R test"); } catch (QueryException e) { assertThat(e.getMessages(), hasSize(1)); assertThat(e.getMessages().iterator().next(), is(QueryMessages.malformedQuery())); } } @Test public void non_filtered() { parse("-B foo"); assertFalse(subject.isFiltered()); } @Test public void non_grouping() { parse("-G foo"); assertFalse(subject.isGrouping()); } @Test public void non_recursive() { parse("-r foo"); assertFalse(subject.isReturningReferencedObjects()); } @Test public void is_short_hand() { parse("-F foo"); assertTrue(subject.isShortHand()); } @Test public void short_hand_is_non_recursive() { parse("-F foo"); assertTrue(subject.isShortHand()); assertFalse(subject.isReturningReferencedObjects()); } @Test public void has_ip_flags() { final Set<QueryFlag> flags = Sets.newHashSet(QueryFlag.ABUSE_CONTACT, QueryFlag.REVERSE_DOMAIN); for (final Query.MatchOperation matchOperation : Query.MatchOperation.values()) { if (matchOperation.getQueryFlag() != null) { flags.add(matchOperation.getQueryFlag()); } } for (final QueryFlag queryFlag : flags) { for (final String flag : queryFlag.getFlags()) { parse((flag.length() == 1 ? "-" : "--") + flag + " 10.0.0.0"); assertThat("flag: " + flag, subject.hasIpFlags(), is(true)); } } } @Test public void match_operations_default_inetnum() { parse("-T inetnum 10.0.0.0"); assertNull(subject.matchOperation()); } @Test public void match_operations_default_inet6num() { parse("-T inet6num ::0/0"); assertNull(subject.matchOperation()); } @Test public void match_operations_no_default_for_maintainer() { parse("-T mntner foo"); assertNull(subject.matchOperation()); } @Test public void match_operations_empty() { parse("foo"); assertNull(subject.matchOperation()); } @Test public void recognize_flags_with_arguments() { String[] flagsWithArguments = {"t", "v", "q", "V"}; final StringBuilder queryBuilder = new StringBuilder(); for (String flag : flagsWithArguments) { queryBuilder.append("-").append(flag).append(" ").append(flag).append("-flag").append(" "); } queryBuilder.append("is wrong"); parse(queryBuilder.toString()); assertThat(subject.getSearchValue(), is("is wrong")); } @Test public void no_sources() { parse("test"); assertThat(subject.getSources(), hasSize(0)); } @Test public void source() { parse("-s RIPE foo"); assertThat(subject.getSources(), contains("RIPE")); } @Test public void sources() { parse("-s RIPE,TEST foo"); assertThat(subject.getSources(), contains("RIPE", "TEST")); } @Test public void missing_arguments_for_flags() { String[] flagsWithArguments = {"i", "s", "t", "v", "q", "V"}; for (String flag : flagsWithArguments) { try { parse("-" + flag); fail("Missing argument for " + flag + " should throw an exception"); } catch (QueryException e) { // OK } } } @Test public void single_type_invalid_searchkey() { try { parse("-T aut-num foo"); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getCompletionInfo(), Matchers.is(QueryCompletionInfo.PARAMETER_ERROR)); assertThat(e.getMessages(), contains(QueryMessages.invalidSearchKey())); } } @Test public void single_type() { parse("-T aut-num AS1"); assertTrue(subject.hasObjectTypeFilter(ObjectType.AUT_NUM)); } @Test public void multiple_types_casing() { parse("-T aut-num,iNet6nUM,iNETnUm foo"); assertTrue(subject.hasObjectTypeFilter(ObjectType.INETNUM)); assertTrue(subject.hasObjectTypeFilter(ObjectType.INET6NUM)); assertFalse(subject.hasObjectTypeFilter(ObjectType.AUT_NUM)); } @Test public void multiple_types_with_empty_element() { parse("-T aut-num,,iNETnUm foo"); assertTrue(subject.hasObjectTypeFilter(ObjectType.INETNUM)); assertFalse(subject.hasObjectTypeFilter(ObjectType.AUT_NUM)); parse("-T aut-num,,iNETnUm as112"); assertTrue(subject.hasObjectTypeFilter(ObjectType.INETNUM)); assertTrue(subject.hasObjectTypeFilter(ObjectType.AUT_NUM)); } @Test public void short_types_casing() { parse("-T in,rT,An foo"); assertTrue(subject.hasObjectTypeFilter(ObjectType.INETNUM)); assertFalse(subject.hasObjectTypeFilter(ObjectType.ROUTE)); assertFalse(subject.hasObjectTypeFilter(ObjectType.AUT_NUM)); } @Test public void non_existing_types() { try { parse("-T aUT-Num,IAmInvalid,iNETnUm"); fail("Non existing type should throw an exception"); } catch (QueryException e) { assertThat(e.getMessage(), containsString("ERROR:103")); } } @Test public void type_option_without_space() { parse("-Tinetnum dont_care"); assertTrue(subject.hasObjectTypeFilter(ObjectType.INETNUM)); } @Test public void type_option_with_extra_space() { parse("-T inetnum dont_care"); assertTrue(subject.hasObjectTypeFilter(ObjectType.INETNUM)); } @Test public void type_with_clustered_options() { parse("-rT inetnum dont_care"); assertFalse(subject.isReturningReferencedObjects()); assertTrue(subject.hasObjectTypeFilter(ObjectType.INETNUM)); } @Test public void type_with_clustered_options_and_no_space() { parse("-rTinetnum dont_care"); assertFalse(subject.isReturningReferencedObjects()); assertTrue(subject.hasObjectTypeFilter(ObjectType.INETNUM)); } @Test public void proxied_for() { parse("-VclientId,10.0.0.0 foo"); assertEquals("clientId,10.0.0.0", subject.getProxy()); } @Test(expected = QueryException.class) public void proxied_for_invalid() { parse("-VclientId,ipAddress"); } @Test public void one_element_proxy_has_no_proxy_ip() { parse("-Vone foo"); assertTrue(subject.isProxyValid()); assertFalse(subject.hasProxyWithIp()); assertThat(subject.getProxyIp(), nullValue()); } @Test public void proxy_with_ip() { parse("-Vone,10.0.0.1 foo"); assertTrue(subject.isProxyValid()); assertTrue(subject.hasProxyWithIp()); } @Test(expected = QueryException.class) public void proxy_with_invalid_ip() { parse("-Vone,two"); } @Test(expected = QueryException.class) public void proxy_with_more_than_two_elements() { parse("-Vone,two,10.1.1.1"); } @Test public void to_string_returns_input() { parse("-r -GBTinetnum dont_care"); assertEquals("-r -GBTinetnum dont_care", subject.toString()); } @SuppressWarnings({"EqualsBetweenInconvertibleTypes", "ObjectEqualsNull"}) @Test public void equals_hashcode() { parse("-Tperson Truus"); assertTrue(subject.equals(subject)); assertThat(subject.hashCode(), is(subject.hashCode())); assertFalse(subject.equals(null)); assertFalse(subject.equals(2L)); Query differentQuery = parseWithNewline("-Tperson joost"); assertFalse(subject.equals(differentQuery)); assertThat(subject.hashCode(), not(is(differentQuery.hashCode()))); Query sameQuery = parseWithNewline("-Tperson Truus"); assertTrue(subject.equals(sameQuery)); assertThat(subject.hashCode(), is(sameQuery.hashCode())); } @Test public void only_keep_alive_flag_specified() { parse("-k\r"); assertTrue(subject.hasKeepAlive()); assertThat(subject.getSearchValue(), is("")); } @Test public void only_keep_alive_flag_specified_longoption() { parse("--persistent-connection\r"); assertTrue(subject.hasKeepAlive()); assertThat(subject.getSearchValue(), is("")); } @Test public void keep_alive_recognised() { parse("-rBG -T inetnum --persistent-connection 192.168.200.0 - 192.168.200.255\r"); assertTrue(subject.hasKeepAlive()); assertThat(subject.getSearchValue(), is("192.168.200.0 - 192.168.200.255")); } @Test(expected = QueryException.class) public void invalidProxyShouldThrowException() { Query.parse("-Vone,two,three -Tperson DW-RIPE"); } @Test public void testNoInverse() { final Query query = Query.parse("foo"); assertThat(query.isInverse(), is(false)); } @Test public void testInverseSingleAttribute() { final Query query = Query.parse("-i mnt-by aardvark-mnt"); assertThat(query.isInverse(), is(true)); assertThat(query.getAttributeTypes(), containsInAnyOrder(AttributeType.MNT_BY)); assertThat(query.getSearchValue(), is("aardvark-mnt")); assertNull(query.matchOperation()); } @Test public void testInverseSingleAttributeWithTypeFilter() { final Query query = Query.parse("-i mnt-by aardvark-mnt -T inetnum"); assertThat(query.isInverse(), is(true)); assertThat(query.getAttributeTypes(), containsInAnyOrder(AttributeType.MNT_BY)); assertThat(query.getSearchValue(), is("aardvark-mnt")); assertNull(query.matchOperation()); } @Test public void testInverseSingleAttributeShort() { final Query query = Query.parse("-i mb aardvark-mnt"); assertThat(query.isInverse(), is(true)); assertThat(query.getAttributeTypes(), containsInAnyOrder(AttributeType.MNT_BY)); assertThat(query.getSearchValue(), is("aardvark-mnt")); } @Test public void testInverseInvalidAttribute() { try { Query.parse("-i some-invalid aardvark-mnt"); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getMessage(), is(QueryMessages.invalidAttributeType("some-invalid").toString())); } } @Test public void testInverseMultipleAttributes() { final Query query = Query.parse("-i mb,mz aardvark-mnt"); assertThat(query.isInverse(), is(true)); assertThat(query.getAttributeTypes(), containsInAnyOrder(AttributeType.MNT_REF, AttributeType.MNT_BY)); assertThat(query.getSearchValue(), is("aardvark-mnt")); } @Test public void testMultipleObjectTypes() { final Query query = Query.parse("-T inet6num,domain,inetnum searchkey"); assertThat(query.getSearchValue(), is("searchkey")); assertThat(query.getObjectTypes(), contains(ObjectType.INETNUM, ObjectType.INET6NUM, ObjectType.DOMAIN)); } @Test public void testMultipleSeparatedObjectTypes() { final Query query = Query.parse("-T inetnum -T inet6num,domain searchkey"); assertThat(query.getObjectTypes(), contains(ObjectType.INETNUM, ObjectType.INET6NUM, ObjectType.DOMAIN)); } @Test public void testMultipleSeparatedAttributeTypes() { final Query query = Query.parse("-i mnt-by -i mnt-ref,mnt-lower foo"); assertThat(query.getAttributeTypes(), containsInAnyOrder(AttributeType.MNT_BY, AttributeType.MNT_REF, AttributeType.MNT_LOWER)); } @Test public void illegal_range_ipv4_more_all() { illegalRange("-M 0/0"); } @Test public void illegal_range_ipv4_more() { illegalRange("-m 0/0"); } @Test public void illegal_range_ipv6_more_all() { illegalRange("-M ::0/0"); } @Test public void illegal_range_ipv6_more() { illegalRange("-m ::0/0"); } private void illegalRange(final String queryString) { try { Query.parse(queryString); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessage(), is(QueryMessages.illegalRange().toString())); } } @Test(expected = QueryException.class) public void multiple_proxies() { Query.parse("-V ripews,188.111.4.162 -V 85.25.132.61"); } @Test public void max_elements_exceeded() { try { Query.parse("a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a "); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getMessage(), is(QueryMessages.malformedQuery().toString())); } } @Test public void attributes_person() { final Query query = Query.parse("-i person name"); assertThat(query.getAttributeTypes(), contains(AttributeType.ADMIN_C, AttributeType.TECH_C, AttributeType.ZONE_C, AttributeType.AUTHOR, AttributeType.PING_HDL)); } @Test public void attributes_person_and_others() { final Query query = Query.parse("-i mb,person,ml name"); assertThat(query.getAttributeTypes(), contains(AttributeType.MNT_BY, AttributeType.ADMIN_C, AttributeType.TECH_C, AttributeType.ZONE_C, AttributeType.AUTHOR, AttributeType.PING_HDL, AttributeType.MNT_LOWER)); } @Test public void getAsBlockRange() { Query query = Query.parse("-r -T as-block AS1-AS2"); assertTrue(query.getAsBlockRangeOrNull().getBegin() == 1); assertTrue(query.getAsBlockRangeOrNull().getEnd() == 2); } @Test public void not_lookupBothDirections() { Query query = Query.parse("10.0.0.0"); assertFalse(query.isLookupInBothDirections()); } @Test public void getIpKeyOrNull_both_directions_forward() { Query query = Query.parse("-d 10.0.0.0"); assertTrue(query.isLookupInBothDirections()); assertThat(query.getIpKeyOrNull().toString(), is("10.0.0.0/32")); } @Test public void getIpKeyOrNull_both_directions_reverse_domain() { Query query = Query.parse("-d 10.in-addr.arpa"); assertTrue(query.isLookupInBothDirections()); assertThat(query.getIpKeyOrNull().toString(), is("10.0.0.0/8")); } @Test public void not_isReturningIrt() { Query query = Query.parse("10.0.0.0"); assertFalse(query.isReturningIrt()); } @Test public void isReturningIrt() { Query query = Query.parse("-c 10.0.0.0"); assertTrue(query.isReturningIrt()); } @Test public void hasSources() { Query query = Query.parse("-s RIPE,TEST 10.0.0.0"); assertTrue(query.hasSources()); assertThat(query.getSources(), contains("RIPE", "TEST")); } @Test public void not_hasSources() { Query query = Query.parse("10.0.0.0"); assertFalse(query.hasSources()); } @Test public void isPrimaryObjectsOnly() { Query query = Query.parse("-rG 10.0.0.0"); assertTrue(query.isPrimaryObjectsOnly()); } @Test public void isPrimaryObjectsOnly_grouping() { Query query = Query.parse("-r 10.0.0.0"); assertFalse(query.isPrimaryObjectsOnly()); } @Test public void isPrimaryObjectsOnly_relatedTo() { Query query = Query.parse("-G 10.0.0.0"); assertFalse(query.isPrimaryObjectsOnly()); } @Test public void isPrimaryObjectsOnly_irt() { Query query = Query.parse("-rGc 10.0.0.0"); assertFalse(query.isPrimaryObjectsOnly()); } @Test(expected = QueryException.class) public void system_info_invalid_option() { Query query = Query.parse("-q invalid"); query.getSystemInfoOption(); } @Test(expected = QueryException.class) public void system_info_with_multiple_arguments() { Query query = Query.parse("-q version -q invalid"); query.getSystemInfoOption(); } @Test(expected = QueryException.class) public void system_info_multiple_flags_no_arguments() { Query query = Query.parse("-q -q"); query.getSystemInfoOption(); } @Test public void system_info_version_flag() { Query query = Query.parse("-q version"); assertThat(query.isSystemInfo(), is(true)); assertThat(query.getSystemInfoOption(), is(Query.SystemInfoOption.VERSION)); } @Test public void system_info_types_flag() { Query query = Query.parse("-q types"); assertThat(query.isSystemInfo(), is(true)); assertThat(query.getSystemInfoOption(), is(Query.SystemInfoOption.TYPES)); } @Test public void system_info_types_flag_longoption() { Query query = Query.parse("--types"); assertThat(query.isSystemInfo(), is(true)); assertThat(query.getSystemInfoOption(), is(Query.SystemInfoOption.TYPES)); } @Test public void isAllSources() { Query query = Query.parse("-a foo"); assertThat(query.isAllSources(), is(true)); } @Test public void not_isAllSources() { Query query = Query.parse("foo"); assertThat(query.isAllSources(), is(false)); } @Test public void isBrief() { Query query = Query.parse("-b 10.0.0.0"); assertThat(query.isBriefAbuseContact(), is(true)); } @Test public void isBrief_forces_grouping_and_irt() { Query query = Query.parse("-b -C 10.0.0.0"); assertThat(query.isBriefAbuseContact(), is(true)); assertThat(query.isGrouping(), is(false)); assertThat(query.isReturningIrt(), is(true)); } @Test public void not_isBrief() { Query query = Query.parse("foo"); assertThat(query.isBriefAbuseContact(), is(false)); } @Test public void isKeysOnly() { Query query = Query.parse("-K 10.0.0.0"); assertThat(query.isKeysOnly(), is(true)); } @Test public void isKeysOnly_forces_non_grouping() { Query query = Query.parse("-K 10.0.0.0"); assertThat(query.isKeysOnly(), is(true)); assertThat(query.isGrouping(), is(false)); } @Test public void not_isKeysOnly() { Query query = Query.parse("foo"); assertThat(query.isKeysOnly(), is(false)); } @Test public void not_related_when_isKeysOnly() { Query query = Query.parse("-K 10.0.0.0"); assertThat(query.isReturningReferencedObjects(), is(false)); } @Test public void not_irt_when_isKeysOnline() { Query query = Query.parse("-c -K 10.0.0.0"); assertThat(query.isReturningIrt(), is(false)); } @Test public void hasOption() { Query query = Query.parse("-s RIPE -T inetnum 10.0.0.0"); assertThat(query.hasOption(QueryFlag.SOURCES), is(true)); assertThat(query.hasOption(QueryFlag.SELECT_TYPES), is(true)); assertThat(query.hasOption(QueryFlag.NO_REFERENCED), is(false)); } @Test public void validTemplateQuery() { Query query = Query.parse("-t person"); assertThat(query.hasOption(QueryFlag.TEMPLATE), is(true)); assertThat(query.isTemplate(), is(true)); assertThat(query.getTemplateOption(), is("person")); } @Test(expected = QueryException.class) public void templateQueryMultipleArguments() { Query query = Query.parse("-t person -t role"); query.getTemplateOption(); } @Test public void validVerboseTemplateQuery() { Query query = Query.parse("-v person"); assertThat(query.hasOption(QueryFlag.VERBOSE), is(true)); assertThat(query.isVerbose(), is(true)); assertThat(query.getVerboseOption(), is("person")); } @Test(expected = QueryException.class) public void verboseTemplateQueryMultipleArguments() { Query query = Query.parse("-v person -v role"); query.getVerboseOption(); } @Test public void systemInfoWithExtraFlagAndArgument() { Query query = Query.parse("-q version -t person"); assertThat(query.getSystemInfoOption(), is(Query.SystemInfoOption.VERSION)); assertThat(query.getTemplateOption(), is("person")); } @Test public void multiple_match_operations() { try { Query.parse("-m -x 10.0.0.0"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.duplicateIpFlagsPassed())); } } @Test public void match_operations_without_ipkey() { Query query = Query.parse("-m test"); assertThat(query.getWarnings(), hasItem(QueryMessages.uselessIpFlagPassed())); } @Test public void invalid_combination() { try { Query.parse("-b -F 10.0.0.0"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.invalidCombinationOfFlags("-b, --abuse-contact", "-F, --brief"))); } } @Test public void brief_without_ipkey() { try { Query.parse("-b test"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.malformedQuery())); } } @Test public void brief_not_showing_referenced_objects() { final Query query = Query.parse("-b 10.0.0.0"); assertThat(query.isReturningReferencedObjects(), is(false)); } @Test public void brief_not_grouping() { final Query query = Query.parse("-b 10.0.0.0"); assertThat(query.isGrouping(), is(false)); } @Test public void unsupportedQuery() { try { Query.parse("..."); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.invalidSearchKey())); } } @Test public void nonVersionQuery() { Query query = Query.parse("10.0.0.0"); assertThat(query.hasOption(QueryFlag.LIST_VERSIONS), is(false)); assertThat(query.isVersionList(), is(false)); assertThat(query.hasOption(QueryFlag.SHOW_VERSION), is(false)); assertThat(query.isObjectVersion(), is(false)); } @Test public void versionlistQuery() { Query query = Query.parse("--list-versions 10.0.0.0"); assertThat(query.hasOption(QueryFlag.LIST_VERSIONS), is(true)); assertThat(query.isVersionList(), is(true)); } @Test public void versionQuery() { Query query = Query.parse("--show-version 1 10.0.0.0"); assertThat(query.hasOption(QueryFlag.SHOW_VERSION), is(true)); assertThat(query.isObjectVersion(), is(true)); } @Test - public void allow_only_k_and_V_options_for_version_queries() { + public void allow_only_k_T_and_V_options_for_version_queries() { final String[] validQueries = { - "--show-version 1 AS12 -k", - "--show-version 1 AS12 -V fred", - "--show-version 1 AS12 -k -V fred", - "--list-versions AS12 -k -V fred", - "--list-versions AS12 -V fred", - "--list-versions AS12 -k", - "--diff-versions 1:2 AS12", - "--diff-versions 1:2 AS12 -k", - "--diff-versions 1:2 AS12 -V fred" + "--show-version 1 AS12 -k", + "--show-version 1 AS12 -V fred", + "--show-version 1 AS12 -k -V fred", + "--list-versions AS12 -k -V fred", + "--list-versions AS12 -V fred", + "--list-versions AS12 -k", + "--diff-versions 1:2 AS12", + "--diff-versions 1:2 AS12 -k", + "--diff-versions 1:2 AS12 -V fred", + "--show-version 1 AS12 -T aut-num", }; for (String query : validQueries) { Query.parse(query); } final String[] invalidQueries = { - "--show-version 1 AS12 -T aut-num", - "--show-version 1 AS12 -B", - "--list-versions AS12 -G", - "--list-versions AS12 -V fred --no-tag-info", - "--list-versions AS12 -k --show-version 1 AS12", - "--diff-versions 1:2 AS12 -k --show-version 1", - "--diff-versions 1:2 AS12 -B", - "--diff-versions 1:2 AS12 -V fred --no-tag-info" + "--show-version 1 AS12 -B", + "--list-versions AS12 -G", + "--list-versions AS12 -V fred --no-tag-info", + "--list-versions AS12 -k --show-version 1 AS12", + "--diff-versions 1:2 AS12 -k --show-version 1", + "--diff-versions 1:2 AS12 -B", + "--diff-versions 1:2 AS12 -V fred --no-tag-info" }; for (String query : invalidQueries) { try { Query.parse(query); fail(String.format("%s should not succeed", query)); } catch (final QueryException e) { assertThat(e.getMessage(), containsString("cannot be used together")); } } } @Test public void versionDiffQuery() { Query query = Query.parse("--diff-versions 1:2 10.0.0.0"); assertThat(query.hasOption(QueryFlag.DIFF_VERSIONS), is(true)); assertThat(query.isVersionDiff(), is(true)); } @Test public void filter_tag_include_no_query() { try { Query.parse("--filter-tag-include unref"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.noSearchKeySpecified())); } } @Test public void filter_tag_exclude_no_query() { try { Query.parse("--filter-tag-exclude unref"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.noSearchKeySpecified())); } } @Test public void filter_tag_include_unref() { final Query query = Query.parse("--filter-tag-include unref test"); assertThat(query.hasOption(QueryFlag.FILTER_TAG_INCLUDE), is(true)); } @Test public void filter_tag_exclude_unref() { final Query query = Query.parse("--filter-tag-exclude unref test"); assertThat(query.hasOption(QueryFlag.FILTER_TAG_EXCLUDE), is(true)); } @Test public void filter_tag_include_unref_different_casing() { final Query query = Query.parse("--filter-tag-include UnReF test"); assertThat(query.hasOption(QueryFlag.FILTER_TAG_INCLUDE), is(true)); } @Test public void filter_tag_exclude_unref_different_casing() { final Query query = Query.parse("--filter-tag-exclude UnReF test"); assertThat(query.hasOption(QueryFlag.FILTER_TAG_EXCLUDE), is(true)); } @Test public void show_tag_info() { final Query query = Query.parse("--show-tag-info TEST-MNT"); assertThat(query.hasOption(QueryFlag.SHOW_TAG_INFO), is(true)); } @Test public void no_tag_info() { final Query query = Query.parse("--no-tag-info TEST-MNT"); assertThat(query.hasOption(QueryFlag.NO_TAG_INFO), is(true)); } @Test public void no_tag_info_and_show_tag_info_in_the_same_query() { try { Query.parse("--no-tag-info --show-tag-info TEST-MNT"); fail(); } catch (QueryException e) { assertThat(e.getMessage(), containsString("The flags \"--show-tag-info\" and \"--no-tag-info\" cannot be used together.")); } } @Test public void grs_search_types_specified_none() { final Query query = Query.parse("--resource 10.0.0.0"); assertThat(query.getObjectTypes(), contains( ObjectType.INETNUM, ObjectType.ROUTE, ObjectType.DOMAIN)); } @Test public void grs_search_types_specified_single() { final Query query = Query.parse("--resource -Tinetnum 10.0.0.0"); assertThat(query.getObjectTypes(), contains(ObjectType.INETNUM)); } @Test public void inverse_query_should_not_filter_object_types() { final Query query = Query.parse("-i nic-hdl 10.0.0.1"); assertThat(query.getObjectTypes(), hasSize(21)); } @Test public void grs_search_types_specified_non_resource() { final Query query = Query.parse("--resource -Tinetnum,mntner 10.0.0.0"); assertThat(query.getObjectTypes(), contains(ObjectType.INETNUM)); } @Test public void grs_enables_all_sources() { final Query query = Query.parse("--resource 10.0.0.0"); assertThat(query.isAllSources(), is(false)); assertThat(query.isResource(), is(true)); } }
false
true
public void allow_only_k_and_V_options_for_version_queries() { final String[] validQueries = { "--show-version 1 AS12 -k", "--show-version 1 AS12 -V fred", "--show-version 1 AS12 -k -V fred", "--list-versions AS12 -k -V fred", "--list-versions AS12 -V fred", "--list-versions AS12 -k", "--diff-versions 1:2 AS12", "--diff-versions 1:2 AS12 -k", "--diff-versions 1:2 AS12 -V fred" }; for (String query : validQueries) { Query.parse(query); } final String[] invalidQueries = { "--show-version 1 AS12 -T aut-num", "--show-version 1 AS12 -B", "--list-versions AS12 -G", "--list-versions AS12 -V fred --no-tag-info", "--list-versions AS12 -k --show-version 1 AS12", "--diff-versions 1:2 AS12 -k --show-version 1", "--diff-versions 1:2 AS12 -B", "--diff-versions 1:2 AS12 -V fred --no-tag-info" }; for (String query : invalidQueries) { try { Query.parse(query); fail(String.format("%s should not succeed", query)); } catch (final QueryException e) { assertThat(e.getMessage(), containsString("cannot be used together")); } } }
public void allow_only_k_T_and_V_options_for_version_queries() { final String[] validQueries = { "--show-version 1 AS12 -k", "--show-version 1 AS12 -V fred", "--show-version 1 AS12 -k -V fred", "--list-versions AS12 -k -V fred", "--list-versions AS12 -V fred", "--list-versions AS12 -k", "--diff-versions 1:2 AS12", "--diff-versions 1:2 AS12 -k", "--diff-versions 1:2 AS12 -V fred", "--show-version 1 AS12 -T aut-num", }; for (String query : validQueries) { Query.parse(query); } final String[] invalidQueries = { "--show-version 1 AS12 -B", "--list-versions AS12 -G", "--list-versions AS12 -V fred --no-tag-info", "--list-versions AS12 -k --show-version 1 AS12", "--diff-versions 1:2 AS12 -k --show-version 1", "--diff-versions 1:2 AS12 -B", "--diff-versions 1:2 AS12 -V fred --no-tag-info" }; for (String query : invalidQueries) { try { Query.parse(query); fail(String.format("%s should not succeed", query)); } catch (final QueryException e) { assertThat(e.getMessage(), containsString("cannot be used together")); } } }
diff --git a/src/com/github/etsai/kfstatsxtslite/migrate/MigrateMain.java b/src/com/github/etsai/kfstatsxtslite/migrate/MigrateMain.java index e4b36d0..0417c85 100644 --- a/src/com/github/etsai/kfstatsxtslite/migrate/MigrateMain.java +++ b/src/com/github/etsai/kfstatsxtslite/migrate/MigrateMain.java @@ -1,101 +1,101 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.github.etsai.kfstatsxtslite.migrate; import com.github.etsai.utils.Time; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Calendar; /** * Main entry point for the migration from SQLite to MYSQL * @author etsai */ public class MigrateMain { /** * @param args the command line arguments */ public static void main(String[] args) throws ClassNotFoundException, SQLException { if (args.length != 4) { System.err.println("Usage: migrate [sqlite url] [mysql url] [mysql user name] [mysql password]"); System.exit(1); } System.out.println("Starting data migration: " + Calendar.getInstance().getTime()); Class.forName("org.sqlite.JDBC"); Connection src= DriverManager.getConnection(args[0]); Connection dst= DriverManager.getConnection(args[1], args[2], args[3]); long start= System.currentTimeMillis(); move(src.createStatement(), dst.createStatement()); long end= System.currentTimeMillis(); System.out.println(String.format("Done: %1$.2f seconds", (end - start)/(double)1000)); } static void move(Statement srcSt, Statement dstSt) throws SQLException { ResultSet rs; System.out.println("Copying deaths"); rs= srcSt.executeQuery("select * from deaths"); while(rs.next()) { - dstSt.executeUpdate(String.format("call update_deaths '%s', %d);", + dstSt.executeUpdate(String.format("call update_deaths('%s', %d);", rs.getString("name"), rs.getInt("count"))); } rs.close(); System.out.println("Copying player records"); rs= srcSt.executeQuery("select * from records"); while(rs.next()) { dstSt.executeUpdate(String.format("call update_record('%s', %d, %d, %d);", rs.getString("steamid"), rs.getInt("wins"), rs.getInt("losses"), rs.getInt("disconnects"))); } rs.close(); System.out.println("Copying aggregate stats"); rs= srcSt.executeQuery("select * from aggregate"); while(rs.next()) { dstSt.executeUpdate(String.format("call update_aggregate('%s', %d, '%s');", rs.getString("stat"), rs.getInt("value"), rs.getString("category"))); } rs.close(); System.out.println("Copying difficulties"); rs= srcSt.executeQuery("select * from difficulties"); while(rs.next()) { Time time= new Time(rs.getString("time")); dstSt.executeUpdate(String.format("call update_difficulty('%s', '%s', %d, %d, %d, %d);", rs.getString("name"), rs.getString("length"), rs.getInt("wins"), rs.getInt("losses"), rs.getInt("wave"), time.toSeconds())); } rs.close(); System.out.println("Copying levels"); rs= srcSt.executeQuery("select * from levels"); while(rs.next()) { Time time= new Time(rs.getString("time")); dstSt.executeUpdate(String.format("call update_level('%s', %d, %d, %d);", rs.getString("name"), rs.getInt("wins"), rs.getInt("losses"), time.toSeconds())); } rs.close(); System.out.println("Copying player stats"); rs= srcSt.executeQuery("select * from player"); while(rs.next()) { for(String statValue: rs.getString("stats").split(",")) { String[] split= statValue.split("="); dstSt.executeUpdate(String.format("call update_player('%s', '%s', %d, '%s');", rs.getString("steamid"), split[0], Integer.valueOf(split[1]), rs.getString("category"))); } } rs.close(); } }
true
true
static void move(Statement srcSt, Statement dstSt) throws SQLException { ResultSet rs; System.out.println("Copying deaths"); rs= srcSt.executeQuery("select * from deaths"); while(rs.next()) { dstSt.executeUpdate(String.format("call update_deaths '%s', %d);", rs.getString("name"), rs.getInt("count"))); } rs.close(); System.out.println("Copying player records"); rs= srcSt.executeQuery("select * from records"); while(rs.next()) { dstSt.executeUpdate(String.format("call update_record('%s', %d, %d, %d);", rs.getString("steamid"), rs.getInt("wins"), rs.getInt("losses"), rs.getInt("disconnects"))); } rs.close(); System.out.println("Copying aggregate stats"); rs= srcSt.executeQuery("select * from aggregate"); while(rs.next()) { dstSt.executeUpdate(String.format("call update_aggregate('%s', %d, '%s');", rs.getString("stat"), rs.getInt("value"), rs.getString("category"))); } rs.close(); System.out.println("Copying difficulties"); rs= srcSt.executeQuery("select * from difficulties"); while(rs.next()) { Time time= new Time(rs.getString("time")); dstSt.executeUpdate(String.format("call update_difficulty('%s', '%s', %d, %d, %d, %d);", rs.getString("name"), rs.getString("length"), rs.getInt("wins"), rs.getInt("losses"), rs.getInt("wave"), time.toSeconds())); } rs.close(); System.out.println("Copying levels"); rs= srcSt.executeQuery("select * from levels"); while(rs.next()) { Time time= new Time(rs.getString("time")); dstSt.executeUpdate(String.format("call update_level('%s', %d, %d, %d);", rs.getString("name"), rs.getInt("wins"), rs.getInt("losses"), time.toSeconds())); } rs.close(); System.out.println("Copying player stats"); rs= srcSt.executeQuery("select * from player"); while(rs.next()) { for(String statValue: rs.getString("stats").split(",")) { String[] split= statValue.split("="); dstSt.executeUpdate(String.format("call update_player('%s', '%s', %d, '%s');", rs.getString("steamid"), split[0], Integer.valueOf(split[1]), rs.getString("category"))); } } rs.close(); }
static void move(Statement srcSt, Statement dstSt) throws SQLException { ResultSet rs; System.out.println("Copying deaths"); rs= srcSt.executeQuery("select * from deaths"); while(rs.next()) { dstSt.executeUpdate(String.format("call update_deaths('%s', %d);", rs.getString("name"), rs.getInt("count"))); } rs.close(); System.out.println("Copying player records"); rs= srcSt.executeQuery("select * from records"); while(rs.next()) { dstSt.executeUpdate(String.format("call update_record('%s', %d, %d, %d);", rs.getString("steamid"), rs.getInt("wins"), rs.getInt("losses"), rs.getInt("disconnects"))); } rs.close(); System.out.println("Copying aggregate stats"); rs= srcSt.executeQuery("select * from aggregate"); while(rs.next()) { dstSt.executeUpdate(String.format("call update_aggregate('%s', %d, '%s');", rs.getString("stat"), rs.getInt("value"), rs.getString("category"))); } rs.close(); System.out.println("Copying difficulties"); rs= srcSt.executeQuery("select * from difficulties"); while(rs.next()) { Time time= new Time(rs.getString("time")); dstSt.executeUpdate(String.format("call update_difficulty('%s', '%s', %d, %d, %d, %d);", rs.getString("name"), rs.getString("length"), rs.getInt("wins"), rs.getInt("losses"), rs.getInt("wave"), time.toSeconds())); } rs.close(); System.out.println("Copying levels"); rs= srcSt.executeQuery("select * from levels"); while(rs.next()) { Time time= new Time(rs.getString("time")); dstSt.executeUpdate(String.format("call update_level('%s', %d, %d, %d);", rs.getString("name"), rs.getInt("wins"), rs.getInt("losses"), time.toSeconds())); } rs.close(); System.out.println("Copying player stats"); rs= srcSt.executeQuery("select * from player"); while(rs.next()) { for(String statValue: rs.getString("stats").split(",")) { String[] split= statValue.split("="); dstSt.executeUpdate(String.format("call update_player('%s', '%s', %d, '%s');", rs.getString("steamid"), split[0], Integer.valueOf(split[1]), rs.getString("category"))); } } rs.close(); }
diff --git a/org.emftext.runtime/src/org/emftext/runtime/util/MinimalModelHelper.java b/org.emftext.runtime/src/org/emftext/runtime/util/MinimalModelHelper.java index 130534da2..e885a7aa1 100644 --- a/org.emftext.runtime/src/org/emftext/runtime/util/MinimalModelHelper.java +++ b/org.emftext.runtime/src/org/emftext/runtime/util/MinimalModelHelper.java @@ -1,90 +1,97 @@ package org.emftext.runtime.util; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; /** * A helper class that is able to create minimal model instances for Ecore * models. * * TODO mseifert: add cross references where possible */ public class MinimalModelHelper { private final static EClassUtil eClassUtil = new EClassUtil(); public EObject getMinimalModel(EClass eClass, EClass[] allAvailableClasses) { EPackage ePackage = eClass.getEPackage(); if (ePackage == null) { return null; } EObject root = ePackage.getEFactoryInstance().create(eClass); List<EStructuralFeature> features = eClass.getEAllStructuralFeatures(); for (EStructuralFeature feature : features) { if (feature instanceof EReference) { EReference reference = (EReference) feature; if (reference.isContainment()) { // TODO mseifert: handle opposite containments properly // TODO @jjohannes: can you comment on this? EClassifier type = reference.getEType(); if (type instanceof EClass) { EClass typeClass = (EClass) type; if (typeClass.isAbstract()) { // find subclasses List<EClass> subClasses = findSubClasses(typeClass, allAvailableClasses); if (subClasses.size() == 0) { continue; } else { // pick the first subclass typeClass = subClasses.get(0); } } int lowerBound = reference.getLowerBound(); for (int i = 0; i < lowerBound; i++) { EObject subModel = getMinimalModel(typeClass, allAvailableClasses); if (subModel == null) { continue; } Object value = root.eGet(reference); if (value instanceof List) { List<EObject> list = (List<EObject>) value; list.add(subModel); } else { root.eSet(reference, subModel); } } } } } else if (feature instanceof EAttribute) { EAttribute attribute = (EAttribute) feature; if ("EString".equals(attribute.getEType().getName())) { - root.eSet(attribute, "some" + StringUtil.capitalize(attribute.getName())); + String initialValue = "some" + StringUtil.capitalize(attribute.getName()); + Object value = root.eGet(attribute); + if (value instanceof List) { + List<String> list = (List<String>) value; + list.add(initialValue); + } else { + root.eSet(attribute, initialValue); + } } } } return root; } private List<EClass> findSubClasses(EClass eClass, EClass[] allAvailableClasses) { ArrayList<EClass> result = new ArrayList<EClass>(); for (EClass next : allAvailableClasses) { if (eClassUtil.isSubClass(next, eClass) && !next.isAbstract() && !next.isInterface()) { result.add(next); } } return result; } }
true
true
public EObject getMinimalModel(EClass eClass, EClass[] allAvailableClasses) { EPackage ePackage = eClass.getEPackage(); if (ePackage == null) { return null; } EObject root = ePackage.getEFactoryInstance().create(eClass); List<EStructuralFeature> features = eClass.getEAllStructuralFeatures(); for (EStructuralFeature feature : features) { if (feature instanceof EReference) { EReference reference = (EReference) feature; if (reference.isContainment()) { // TODO mseifert: handle opposite containments properly // TODO @jjohannes: can you comment on this? EClassifier type = reference.getEType(); if (type instanceof EClass) { EClass typeClass = (EClass) type; if (typeClass.isAbstract()) { // find subclasses List<EClass> subClasses = findSubClasses(typeClass, allAvailableClasses); if (subClasses.size() == 0) { continue; } else { // pick the first subclass typeClass = subClasses.get(0); } } int lowerBound = reference.getLowerBound(); for (int i = 0; i < lowerBound; i++) { EObject subModel = getMinimalModel(typeClass, allAvailableClasses); if (subModel == null) { continue; } Object value = root.eGet(reference); if (value instanceof List) { List<EObject> list = (List<EObject>) value; list.add(subModel); } else { root.eSet(reference, subModel); } } } } } else if (feature instanceof EAttribute) { EAttribute attribute = (EAttribute) feature; if ("EString".equals(attribute.getEType().getName())) { root.eSet(attribute, "some" + StringUtil.capitalize(attribute.getName())); } } } return root; }
public EObject getMinimalModel(EClass eClass, EClass[] allAvailableClasses) { EPackage ePackage = eClass.getEPackage(); if (ePackage == null) { return null; } EObject root = ePackage.getEFactoryInstance().create(eClass); List<EStructuralFeature> features = eClass.getEAllStructuralFeatures(); for (EStructuralFeature feature : features) { if (feature instanceof EReference) { EReference reference = (EReference) feature; if (reference.isContainment()) { // TODO mseifert: handle opposite containments properly // TODO @jjohannes: can you comment on this? EClassifier type = reference.getEType(); if (type instanceof EClass) { EClass typeClass = (EClass) type; if (typeClass.isAbstract()) { // find subclasses List<EClass> subClasses = findSubClasses(typeClass, allAvailableClasses); if (subClasses.size() == 0) { continue; } else { // pick the first subclass typeClass = subClasses.get(0); } } int lowerBound = reference.getLowerBound(); for (int i = 0; i < lowerBound; i++) { EObject subModel = getMinimalModel(typeClass, allAvailableClasses); if (subModel == null) { continue; } Object value = root.eGet(reference); if (value instanceof List) { List<EObject> list = (List<EObject>) value; list.add(subModel); } else { root.eSet(reference, subModel); } } } } } else if (feature instanceof EAttribute) { EAttribute attribute = (EAttribute) feature; if ("EString".equals(attribute.getEType().getName())) { String initialValue = "some" + StringUtil.capitalize(attribute.getName()); Object value = root.eGet(attribute); if (value instanceof List) { List<String> list = (List<String>) value; list.add(initialValue); } else { root.eSet(attribute, initialValue); } } } } return root; }
diff --git a/builder/src/main/java/com/android/builder/AndroidBuilder.java b/builder/src/main/java/com/android/builder/AndroidBuilder.java index 35b4557..f53e361 100644 --- a/builder/src/main/java/com/android/builder/AndroidBuilder.java +++ b/builder/src/main/java/com/android/builder/AndroidBuilder.java @@ -1,863 +1,862 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.builder; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.annotations.VisibleForTesting; import com.android.builder.compiler.AidlProcessor; import com.android.builder.compiler.SourceGenerator; import com.android.builder.packaging.DuplicateFileException; import com.android.builder.packaging.JavaResourceProcessor; import com.android.builder.packaging.Packager; import com.android.builder.packaging.PackagerException; import com.android.builder.packaging.SealedPackageException; import com.android.builder.signing.DebugKeyHelper; import com.android.builder.signing.KeystoreHelper; import com.android.builder.signing.KeytoolException; import com.android.builder.signing.SigningInfo; import com.android.manifmerger.ManifestMerger; import com.android.manifmerger.MergerLog; import com.android.prefs.AndroidLocation.AndroidLocationException; import com.android.sdklib.IAndroidTarget; import com.android.sdklib.IAndroidTarget.IOptionalLibrary; import com.android.utils.ILogger; import com.google.common.collect.Lists; import com.google.common.io.Files; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * This is the main builder class. It is given all the data to process the build (such as * {@link ProductFlavor}s, {@link BuildType} and dependencies) and use them when doing specific * build steps. * * To use: * create a builder with {@link #AndroidBuilder(SdkParser, ILogger, boolean)}, * configure compile target with {@link #setTarget(String)} * configure build variant with {@link #setVariantConfig(VariantConfiguration)} * * then build steps can be done with * {@link #generateBuildConfig(String, java.util.List)} * {@link #processManifest(String)} * {@link #processResources(String, String, String, String, String, AaptOptions)} * {@link #convertBytecode(java.util.List, java.util.List, String, DexOptions)} * {@link #packageApk(String, String, String, String)} * * Java compilation is not handled but the builder provides the runtime classpath with * {@link #getRuntimeClasspath()}. */ public class AndroidBuilder { private final SdkParser mSdkParser; private final ILogger mLogger; private final CommandLineRunner mCmdLineRunner; private final boolean mVerboseExec; private IAndroidTarget mTarget; // config private VariantConfiguration mVariant; /** * Creates an AndroidBuilder * <p/> * This receives an {@link SdkParser} to provide the build with information about the SDK, as * well as an {@link ILogger} to display output. * <p/> * <var>verboseExec</var> is needed on top of the ILogger due to remote exec tools not being * able to output info and verbose messages separately. * * @param sdkParser * @param logger * @param verboseExec */ public AndroidBuilder( @NonNull SdkParser sdkParser, @NonNull ILogger logger, boolean verboseExec) { mSdkParser = checkNotNull(sdkParser); mLogger = checkNotNull(logger); mVerboseExec = verboseExec; mCmdLineRunner = new CommandLineRunner(mLogger); } @VisibleForTesting AndroidBuilder( @NonNull SdkParser sdkParser, @NonNull CommandLineRunner cmdLineRunner, @NonNull ILogger logger, boolean verboseExec) { mSdkParser = checkNotNull(sdkParser); mCmdLineRunner = checkNotNull(cmdLineRunner); mLogger = checkNotNull(logger); mVerboseExec = verboseExec; } /** * Sets the compilation target hash string. * * @param target the compilation target * * @see IAndroidTarget#hashString() */ public void setTarget(@NonNull String target) { checkNotNull(target, "target cannot be null."); mTarget = mSdkParser.resolveTarget(target, mLogger); if (mTarget == null) { throw new RuntimeException("Unknown target: " + target); } } /** * Sets the build variant configuration * * @param variant the configuration of the variant * */ public void setVariantConfig(@NonNull VariantConfiguration variant) { mVariant = checkNotNull(variant, "variant cannot be null."); } /** * Returns the runtime classpath to be used during compilation. */ public List<String> getRuntimeClasspath() { checkState(mTarget != null, "Target not set."); List<String> classpath = Lists.newArrayList(); classpath.add(mTarget.getPath(IAndroidTarget.ANDROID_JAR)); // add optional libraries if any IOptionalLibrary[] libs = mTarget.getOptionalLibraries(); if (libs != null) { for (IOptionalLibrary lib : libs) { classpath.add(lib.getJarPath()); } } // add annotations.jar if needed. if (mTarget.getVersion().getApiLevel() <= 15) { classpath.add(mSdkParser.getAnnotationsJar()); } return classpath; } /** * Generate the BuildConfig class for the project. * @param sourceOutputDir directory where to put this. This is the source folder, not the * package folder. * @param additionalLines additional lines to put in the class. These must be valid Java lines. * @throws IOException */ public void generateBuildConfig( @NonNull String sourceOutputDir, @Nullable List<String> additionalLines) throws IOException { checkState(mVariant != null, "No Variant Configuration has been set."); checkState(mTarget != null, "Target not set."); String packageName; if (mVariant.getType() == VariantConfiguration.Type.TEST) { packageName = mVariant.getPackageName(); } else { packageName = mVariant.getPackageFromManifest(); } BuildConfigGenerator generator = new BuildConfigGenerator( sourceOutputDir, packageName, mVariant.getBuildType().isDebuggable()); generator.generate(additionalLines); } /** * Pre-process resources. This crunches images and process 9-patches before they can * be packaged. * This is incremental. * * Call this directly if you don't care about checking whether the inputs have changed. * Otherwise, get the input first to check with {@link VariantConfiguration#getResourceInputs()} * and then call (or not), {@link #preprocessResources(String, java.util.List)}. * * @param resOutputDir where the processed resources are stored. * @throws IOException * @throws InterruptedException */ public void preprocessResources(@NonNull String resOutputDir) throws IOException, InterruptedException { checkState(mVariant != null, "No Variant Configuration has been set."); List<File> inputs = mVariant.getResourceInputs(); preprocessResources(resOutputDir, inputs); } /** * Pre-process resources. This crunches images and process 9-patches before they can * be packaged. * This is incremental. * * @param resOutputDir where the processed resources are stored. * @param inputs the input res folders * @throws IOException * @throws InterruptedException */ public void preprocessResources(@NonNull String resOutputDir, List<File> inputs) throws IOException, InterruptedException { checkState(mVariant != null, "No Variant Configuration has been set."); checkState(mTarget != null, "Target not set."); checkNotNull(resOutputDir, "resOutputDir cannot be null."); if (inputs == null || inputs.isEmpty()) { return; } // launch aapt: create the command line ArrayList<String> command = Lists.newArrayList(); @SuppressWarnings("deprecation") String aaptPath = mTarget.getPath(IAndroidTarget.AAPT); command.add(aaptPath); command.add("crunch"); if (mVerboseExec) { command.add("-v"); } boolean runCommand = false; for (File input : inputs) { if (input.isDirectory()) { command.add("-S"); command.add(input.getAbsolutePath()); runCommand = true; } } if (!runCommand) { return; } command.add("-C"); command.add(resOutputDir); mLogger.info("crunch command: %s", command.toString()); mCmdLineRunner.runCmdLine(command); } /** * Merges all the manifest from the BuildType and ProductFlavor(s) into a single manifest. * * TODO: figure out the order. Libraries first or buildtype/flavors first? * * @param outManifestLocation the output location for the merged manifest */ public void processManifest(@NonNull String outManifestLocation) { checkState(mVariant != null, "No Variant Configuration has been set."); checkState(mTarget != null, "Target not set."); checkNotNull(outManifestLocation, "outManifestLocation cannot be null."); if (mVariant.getType() == VariantConfiguration.Type.TEST) { VariantConfiguration testedConfig = mVariant.getTestedConfig(); if (testedConfig.getType() == VariantConfiguration.Type.LIBRARY) { try { // create the test manifest, merge the libraries in it File generatedTestManifest = File.createTempFile("manifestMerge", ".xml"); generateTestManifest(generatedTestManifest.getAbsolutePath()); mergeLibraryManifests( generatedTestManifest, mVariant.getDirectLibraries(), new File(outManifestLocation)); } catch (IOException e) { throw new RuntimeException(e); } } else { generateTestManifest(outManifestLocation); } } else { mergeManifest(mVariant, outManifestLocation); } } private void generateTestManifest(String outManifestLocation) { TestManifestGenerator generator = new TestManifestGenerator(outManifestLocation, mVariant.getPackageName(), mVariant.getTestedPackageName(), mVariant.getInstrumentationRunner()); try { generator.generate(); } catch (IOException e) { throw new RuntimeException(e); } } private void mergeManifest(VariantConfiguration config, String outManifestLocation) { try { // gather the app manifests: main + buildType and Flavors. File mainManifest = config.getDefaultSourceSet().getAndroidManifest(); List<File> subManifests = Lists.newArrayList(); File typeLocation = config.getBuildTypeSourceSet().getAndroidManifest(); if (typeLocation != null && typeLocation.isFile()) { subManifests.add(typeLocation); } for (SourceSet sourceSet : config.getFlavorSourceSets()) { File f = sourceSet.getAndroidManifest(); if (f != null && f.isFile()) { subManifests.add(f); } } // if no manifest to merge, just copy to location if (subManifests.isEmpty() && !config.hasLibraries()) { Files.copy(mainManifest, new File(outManifestLocation)); } else { File outManifest = new File(outManifestLocation); // first merge the app manifest. if (!subManifests.isEmpty()) { File mainManifestOut = outManifest; // if there is also libraries, put this in a temp file. if (config.hasLibraries()) { // TODO find better way of storing intermediary file? mainManifestOut = File.createTempFile("manifestMerge", ".xml"); mainManifestOut.deleteOnExit(); } ManifestMerger merger = new ManifestMerger(MergerLog.wrapSdkLog(mLogger), null); if (merger.process( mainManifestOut, mainManifest, subManifests.toArray(new File[subManifests.size()])) == false) { throw new RuntimeException(); } // now the main manifest is the newly merged one mainManifest = mainManifestOut; } if (config.hasLibraries()) { // recursively merge all manifests starting with the leaves and up toward the // root (the app) mergeLibraryManifests(mainManifest, config.getDirectLibraries(), new File(outManifestLocation)); } } } catch (IOException e) { throw new RuntimeException(e); } } /** * Merges library manifests into a main manifest. * @param mainManifest the main manifest * @param directLibraries the libraries to merge * @param outManifest the output file * @throws IOException */ private void mergeLibraryManifests( File mainManifest, Iterable<AndroidDependency> directLibraries, File outManifest) throws IOException { List<File> manifests = Lists.newArrayList(); for (AndroidDependency library : directLibraries) { List<AndroidDependency> subLibraries = library.getDependencies(); if (subLibraries == null || subLibraries.size() == 0) { manifests.add(library.getManifest()); } else { File mergeLibManifest = File.createTempFile("manifestMerge", ".xml"); mergeLibManifest.deleteOnExit(); mergeLibraryManifests( library.getManifest(), subLibraries, mergeLibManifest); manifests.add(mergeLibManifest); } } ManifestMerger merger = new ManifestMerger(MergerLog.wrapSdkLog(mLogger), null); if (merger.process( outManifest, mainManifest, manifests.toArray(new File[manifests.size()])) == false) { throw new RuntimeException(); } } /** * * Process the resources and generate R.java and/or the packaged resources. * * Call this directly if you don't care about checking whether the inputs have changed. * Otherwise, get the input first to check with {@link VariantConfiguration#getResourceInputs()} * and then call (or not), * {@link #processResources(String, String, java.util.List, String, String, String, AaptOptions)}. * @param manifestFile the location of the manifest file * @param preprocessResDir the pre-processed folder * @param sourceOutputDir optional source folder to generate R.java * @param resPackageOutput optional filepath for packaged resources * @param proguardOutput optional filepath for proguard file to generate * @param options the {@link AaptOptions} * @throws IOException * @throws InterruptedException */ public void processResources( @NonNull String manifestFile, @Nullable String preprocessResDir, @Nullable String sourceOutputDir, @Nullable String resPackageOutput, @Nullable String proguardOutput, @NonNull AaptOptions options) throws IOException, InterruptedException { List<File> inputs = mVariant.getResourceInputs(); processResources(manifestFile, preprocessResDir, inputs, sourceOutputDir, resPackageOutput, proguardOutput, options); } /** * Process the resources and generate R.java and/or the packaged resources. * * * @param manifestFile the location of the manifest file * @param preprocessResDir the pre-processed folder * @param resInputs the res folder inputs * @param sourceOutputDir optional source folder to generate R.java * @param resPackageOutput optional filepath for packaged resources * @param proguardOutput optional filepath for proguard file to generate * @param options the {@link AaptOptions} * @throws IOException * @throws InterruptedException */ public void processResources( @NonNull String manifestFile, @Nullable String preprocessResDir, @NonNull List<File> resInputs, @Nullable String sourceOutputDir, @Nullable String resPackageOutput, @Nullable String proguardOutput, @NonNull AaptOptions options) throws IOException, InterruptedException { checkState(mVariant != null, "No Variant Configuration has been set."); checkState(mTarget != null, "Target not set."); checkNotNull(manifestFile, "manifestFile cannot be null."); checkNotNull(resInputs, "resInputs cannot be null."); checkNotNull(options, "options cannot be null."); // if both output types are empty, then there's nothing to do and this is an error checkArgument(sourceOutputDir != null || resPackageOutput != null, "No output provided for aapt task"); // launch aapt: create the command line ArrayList<String> command = Lists.newArrayList(); @SuppressWarnings("deprecation") String aaptPath = mTarget.getPath(IAndroidTarget.AAPT); command.add(aaptPath); command.add("package"); if (mVerboseExec) { command.add("-v"); } command.add("-f"); command.add("--no-crunch"); // inputs command.add("-I"); command.add(mTarget.getPath(IAndroidTarget.ANDROID_JAR)); command.add("-M"); command.add(manifestFile); boolean useOverlay = false; if (preprocessResDir != null) { File preprocessResFile = new File(preprocessResDir); if (preprocessResFile.isDirectory()) { command.add("-S"); command.add(preprocessResDir); } } for (File resFolder : resInputs) { if (resFolder.isDirectory()) { command.add("-S"); command.add(resFolder.getAbsolutePath()); } } command.add("--auto-add-overlay"); // TODO support 2+ assets folders. // if (typeAssetsLocation != null) { // command.add("-A"); // command.add(typeAssetsLocation); // } // // if (flavorAssetsLocation != null) { // command.add("-A"); // command.add(flavorAssetsLocation); // } File mainAssetsLocation = mVariant.getDefaultSourceSet().getAndroidAssets(); if (mainAssetsLocation != null && mainAssetsLocation.isDirectory()) { command.add("-A"); command.add(mainAssetsLocation.getAbsolutePath()); } // outputs if (sourceOutputDir != null) { command.add("-m"); command.add("-J"); command.add(sourceOutputDir); } if (mVariant.getType() != VariantConfiguration.Type.LIBRARY && resPackageOutput != null) { command.add("-F"); command.add(resPackageOutput); if (proguardOutput != null) { command.add("-G"); command.add(proguardOutput); } } // options controlled by build variants if (mVariant.getBuildType().isDebuggable()) { command.add("--debug-mode"); } if (mVariant.getType() == VariantConfiguration.Type.DEFAULT) { String packageOverride = mVariant.getPackageOverride(); if (packageOverride != null) { command.add("--rename-manifest-package"); command.add(packageOverride); mLogger.verbose("Inserting package '%s' in AndroidManifest.xml", packageOverride); } boolean forceErrorOnReplace = false; ProductFlavor mergedFlavor = mVariant.getMergedFlavor(); int versionCode = mergedFlavor.getVersionCode(); if (versionCode != -1) { command.add("--version-code"); command.add(Integer.toString(versionCode)); mLogger.verbose("Inserting versionCode '%d' in AndroidManifest.xml", versionCode); forceErrorOnReplace = true; } String versionName = mergedFlavor.getVersionName(); if (versionName != null) { command.add("--version-name"); command.add(versionName); mLogger.verbose("Inserting versionName '%s' in AndroidManifest.xml", versionName); forceErrorOnReplace = true; } int minSdkVersion = mergedFlavor.getMinSdkVersion(); if (minSdkVersion != -1) { command.add("--min-sdk-version"); command.add(Integer.toString(minSdkVersion)); mLogger.verbose("Inserting minSdkVersion '%d' in AndroidManifest.xml", minSdkVersion); forceErrorOnReplace = true; } int targetSdkVersion = mergedFlavor.getTargetSdkVersion(); if (targetSdkVersion != -1) { command.add("--target-sdk-version"); command.add(Integer.toString(targetSdkVersion)); mLogger.verbose("Inserting targetSdkVersion '%d' in AndroidManifest.xml", targetSdkVersion); forceErrorOnReplace = true; } if (forceErrorOnReplace) { - // TODO: force aapt to fail if replace of versionCode/Name or min/targetSdkVersion fails - // Need to add the options to aapt first. + command.add("--error-on-failed-insert"); } } // library specific options if (mVariant.getType() == VariantConfiguration.Type.LIBRARY) { command.add("--non-constant-id"); } else { // only create the R class from library dependencies if this is not a library itself. String extraPackages = mVariant.getLibraryPackages(); if (extraPackages != null) { command.add("--extra-packages"); command.add(extraPackages); } } // AAPT options String ignoreAssets = options.getIgnoreAssets(); if (ignoreAssets != null) { command.add("---ignore-assets"); command.add(ignoreAssets); } List<String> noCompressList = options.getNoCompress(); if (noCompressList != null) { for (String noCompress : noCompressList) { command.add("-0"); command.add(noCompress); } } mLogger.info("aapt command: %s", command.toString()); mCmdLineRunner.runCmdLine(command); } /** * compiles all AIDL files. * * Call this directly if you don't care about checking whether the imports have changed. * Otherwise, get the imports first to check with * {@link com.android.builder.VariantConfiguration#getAidlImports()} * and then call (or not), {@link #compileAidl(java.util.List, java.io.File, java.util.List)}. * * @param sourceFolders * @param sourceOutputDir * @throws IOException * @throws InterruptedException */ public void compileAidl(@NonNull List<File> sourceFolders, @NonNull File sourceOutputDir) throws IOException, InterruptedException { checkState(mVariant != null, "No Variant Configuration has been set."); compileAidl(sourceFolders, sourceOutputDir, mVariant.getAidlImports()); } public void compileAidl(@NonNull List<File> sourceFolders, @NonNull File sourceOutputDir, @NonNull List<File> importFolders) throws IOException, InterruptedException { checkState(mVariant != null, "No Variant Configuration has been set."); checkState(mTarget != null, "Target not set."); checkNotNull(sourceFolders, "sourceFolders cannot be null."); checkNotNull(sourceOutputDir, "sourceOutputDir cannot be null."); checkNotNull(importFolders, "importFolders cannot be null."); SourceGenerator compiler = new SourceGenerator(mLogger); @SuppressWarnings("deprecation") String aidlPath = mTarget.getPath(IAndroidTarget.AIDL); AidlProcessor processor = new AidlProcessor( aidlPath, mTarget.getPath(IAndroidTarget.ANDROID_AIDL), importFolders, mCmdLineRunner); compiler.processFiles(processor, sourceFolders, sourceOutputDir); } public void convertBytecode( @NonNull List<String> classesLocation, @NonNull List<String> libraries, @NonNull String outDexFile, @NonNull DexOptions dexOptions) throws IOException, InterruptedException { checkState(mVariant != null, "No Variant Configuration has been set."); checkState(mTarget != null, "Target not set."); checkNotNull(classesLocation, "classesLocation cannot be null."); checkNotNull(libraries, "libraries cannot be null."); checkNotNull(outDexFile, "outDexFile cannot be null."); checkNotNull(dexOptions, "dexOptions cannot be null."); // launch dx: create the command line ArrayList<String> command = Lists.newArrayList(); @SuppressWarnings("deprecation") String dxPath = mTarget.getPath(IAndroidTarget.DX); command.add(dxPath); command.add("--dex"); if (mVerboseExec) { command.add("--verbose"); } command.add("--output"); command.add(outDexFile); // TODO: handle dependencies // TODO: handle dex options mLogger.verbose("Dex class inputs: " + classesLocation); command.addAll(classesLocation); mLogger.verbose("Dex library inputs: " + libraries); command.addAll(libraries); mCmdLineRunner.runCmdLine(command); } /** * Packages the apk. * @param androidResPkgLocation * @param classesDexLocation * @param jniLibsLocation * @param outApkLocation */ public void packageApk( @NonNull String androidResPkgLocation, @NonNull String classesDexLocation, @Nullable String jniLibsLocation, @NonNull String outApkLocation) throws DuplicateFileException { checkState(mVariant != null, "No Variant Configuration has been set."); checkState(mTarget != null, "Target not set."); checkNotNull(androidResPkgLocation, "androidResPkgLocation cannot be null."); checkNotNull(classesDexLocation, "classesDexLocation cannot be null."); checkNotNull(outApkLocation, "outApkLocation cannot be null."); BuildType buildType = mVariant.getBuildType(); SigningInfo signingInfo = null; try { if (buildType.isDebugSigned()) { String storeLocation = DebugKeyHelper.defaultDebugKeyStoreLocation(); File storeFile = new File(storeLocation); if (storeFile.isDirectory()) { throw new RuntimeException( String.format("A folder is in the way of the debug keystore: %s", storeLocation)); } else if (storeFile.exists() == false) { if (DebugKeyHelper.createNewStore( storeLocation, null /*storeType*/, mLogger) == false) { throw new RuntimeException(); } } // load the key signingInfo = DebugKeyHelper.getDebugKey(storeLocation, null /*storeStype*/); } else if (mVariant.getMergedFlavor().isSigningReady()) { ProductFlavor flavor = mVariant.getMergedFlavor(); signingInfo = KeystoreHelper.getSigningInfo( flavor.getSigningStoreLocation(), flavor.getSigningStorePassword(), null, /*storeStype*/ flavor.getSigningKeyAlias(), flavor.getSigningKeyPassword()); } } catch (AndroidLocationException e) { throw new RuntimeException(e); } catch (KeytoolException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { // this shouldn't happen as we have checked ahead of calling getDebugKey. throw new RuntimeException(e); } try { Packager packager = new Packager( outApkLocation, androidResPkgLocation, classesDexLocation, signingInfo, mLogger); packager.setDebugJniMode(buildType.isDebugJniBuild()); // figure out conflicts! JavaResourceProcessor resProcessor = new JavaResourceProcessor(packager); if (mVariant.getBuildTypeSourceSet() != null) { Set<File> buildTypeJavaResLocations = mVariant.getBuildTypeSourceSet().getJavaResources(); for (File buildTypeJavaResLocation : buildTypeJavaResLocations) { if (buildTypeJavaResLocation != null && buildTypeJavaResLocation.isDirectory()) { resProcessor.addSourceFolder(buildTypeJavaResLocation.getAbsolutePath()); } } } for (SourceSet sourceSet : mVariant.getFlavorSourceSets()) { Set<File> flavorJavaResLocations = sourceSet.getJavaResources(); for (File flavorJavaResLocation : flavorJavaResLocations) { if (flavorJavaResLocation != null && flavorJavaResLocation.isDirectory()) { resProcessor.addSourceFolder(flavorJavaResLocation.getAbsolutePath()); } } } Set<File> mainJavaResLocations = mVariant.getDefaultSourceSet().getJavaResources(); for (File mainJavaResLocation : mainJavaResLocations) { if (mainJavaResLocation != null && mainJavaResLocation.isDirectory()) { resProcessor.addSourceFolder(mainJavaResLocation.getAbsolutePath()); } } // add the resources from the jar files. List<JarDependency> jars = mVariant.getJars(); if (jars != null) { for (JarDependency jar : jars) { packager.addResourcesFromJar(new File(jar.getLocation())); } } // add the resources from the libs jar files List<AndroidDependency> libs = mVariant.getDirectLibraries(); addLibJavaResourcesToPackager(packager, libs); // also add resources from library projects and jars if (jniLibsLocation != null) { packager.addNativeLibraries(jniLibsLocation); } packager.sealApk(); } catch (PackagerException e) { throw new RuntimeException(e); } catch (SealedPackageException e) { throw new RuntimeException(e); } } private void addLibJavaResourcesToPackager(Packager packager, List<AndroidDependency> libs) throws PackagerException, SealedPackageException, DuplicateFileException { if (libs != null) { for (AndroidDependency lib : libs) { packager.addResourcesFromJar(lib.getJarFile()); // recursively add the dependencies of this library. addLibJavaResourcesToPackager(packager, lib.getDependencies()); } } } }
true
true
public void processResources( @NonNull String manifestFile, @Nullable String preprocessResDir, @NonNull List<File> resInputs, @Nullable String sourceOutputDir, @Nullable String resPackageOutput, @Nullable String proguardOutput, @NonNull AaptOptions options) throws IOException, InterruptedException { checkState(mVariant != null, "No Variant Configuration has been set."); checkState(mTarget != null, "Target not set."); checkNotNull(manifestFile, "manifestFile cannot be null."); checkNotNull(resInputs, "resInputs cannot be null."); checkNotNull(options, "options cannot be null."); // if both output types are empty, then there's nothing to do and this is an error checkArgument(sourceOutputDir != null || resPackageOutput != null, "No output provided for aapt task"); // launch aapt: create the command line ArrayList<String> command = Lists.newArrayList(); @SuppressWarnings("deprecation") String aaptPath = mTarget.getPath(IAndroidTarget.AAPT); command.add(aaptPath); command.add("package"); if (mVerboseExec) { command.add("-v"); } command.add("-f"); command.add("--no-crunch"); // inputs command.add("-I"); command.add(mTarget.getPath(IAndroidTarget.ANDROID_JAR)); command.add("-M"); command.add(manifestFile); boolean useOverlay = false; if (preprocessResDir != null) { File preprocessResFile = new File(preprocessResDir); if (preprocessResFile.isDirectory()) { command.add("-S"); command.add(preprocessResDir); } } for (File resFolder : resInputs) { if (resFolder.isDirectory()) { command.add("-S"); command.add(resFolder.getAbsolutePath()); } } command.add("--auto-add-overlay"); // TODO support 2+ assets folders. // if (typeAssetsLocation != null) { // command.add("-A"); // command.add(typeAssetsLocation); // } // // if (flavorAssetsLocation != null) { // command.add("-A"); // command.add(flavorAssetsLocation); // } File mainAssetsLocation = mVariant.getDefaultSourceSet().getAndroidAssets(); if (mainAssetsLocation != null && mainAssetsLocation.isDirectory()) { command.add("-A"); command.add(mainAssetsLocation.getAbsolutePath()); } // outputs if (sourceOutputDir != null) { command.add("-m"); command.add("-J"); command.add(sourceOutputDir); } if (mVariant.getType() != VariantConfiguration.Type.LIBRARY && resPackageOutput != null) { command.add("-F"); command.add(resPackageOutput); if (proguardOutput != null) { command.add("-G"); command.add(proguardOutput); } } // options controlled by build variants if (mVariant.getBuildType().isDebuggable()) { command.add("--debug-mode"); } if (mVariant.getType() == VariantConfiguration.Type.DEFAULT) { String packageOverride = mVariant.getPackageOverride(); if (packageOverride != null) { command.add("--rename-manifest-package"); command.add(packageOverride); mLogger.verbose("Inserting package '%s' in AndroidManifest.xml", packageOverride); } boolean forceErrorOnReplace = false; ProductFlavor mergedFlavor = mVariant.getMergedFlavor(); int versionCode = mergedFlavor.getVersionCode(); if (versionCode != -1) { command.add("--version-code"); command.add(Integer.toString(versionCode)); mLogger.verbose("Inserting versionCode '%d' in AndroidManifest.xml", versionCode); forceErrorOnReplace = true; } String versionName = mergedFlavor.getVersionName(); if (versionName != null) { command.add("--version-name"); command.add(versionName); mLogger.verbose("Inserting versionName '%s' in AndroidManifest.xml", versionName); forceErrorOnReplace = true; } int minSdkVersion = mergedFlavor.getMinSdkVersion(); if (minSdkVersion != -1) { command.add("--min-sdk-version"); command.add(Integer.toString(minSdkVersion)); mLogger.verbose("Inserting minSdkVersion '%d' in AndroidManifest.xml", minSdkVersion); forceErrorOnReplace = true; } int targetSdkVersion = mergedFlavor.getTargetSdkVersion(); if (targetSdkVersion != -1) { command.add("--target-sdk-version"); command.add(Integer.toString(targetSdkVersion)); mLogger.verbose("Inserting targetSdkVersion '%d' in AndroidManifest.xml", targetSdkVersion); forceErrorOnReplace = true; } if (forceErrorOnReplace) { // TODO: force aapt to fail if replace of versionCode/Name or min/targetSdkVersion fails // Need to add the options to aapt first. } } // library specific options if (mVariant.getType() == VariantConfiguration.Type.LIBRARY) { command.add("--non-constant-id"); } else { // only create the R class from library dependencies if this is not a library itself. String extraPackages = mVariant.getLibraryPackages(); if (extraPackages != null) { command.add("--extra-packages"); command.add(extraPackages); } } // AAPT options String ignoreAssets = options.getIgnoreAssets(); if (ignoreAssets != null) { command.add("---ignore-assets"); command.add(ignoreAssets); } List<String> noCompressList = options.getNoCompress(); if (noCompressList != null) { for (String noCompress : noCompressList) { command.add("-0"); command.add(noCompress); } } mLogger.info("aapt command: %s", command.toString()); mCmdLineRunner.runCmdLine(command); }
public void processResources( @NonNull String manifestFile, @Nullable String preprocessResDir, @NonNull List<File> resInputs, @Nullable String sourceOutputDir, @Nullable String resPackageOutput, @Nullable String proguardOutput, @NonNull AaptOptions options) throws IOException, InterruptedException { checkState(mVariant != null, "No Variant Configuration has been set."); checkState(mTarget != null, "Target not set."); checkNotNull(manifestFile, "manifestFile cannot be null."); checkNotNull(resInputs, "resInputs cannot be null."); checkNotNull(options, "options cannot be null."); // if both output types are empty, then there's nothing to do and this is an error checkArgument(sourceOutputDir != null || resPackageOutput != null, "No output provided for aapt task"); // launch aapt: create the command line ArrayList<String> command = Lists.newArrayList(); @SuppressWarnings("deprecation") String aaptPath = mTarget.getPath(IAndroidTarget.AAPT); command.add(aaptPath); command.add("package"); if (mVerboseExec) { command.add("-v"); } command.add("-f"); command.add("--no-crunch"); // inputs command.add("-I"); command.add(mTarget.getPath(IAndroidTarget.ANDROID_JAR)); command.add("-M"); command.add(manifestFile); boolean useOverlay = false; if (preprocessResDir != null) { File preprocessResFile = new File(preprocessResDir); if (preprocessResFile.isDirectory()) { command.add("-S"); command.add(preprocessResDir); } } for (File resFolder : resInputs) { if (resFolder.isDirectory()) { command.add("-S"); command.add(resFolder.getAbsolutePath()); } } command.add("--auto-add-overlay"); // TODO support 2+ assets folders. // if (typeAssetsLocation != null) { // command.add("-A"); // command.add(typeAssetsLocation); // } // // if (flavorAssetsLocation != null) { // command.add("-A"); // command.add(flavorAssetsLocation); // } File mainAssetsLocation = mVariant.getDefaultSourceSet().getAndroidAssets(); if (mainAssetsLocation != null && mainAssetsLocation.isDirectory()) { command.add("-A"); command.add(mainAssetsLocation.getAbsolutePath()); } // outputs if (sourceOutputDir != null) { command.add("-m"); command.add("-J"); command.add(sourceOutputDir); } if (mVariant.getType() != VariantConfiguration.Type.LIBRARY && resPackageOutput != null) { command.add("-F"); command.add(resPackageOutput); if (proguardOutput != null) { command.add("-G"); command.add(proguardOutput); } } // options controlled by build variants if (mVariant.getBuildType().isDebuggable()) { command.add("--debug-mode"); } if (mVariant.getType() == VariantConfiguration.Type.DEFAULT) { String packageOverride = mVariant.getPackageOverride(); if (packageOverride != null) { command.add("--rename-manifest-package"); command.add(packageOverride); mLogger.verbose("Inserting package '%s' in AndroidManifest.xml", packageOverride); } boolean forceErrorOnReplace = false; ProductFlavor mergedFlavor = mVariant.getMergedFlavor(); int versionCode = mergedFlavor.getVersionCode(); if (versionCode != -1) { command.add("--version-code"); command.add(Integer.toString(versionCode)); mLogger.verbose("Inserting versionCode '%d' in AndroidManifest.xml", versionCode); forceErrorOnReplace = true; } String versionName = mergedFlavor.getVersionName(); if (versionName != null) { command.add("--version-name"); command.add(versionName); mLogger.verbose("Inserting versionName '%s' in AndroidManifest.xml", versionName); forceErrorOnReplace = true; } int minSdkVersion = mergedFlavor.getMinSdkVersion(); if (minSdkVersion != -1) { command.add("--min-sdk-version"); command.add(Integer.toString(minSdkVersion)); mLogger.verbose("Inserting minSdkVersion '%d' in AndroidManifest.xml", minSdkVersion); forceErrorOnReplace = true; } int targetSdkVersion = mergedFlavor.getTargetSdkVersion(); if (targetSdkVersion != -1) { command.add("--target-sdk-version"); command.add(Integer.toString(targetSdkVersion)); mLogger.verbose("Inserting targetSdkVersion '%d' in AndroidManifest.xml", targetSdkVersion); forceErrorOnReplace = true; } if (forceErrorOnReplace) { command.add("--error-on-failed-insert"); } } // library specific options if (mVariant.getType() == VariantConfiguration.Type.LIBRARY) { command.add("--non-constant-id"); } else { // only create the R class from library dependencies if this is not a library itself. String extraPackages = mVariant.getLibraryPackages(); if (extraPackages != null) { command.add("--extra-packages"); command.add(extraPackages); } } // AAPT options String ignoreAssets = options.getIgnoreAssets(); if (ignoreAssets != null) { command.add("---ignore-assets"); command.add(ignoreAssets); } List<String> noCompressList = options.getNoCompress(); if (noCompressList != null) { for (String noCompress : noCompressList) { command.add("-0"); command.add(noCompress); } } mLogger.info("aapt command: %s", command.toString()); mCmdLineRunner.runCmdLine(command); }
diff --git a/src/wms/src/main/java/org/geoserver/wms/GetMapRequest.java b/src/wms/src/main/java/org/geoserver/wms/GetMapRequest.java index 84226e3367..956cc9a298 100644 --- a/src/wms/src/main/java/org/geoserver/wms/GetMapRequest.java +++ b/src/wms/src/main/java/org/geoserver/wms/GetMapRequest.java @@ -1,787 +1,787 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.geoserver.wms; import java.awt.Color; import java.awt.geom.Point2D; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.geoserver.ows.util.CaseInsensitiveMap; import org.geotools.image.palette.InverseColorMapOp; import org.geotools.styling.Style; import org.opengis.filter.Filter; import org.opengis.referencing.crs.CoordinateReferenceSystem; import com.vividsolutions.jts.geom.Envelope; /** * Represents a WMS GetMap request. as a extension to the WMS spec 1.1. * * @author Gabriel Roldan * @author Simone Giannecchini * @version $Id$ */ public class GetMapRequest extends WMSRequest { static final Color DEFAULT_BG = Color.white; public static final String SE_XML = "SE_XML"; /** set of mandatory request's parameters */ private MandatoryParameters mandatoryParams = new MandatoryParameters(); /** set of optionals request's parameters */ private OptionalParameters optionalParams = new OptionalParameters(); /** format options */ private Map<String, Object> formatOptions = new CaseInsensitiveMap(new HashMap()); /** SLD replacement */ private Map /* <String,Object> */env = new HashMap(); /** sql view parameters */ private Map<String, String> viewParams = new HashMap<String, String>(); private Map<String, String> httpRequestHeaders; public GetMapRequest() { super("GetMap"); } public Envelope getBbox() { return this.mandatoryParams.bbox; } public java.awt.Color getBgColor() { return this.optionalParams.bgColor; } /** * DJB: spec says SRS is *required*, so if they dont specify one, we should throw an error * instead we use "NONE" - which is no-projection. Previous behavior was to the WSG84 lat/long * (4326) * * @return request CRS, or <code>null</code> if not set. TODO: make CRS manditory as for spec * conformance */ public CoordinateReferenceSystem getCrs() { return this.optionalParams.crs; } public String getSRS() { return this.optionalParams.srs; } public String getExceptions() { return this.optionalParams.exceptions; } public String getFormat() { return this.mandatoryParams.format; } /** * Map of String,Object which contains kvp's which are specific to a particular output format. */ public Map getFormatOptions() { return formatOptions == null ? Collections.EMPTY_MAP : formatOptions; } /** * Map of strings that make up the SLD enviroment for variable substitution * * @return */ public Map getEnv() { return env; } /** * Map of strings that contain the parameter values for SQL views * * @return */ public Map<String, String> getViewParams() { return viewParams; } public int getHeight() { return this.mandatoryParams.height; } /** * @return the non null list of layers, may be empty */ public List<MapLayerInfo> getLayers() { List<MapLayerInfo> layers = mandatoryParams.layers; return layers; } /** * Gets a list of the styles to be returned by the server. * * @return A list of {@link Style} */ public List<Style> getStyles() { return this.mandatoryParams.styles; } /** * Gets the url specified by the "SLD" parameter. */ public URL getSld() { return this.optionalParams.sld; } /** * Gets the string specified the "SLD_BODY" parameter. */ public String getSldBody() { return this.optionalParams.sldBody; } /** * Gets the string specified by the "SLD_VERSION" parameter. */ public String getSldVersion() { return this.optionalParams.sldVersion; } /** * Gets the value of the "VALIDATESCHEMA" parameter which controls wether the value of the "SLD * paramter is schema validated. */ public Boolean getValidateSchema() { return this.optionalParams.validateSLD; } /** * Gets a list of the the filters that will be applied to each layer before rendering * * @return - * @deprecated use {@link #getFilter()}. */ public List getFilters() { return this.optionalParams.filters; } /** * Gets a list of the the filters that will be applied to each layer before rendering * * @return A list of {@link Filter}. * */ public List getFilter() { return this.optionalParams.filters; } /** * Gets a list of the cql filtesr that will be applied to each layer before rendering. * * @return A list of {@link Filter}. * */ public List getCQLFilter() { return this.optionalParams.cqlFilters; } /** * Gets a list of the feature ids that will be used to filter each layer before rendering. * * @return A list of {@link String}. */ public List getFeatureId() { return this.optionalParams.featureIds; } public boolean isTransparent() { return this.optionalParams.transparent; } /** * <a href="http://wiki.osgeo.org/index.php/WMS_Tiling_Client_Recommendation">WMS-C * specification</a> tiling hint * */ public boolean isTiled() { return this.optionalParams.tiled; } public Point2D getTilesOrigin() { return this.optionalParams.tilesOrigin; } public int getBuffer() { return this.optionalParams.buffer; } public InverseColorMapOp getPalette() { return this.optionalParams.paletteInverter; } public int getWidth() { return this.mandatoryParams.width; } /** * @return the KML/KMZ score value for image vs. vector response * @deprecated use <code>getFormatOptions().get( "kmscore" )</code> */ public int getKMScore() { Integer kmscore = (Integer) getFormatOptions().get("kmscore"); if (kmscore != null) { return kmscore.intValue(); } return 40; // old default } /** * @return true: return full attribution for placemark <description> * @deprecated use <code>getFormatOptions().get( "kmattr" )</code> */ public boolean getKMattr() { Boolean kmattr = (Boolean) getFormatOptions().get("kmattr"); if (kmattr != null) { return kmattr.booleanValue(); } return true; // old default } // /** // * @return super overlay flag, <code>true</code> if super overlay requested. // * @deprecated use <code>getFormatOptions().get( "superoverlay" )</code> // */ // public boolean getSuperOverlay() { // Boolean superOverlay = (Boolean) getFormatOptions().get("superoverlay"); // // if (superOverlay != null) { // return superOverlay.booleanValue(); // } // // return false; //old default // } /** * @return kml legend flag, <code>true</code> if legend is enabled. * @deprecated use <code>getFormatOptions().get( "legend" )</code> */ public boolean getLegend() { Boolean legend = (Boolean) getFormatOptions().get("legend"); if (legend != null) { return legend.booleanValue(); } return false; // old default } /** * @return The time request parameter. */ public List<Date> getTime() { return this.optionalParams.time; } /** * @return The elevation request parameter. */ public double getElevation() { return this.optionalParams.elevation; } /** * Returs the feature version optional parameter * * @return */ public String getFeatureVersion() { return this.optionalParams.featureVersion; } /** * Returns the remote OWS type * * @return */ public String getRemoteOwsType() { return optionalParams.remoteOwsType; } /** * Returs the remote OWS URL * * @return */ public URL getRemoteOwsURL() { return optionalParams.remoteOwsURL; } public void setBbox(Envelope bbox) { this.mandatoryParams.bbox = bbox; } public void setBgColor(java.awt.Color bgColor) { this.optionalParams.bgColor = bgColor; } public void setCrs(CoordinateReferenceSystem crs) { this.optionalParams.crs = crs; } public void setSRS(String srs) { this.optionalParams.srs = srs; } public void setExceptions(String exceptions) { this.optionalParams.exceptions = exceptions; } /** * Sets the GetMap request value for the FORMAT parameter, which is the MIME type for the kind * of image required. */ public void setFormat(String format) { this.mandatoryParams.format = format; } /** * Sets the format options. * * @param formatOptions * A map of String,Object * @see #getFormatOptions() */ public void setFormatOptions(Map formatOptions) { this.formatOptions = formatOptions; } /** * Sets the SLD environment substitution * * @param enviroment */ public void setEnv(Map enviroment) { this.env = enviroment; } /** * Sets the SQL views parameters * * @param viewParams */ public void setViewParams(Map<String, String> viewParams) { this.viewParams = viewParams; } public void setHeight(int height) { this.mandatoryParams.height = height; } public void setHeight(Integer height) { this.mandatoryParams.height = height.intValue(); } public void setLayers(List<MapLayerInfo> layers) { this.mandatoryParams.layers = layers == null ? Collections.EMPTY_LIST : layers; } public void setStyles(List<Style> styles) { this.mandatoryParams.styles = styles == null ? Collections.EMPTY_LIST : new ArrayList<Style>(styles); } /** * Sets the url specified by the "SLD" parameter. */ public void setSld(URL sld) { this.optionalParams.sld = sld; } /** * Sets the string specified by the "SLD_BODY" parameter */ public void setSldBody(String sldBody) { this.optionalParams.sldBody = sldBody; } /** * Sets the string specified by the "SLD_VERSION" parameter */ public void setSldVersion(String sldVersion) { this.optionalParams.sldVersion = sldVersion; } /** * Sets the flag to validate the "SLD" parameter or not. //TODO */ public void setValidateSchema(Boolean validateSLD) { this.optionalParams.validateSLD = validateSLD; } /** * Sets a list of filters, one for each layer * * @param filters * A list of {@link Filter}. * @deprecated use {@link #setFilter(List)}. */ public void setFilters(List filters) { setFilter(filters); } /** * Sets a list of filters, one for each layer * * @param filters * A list of {@link Filter}. */ public void setFilter(List filters) { this.optionalParams.filters = filters; } /** * Sets a list of filters ( cql ), one for each layer. * * @param cqlFilters * A list of {@link Filter}. */ public void setCQLFilter(List cqlFilters) { this.optionalParams.cqlFilters = cqlFilters; } /** * Sets a list of feature ids, one for each layer. * * @param featureIds * A list of {@link String}. */ public void setFeatureId(List featureIds) { this.optionalParams.featureIds = featureIds; } public void setTransparent(boolean transparent) { this.optionalParams.transparent = transparent; } public void setTransparent(Boolean transparent) { this.optionalParams.transparent = (transparent != null) ? transparent.booleanValue() : false; } public void setBuffer(int buffer) { this.optionalParams.buffer = buffer; } public void setPalette(InverseColorMapOp paletteInverter) { this.optionalParams.paletteInverter = paletteInverter; } public void setBuffer(Integer buffer) { this.optionalParams.buffer = (buffer != null) ? buffer.intValue() : 0; } public void setTiled(boolean tiled) { this.optionalParams.tiled = tiled; } public void setTiled(Boolean tiled) { this.optionalParams.tiled = (tiled != null) ? tiled.booleanValue() : false; } public void setTilesOrigin(Point2D origin) { this.optionalParams.tilesOrigin = origin; } public void setWidth(int width) { this.mandatoryParams.width = width; } public void setWidth(Integer width) { this.mandatoryParams.width = width.intValue(); } /** * @param score * the KML/KMZ score value for image vs. vector response, from 0 to 100 * @deprecated use <code>getFormatOptions().put( "kmscore", new Integer( score ) );</code> */ public void setKMScore(int score) { getFormatOptions().put("kmscore", new Integer(score)); } /** * @param on * true: full attribution; false: no attribution * @deprecated use <code>getFormatOptions().put( "kmattr", new Boolean( on ) );</code> */ public void setKMattr(boolean on) { getFormatOptions().put("kmattr", new Boolean(on)); } /** * Sets the super overlay parameter on the request. * * @deprecated use * <code>getFormatOptions().put( "superoverlay", new Boolean( superOverlay ) );</code> */ public void setSuperOverlay(boolean superOverlay) { getFormatOptions().put("superoverlay", new Boolean(superOverlay)); } /** * Sets the kml legend parameter of the request. * * @deprecated use <code>getFormatOptions().put( "legend", new Boolean( legend ) );</code> */ public void setLegend(boolean legend) { getFormatOptions().put("legend", new Boolean(legend)); } /** * Sets the time request parameter. * */ public void setTime(List<Date> time) { this.optionalParams.time = new ArrayList<Date>(time); } /** * Sets the elevation request parameter. */ public void setElevation(double elevation) { this.optionalParams.elevation = elevation; } /** * Sets the feature version optional param * * @param featureVersion */ public void setFeatureVersion(String featureVersion) { this.optionalParams.featureVersion = featureVersion; } public void setRemoteOwsType(String remoteOwsType) { this.optionalParams.remoteOwsType = remoteOwsType; } public void setRemoteOwsURL(URL remoteOwsURL) { this.optionalParams.remoteOwsURL = remoteOwsURL; } /** * Sets the maximum number of features to fetch in this request. * <p> * This property only applies if the reqeust is for a vector layer. * </p> */ public void setMaxFeatures(Integer maxFeatures) { this.optionalParams.maxFeatures = maxFeatures; } /** * The maximum number of features to fetch in this request. */ public Integer getMaxFeatures() { return this.optionalParams.maxFeatures; } /** * Sets the offset or start index at which to start returning features in the request. * <p> * It is used in conjunction with {@link #getMaxFeatures()} to page through a feature set. This * property only applies if the request is for a vector layer. * </p> */ public void setStartIndex(Integer startIndex) { this.optionalParams.startIndex = startIndex; } /** * The offset or start index at which to start returning features in the request. */ public Integer getStartIndex() { return this.optionalParams.startIndex; } public double getAngle() { return this.optionalParams.angle; } /** * Sets the map rotation * * @param rotation */ public void setAngle(double rotation) { this.optionalParams.angle = rotation; } private class MandatoryParameters { /** ordered list of requested layers */ List<MapLayerInfo> layers = Collections.emptyList(); /** * ordered list of requested layers' styles, in a one to one relationship with * <code>layers</code> */ List<Style> styles = Collections.emptyList(); Envelope bbox; int width; int height; String format; } private class OptionalParameters { /** * the map's background color requested, or the default (white) if not specified */ Color bgColor = DEFAULT_BG; /** from SRS (1.1) or CRS (1.2) param */ CoordinateReferenceSystem crs; /** EPSG code for the SRS */ String srs; /** vendor extensions, allows to filter each layer with a user defined filter */ List filters; /** cql filters */ List cqlFilters; /** feature id filters */ List featureIds; String exceptions = SE_XML; boolean transparent = false; /** * Tiling hint, according to the <a * href="http://wiki.osgeo.org/index.php/WMS_Tiling_Client_Recommendation">WMS-C * specification</a> */ boolean tiled; /** * Temporary hack since finding a good tiling origin would require us to compute the bbox on * the fly TODO: remove this once we cache the real bbox of vector layers */ public Point2D tilesOrigin; /** the rendering buffer, in pixels **/ int buffer; /** The paletteInverter used for rendering, if any */ InverseColorMapOp paletteInverter; /** * time elevation parameter, a list since many pattern setup can be possible, see for * example http://mapserver.gis.umn.edu/docs/howto/wms_time_support/#time-patterns */ List<Date> time; /** time elevation parameter */ double elevation = Double.NaN; /** * SLD parameter */ URL sld; /** * SLD_BODY parameter */ String sldBody; /** * SLD_VERSION parameter */ String sldVersion; /** flag to validate SLD parameter */ Boolean validateSLD = Boolean.FALSE; /** feature version (for versioned requests) */ String featureVersion; /** Remote OWS type */ String remoteOwsType; /** Remote OWS url */ URL remoteOwsURL; /** paging parameters */ Integer maxFeatures; Integer startIndex; /** map rotation */ double angle; } /** * Standard override of toString() * * @return a String representation of this request. */ public String toString() { StringBuffer returnString = new StringBuffer("\nGetMap Request"); returnString.append("\n version: " + version); returnString.append("\n output format: " + mandatoryParams.format); - returnString.append("\n width height: " + mandatoryParams.height + "," - + mandatoryParams.width); + returnString.append("\n width height: " + mandatoryParams.width + "," + + mandatoryParams.height); returnString.append("\n bbox: " + mandatoryParams.bbox); returnString.append("\n layers: "); for (Iterator<MapLayerInfo> i = mandatoryParams.layers.iterator(); i.hasNext();) { returnString.append(i.next().getName()); if (i.hasNext()) { returnString.append(","); } } returnString.append("\n styles: "); for (Iterator it = mandatoryParams.styles.iterator(); it.hasNext();) { Style s = (Style) it.next(); returnString.append(s.getName()); if (it.hasNext()) { returnString.append(","); } } // returnString.append("\n inside: " + filter.toString()); return returnString.toString(); } public String getHttpRequestHeader(String headerName) { return httpRequestHeaders == null ? null : httpRequestHeaders.get(headerName); } public void putHttpRequestHeader(String headerName, String value) { if (httpRequestHeaders == null) { httpRequestHeaders = new HashMap<String, String>(); } httpRequestHeaders.put(headerName, value); } }
true
true
public String toString() { StringBuffer returnString = new StringBuffer("\nGetMap Request"); returnString.append("\n version: " + version); returnString.append("\n output format: " + mandatoryParams.format); returnString.append("\n width height: " + mandatoryParams.height + "," + mandatoryParams.width); returnString.append("\n bbox: " + mandatoryParams.bbox); returnString.append("\n layers: "); for (Iterator<MapLayerInfo> i = mandatoryParams.layers.iterator(); i.hasNext();) { returnString.append(i.next().getName()); if (i.hasNext()) { returnString.append(","); } } returnString.append("\n styles: "); for (Iterator it = mandatoryParams.styles.iterator(); it.hasNext();) { Style s = (Style) it.next(); returnString.append(s.getName()); if (it.hasNext()) { returnString.append(","); } } // returnString.append("\n inside: " + filter.toString()); return returnString.toString(); }
public String toString() { StringBuffer returnString = new StringBuffer("\nGetMap Request"); returnString.append("\n version: " + version); returnString.append("\n output format: " + mandatoryParams.format); returnString.append("\n width height: " + mandatoryParams.width + "," + mandatoryParams.height); returnString.append("\n bbox: " + mandatoryParams.bbox); returnString.append("\n layers: "); for (Iterator<MapLayerInfo> i = mandatoryParams.layers.iterator(); i.hasNext();) { returnString.append(i.next().getName()); if (i.hasNext()) { returnString.append(","); } } returnString.append("\n styles: "); for (Iterator it = mandatoryParams.styles.iterator(); it.hasNext();) { Style s = (Style) it.next(); returnString.append(s.getName()); if (it.hasNext()) { returnString.append(","); } } // returnString.append("\n inside: " + filter.toString()); return returnString.toString(); }
diff --git a/managed/src/main/org/jboss/managed/plugins/WritethroughManagedPropertyImpl.java b/managed/src/main/org/jboss/managed/plugins/WritethroughManagedPropertyImpl.java index 76427d92..6526600e 100644 --- a/managed/src/main/org/jboss/managed/plugins/WritethroughManagedPropertyImpl.java +++ b/managed/src/main/org/jboss/managed/plugins/WritethroughManagedPropertyImpl.java @@ -1,131 +1,140 @@ /* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.managed.plugins; import java.io.ObjectStreamException; import java.io.Serializable; import org.jboss.beans.info.spi.BeanInfo; import org.jboss.beans.info.spi.PropertyInfo; import org.jboss.managed.api.Fields; import org.jboss.managed.api.ManagedObject; import org.jboss.managed.api.factory.ManagedObjectFactory; import org.jboss.managed.plugins.factory.ManagedObjectFactoryBuilder; import org.jboss.managed.spi.factory.InstanceClassFactory; import org.jboss.metatype.api.values.MetaValue; import org.jboss.metatype.api.values.MetaValueFactory; import org.jboss.metatype.api.types.MetaType; import org.jboss.metatype.plugins.values.MetaValueFactoryBuilder; /** * An extension of ManagedPropertyImpl. * * @author [email protected] * @author [email protected] * @version $Revision$ */ public class WritethroughManagedPropertyImpl extends ManagedPropertyImpl { private static final long serialVersionUID = 1; /** The meta value factory */ private transient MetaValueFactory valueFactory; /** The managed object factory */ private transient ManagedObjectFactory objectFactory; public WritethroughManagedPropertyImpl(Fields fields) { super(fields); } public WritethroughManagedPropertyImpl(ManagedObject managedObject, Fields fields) { super(managedObject, fields); } public WritethroughManagedPropertyImpl(Fields fields, MetaValueFactory valueFactory, ManagedObjectFactory objectFactory) { super(fields); this.valueFactory = valueFactory; this.objectFactory = objectFactory; } protected ManagedObjectFactory getObjectFactory() { if (objectFactory == null) objectFactory = ManagedObjectFactoryBuilder.create(); return objectFactory; } protected MetaValueFactory getValueFactory() { if (valueFactory == null) valueFactory = MetaValueFactoryBuilder.create(); return valueFactory; } /** * Write the value back to the attachment if there is a PropertyInfo * in the Fields.PROPERTY_INFO field. */ @Override @SuppressWarnings("unchecked") public void setValue(Serializable value) { super.setValue(value); PropertyInfo propertyInfo = getField(Fields.PROPERTY_INFO, PropertyInfo.class); if (propertyInfo != null) { Serializable attachment = getManagedObject().getAttachment(); if (attachment != null) { MetaValue metaValue; if (value instanceof MetaValue == false) metaValue = getValueFactory().create(value, propertyInfo.getType()); else metaValue = (MetaValue)value; - MetaType metaType = metaValue.getMetaType(); - if (metaType.isTable() == false && metaType.isComposite() == false) + boolean setValue; + if (metaValue == null) + { + setValue = true; + } + else + { + MetaType metaType = metaValue.getMetaType(); + setValue = (metaType.isTable() == false && metaType.isComposite() == false); + } + if (setValue) { InstanceClassFactory icf = getObjectFactory().getInstanceClassFactory(attachment.getClass()); BeanInfo beanInfo = propertyInfo.getBeanInfo(); icf.setValue(beanInfo, this, attachment, metaValue); } } } } /** * Expose only plain ManangedPropertyImpl. * * @return simpler ManagedPropertyImpl * @throws ObjectStreamException for any error */ private Object writeReplace() throws ObjectStreamException { ManagedPropertyImpl managedProperty = new ManagedPropertyImpl(getManagedObject(), getFields()); managedProperty.setTargetManagedObject(getTargetManagedObject()); return managedProperty; } }
true
true
public void setValue(Serializable value) { super.setValue(value); PropertyInfo propertyInfo = getField(Fields.PROPERTY_INFO, PropertyInfo.class); if (propertyInfo != null) { Serializable attachment = getManagedObject().getAttachment(); if (attachment != null) { MetaValue metaValue; if (value instanceof MetaValue == false) metaValue = getValueFactory().create(value, propertyInfo.getType()); else metaValue = (MetaValue)value; MetaType metaType = metaValue.getMetaType(); if (metaType.isTable() == false && metaType.isComposite() == false) { InstanceClassFactory icf = getObjectFactory().getInstanceClassFactory(attachment.getClass()); BeanInfo beanInfo = propertyInfo.getBeanInfo(); icf.setValue(beanInfo, this, attachment, metaValue); } } } }
public void setValue(Serializable value) { super.setValue(value); PropertyInfo propertyInfo = getField(Fields.PROPERTY_INFO, PropertyInfo.class); if (propertyInfo != null) { Serializable attachment = getManagedObject().getAttachment(); if (attachment != null) { MetaValue metaValue; if (value instanceof MetaValue == false) metaValue = getValueFactory().create(value, propertyInfo.getType()); else metaValue = (MetaValue)value; boolean setValue; if (metaValue == null) { setValue = true; } else { MetaType metaType = metaValue.getMetaType(); setValue = (metaType.isTable() == false && metaType.isComposite() == false); } if (setValue) { InstanceClassFactory icf = getObjectFactory().getInstanceClassFactory(attachment.getClass()); BeanInfo beanInfo = propertyInfo.getBeanInfo(); icf.setValue(beanInfo, this, attachment, metaValue); } } } }
diff --git a/ModelCC/test/test/org/modelcc/types/StringTest.java b/ModelCC/test/test/org/modelcc/types/StringTest.java index a882bed..0b1a448 100644 --- a/ModelCC/test/test/org/modelcc/types/StringTest.java +++ b/ModelCC/test/test/org/modelcc/types/StringTest.java @@ -1,88 +1,88 @@ /* * ModelCC, under ModelCC Shared Software License, www.modelcc.org. Luis Quesada Torres. */ package test.org.modelcc.types; import static org.junit.Assert.*; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Test; import org.modelcc.io.ModelReader; import org.modelcc.io.java.JavaModelReader; import org.modelcc.lexer.recognizer.PatternRecognizer; import org.modelcc.lexer.recognizer.regexp.RegExpPatternRecognizer; import org.modelcc.metamodel.Model; import org.modelcc.parser.Parser; import org.modelcc.parser.ParserException; import org.modelcc.parser.fence.adapter.FenceParserFactory; import org.modelcc.types.StringModel; /** * String Test. * @author elezeta * @serial */ public class StringTest { public static Parser<?> generateParser(Class<?> source) { try { ModelReader jmr = new JavaModelReader(source); Model m = jmr.read(); Set<PatternRecognizer> se = new HashSet<PatternRecognizer>(); se.add(new RegExpPatternRecognizer("( |\n|\t|\r)+")); se.add(new RegExpPatternRecognizer("%.*\n")); return FenceParserFactory.create(m,se); } catch (Exception ex) { Logger.getLogger(StringTest.class.getName()).log(Level.SEVERE, null, ex); assertTrue(false); return null; } } public static void checkMatches(Class<?> source,String input,int matches) { try { int nmatches = generateParser(source).parseAll(input).size(); assertEquals(matches,nmatches); } catch (ParserException e) { assertEquals(matches,0); } } public static Object parse(Class<?> source,String input) { try { return generateParser(source).parse(input); } catch (Exception e) { return null; } } @Test public void TextsTest() { checkMatches(StringModel.class,"",1); checkMatches(StringModel.class,"a",1); checkMatches(StringModel.class,"a$1!$&)=!)",1); checkMatches(StringModel.class,"\"a$1!$&)=!)\"",1); checkMatches(StringModel.class,"\"a$1!\"$&)=!)\"",0); checkMatches(StringModel.class,"a+",1); checkMatches(StringModel.class,"+8\"919",1); checkMatches(StringModel.class,"-",1); - checkMatches(StringModel.class,"a asdiof",1); + checkMatches(StringModel.class,"aasdiof",1); checkMatches(StringModel.class," asdiof",1); checkMatches(StringModel.class,"a;asdf",0); checkMatches(StringModel.class,"a;",0); checkMatches(StringModel.class,"a\n",1); checkMatches(StringModel.class,"a\nad",0); checkMatches(StringModel.class,"a\r",1); assertEquals("testvalue",((StringModel)parse(StringModel.class,"testvalue")).getValue()); assertEquals("testvalue",((StringModel)parse(StringModel.class," testvalue ")).getValue()); assertEquals(" testvalue ",((StringModel)parse(StringModel.class,"\" testvalue \"")).getValue()); assertEquals(" testv\"alue ",((StringModel)parse(StringModel.class,"\" testv\\\"alue \"")).getValue()); } }
true
true
public void TextsTest() { checkMatches(StringModel.class,"",1); checkMatches(StringModel.class,"a",1); checkMatches(StringModel.class,"a$1!$&)=!)",1); checkMatches(StringModel.class,"\"a$1!$&)=!)\"",1); checkMatches(StringModel.class,"\"a$1!\"$&)=!)\"",0); checkMatches(StringModel.class,"a+",1); checkMatches(StringModel.class,"+8\"919",1); checkMatches(StringModel.class,"-",1); checkMatches(StringModel.class,"a asdiof",1); checkMatches(StringModel.class," asdiof",1); checkMatches(StringModel.class,"a;asdf",0); checkMatches(StringModel.class,"a;",0); checkMatches(StringModel.class,"a\n",1); checkMatches(StringModel.class,"a\nad",0); checkMatches(StringModel.class,"a\r",1); assertEquals("testvalue",((StringModel)parse(StringModel.class,"testvalue")).getValue()); assertEquals("testvalue",((StringModel)parse(StringModel.class," testvalue ")).getValue()); assertEquals(" testvalue ",((StringModel)parse(StringModel.class,"\" testvalue \"")).getValue()); assertEquals(" testv\"alue ",((StringModel)parse(StringModel.class,"\" testv\\\"alue \"")).getValue()); }
public void TextsTest() { checkMatches(StringModel.class,"",1); checkMatches(StringModel.class,"a",1); checkMatches(StringModel.class,"a$1!$&)=!)",1); checkMatches(StringModel.class,"\"a$1!$&)=!)\"",1); checkMatches(StringModel.class,"\"a$1!\"$&)=!)\"",0); checkMatches(StringModel.class,"a+",1); checkMatches(StringModel.class,"+8\"919",1); checkMatches(StringModel.class,"-",1); checkMatches(StringModel.class,"aasdiof",1); checkMatches(StringModel.class," asdiof",1); checkMatches(StringModel.class,"a;asdf",0); checkMatches(StringModel.class,"a;",0); checkMatches(StringModel.class,"a\n",1); checkMatches(StringModel.class,"a\nad",0); checkMatches(StringModel.class,"a\r",1); assertEquals("testvalue",((StringModel)parse(StringModel.class,"testvalue")).getValue()); assertEquals("testvalue",((StringModel)parse(StringModel.class," testvalue ")).getValue()); assertEquals(" testvalue ",((StringModel)parse(StringModel.class,"\" testvalue \"")).getValue()); assertEquals(" testv\"alue ",((StringModel)parse(StringModel.class,"\" testv\\\"alue \"")).getValue()); }
diff --git a/SimpleApp/src/org/drchaos/SimpleApp.java b/SimpleApp/src/org/drchaos/SimpleApp.java index 893f5e8..95daadc 100644 --- a/SimpleApp/src/org/drchaos/SimpleApp.java +++ b/SimpleApp/src/org/drchaos/SimpleApp.java @@ -1,42 +1,42 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.drchaos; import java.util.Random; import java.util.Scanner; /** * * @author drchaos */ public class SimpleApp { /** * @param args the command line arguments */ - public static int main(String[] args) { + public static void main(String[] args) { Random generator = new Random(); Scanner scan = new Scanner(System.in); final int GUESSES = 3; // (0 - 9) + 1 is 1-10 int secret = generator.nextInt(9)+1; int myGuess = -1; System.out.println("I am thinking of a number between 1 and 10.\n" + "Try to guess it!"); for(int x=0; x<GUESSES; x++) { System.out.print("Guess: "); myGuess = scan.nextInt(); if(myGuess == secret) { System.out.println("You guessed correct!"); - return 0; // Leave main(), exit program + System.exit(0); // leave main(), exit program } else { System.out.println("You guessed wrong; Try again."); } } - return -1; // Exit status, -1 Lost game + System.exit(-1); // Exit status, -1 Lost game } }
false
true
public static int main(String[] args) { Random generator = new Random(); Scanner scan = new Scanner(System.in); final int GUESSES = 3; // (0 - 9) + 1 is 1-10 int secret = generator.nextInt(9)+1; int myGuess = -1; System.out.println("I am thinking of a number between 1 and 10.\n" + "Try to guess it!"); for(int x=0; x<GUESSES; x++) { System.out.print("Guess: "); myGuess = scan.nextInt(); if(myGuess == secret) { System.out.println("You guessed correct!"); return 0; // Leave main(), exit program } else { System.out.println("You guessed wrong; Try again."); } } return -1; // Exit status, -1 Lost game }
public static void main(String[] args) { Random generator = new Random(); Scanner scan = new Scanner(System.in); final int GUESSES = 3; // (0 - 9) + 1 is 1-10 int secret = generator.nextInt(9)+1; int myGuess = -1; System.out.println("I am thinking of a number between 1 and 10.\n" + "Try to guess it!"); for(int x=0; x<GUESSES; x++) { System.out.print("Guess: "); myGuess = scan.nextInt(); if(myGuess == secret) { System.out.println("You guessed correct!"); System.exit(0); // leave main(), exit program } else { System.out.println("You guessed wrong; Try again."); } } System.exit(-1); // Exit status, -1 Lost game }
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/DateTimeUtil.java b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/DateTimeUtil.java index 4991801f7..8a0b8151e 100644 --- a/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/DateTimeUtil.java +++ b/plugins/org.eclipse.birt.report.engine.emitter.prototype.excel/src/org/eclipse/birt/report/engine/emitter/excel/DateTimeUtil.java @@ -1,207 +1,211 @@ /******************************************************************************* * Copyright (c) 2004, 2008Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.emitter.excel; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.ibm.icu.util.ULocale; public class DateTimeUtil { static Map<ULocale, String> locale2Code = new HashMap<ULocale, String>( ); static { locale2Code.put( new ULocale( "sq", "" ), "[$-41C]" ); locale2Code.put( new ULocale( "sq", "AL" ), "[$-41C]" ); locale2Code.put( new ULocale( "ar", "" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "DZ" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "BH" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "EG" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "IQ" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "JO" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "KW" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "LB" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "LY" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "MA" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "OM" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "QA" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "SA" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "SD" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "SY" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "TN" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "AE" ), "[$-2010401]" ); locale2Code.put( new ULocale( "ar", "YE" ), "[$-2010401]" ); locale2Code.put( new ULocale( "be", "" ), "[$-423]" ); locale2Code.put( new ULocale( "be", "BY" ), "[$-423]" ); locale2Code.put( new ULocale( "bg", "" ), "[$-402]" ); locale2Code.put( new ULocale( "bg", "BG" ), "[$-402]" ); locale2Code.put( new ULocale( "ca", "" ), "[$-403]" ); locale2Code.put( new ULocale( "ca", "ES" ), "[$-403]" ); locale2Code.put( new ULocale( "zh", "" ), "[$-804]" ); locale2Code.put( new ULocale( "zh", "CN" ), "[$-804]" ); locale2Code.put( new ULocale( "zh", "HK" ), "[$-804]" ); locale2Code.put( new ULocale( "zh", "TW" ), "[$-804]" ); locale2Code.put( new ULocale( "hr", "" ), "[$-41A]" ); locale2Code.put( new ULocale( "hr", "HR" ), "[$-41A]" ); locale2Code.put( new ULocale( "cs", "" ), "[$-405]" ); locale2Code.put( new ULocale( "cs", "CZ" ), "[$-405]" ); locale2Code.put( new ULocale( "da", "" ), "[$-406]" ); locale2Code.put( new ULocale( "da", "DK" ), "[$-406]" ); locale2Code.put( new ULocale( "nl", "" ), "[$-413]" ); locale2Code.put( new ULocale( "nl", "BE" ), "[$-413]" ); locale2Code.put( new ULocale( "nl", "NL" ), "[$-413]" ); locale2Code.put( new ULocale( "en", "" ), "[$-409]" ); locale2Code.put( new ULocale( "en", "AU" ), "[$-C09]" ); locale2Code.put( new ULocale( "en", "CA" ), "[$-1009]" ); locale2Code.put( new ULocale( "en", "IN" ), "[$-409]" ); locale2Code.put( new ULocale( "en", "IE" ), "[$-409]" ); locale2Code.put( new ULocale( "en", "NZ" ), "[$-409]" ); locale2Code.put( new ULocale( "en", "ZA" ), "[$-409]" ); locale2Code.put( new ULocale( "en", "GB" ), "[$-809]" ); locale2Code.put( new ULocale( "en", "US" ), "[$-409]" ); locale2Code.put( new ULocale( "et", "" ), "[$-425]" ); locale2Code.put( new ULocale( "et", "EE" ), "[$-425]" ); locale2Code.put( new ULocale( "fi", "" ), "[$-40B]" ); locale2Code.put( new ULocale( "fi", "FI" ), "[$-40B]" ); locale2Code.put( new ULocale( "fr", "", "" ), "[$-40C]" ); locale2Code.put( new ULocale( "fr", "BE" ), "[$-40C]" ); locale2Code.put( new ULocale( "fr", "CA" ), "[$-C0C]" ); locale2Code.put( new ULocale( "fr", "FR" ), "[$-40C]" ); locale2Code.put( new ULocale( "fr", "LU" ), "[$-40C]" ); locale2Code.put( new ULocale( "fr", "CH" ), "[$-40C]" ); locale2Code.put( new ULocale( "de", "" ), "[$-407]" ); locale2Code.put( new ULocale( "de", "AT" ), "[$-C07]" ); locale2Code.put( new ULocale( "de", "DE" ), "[$-407]" ); locale2Code.put( new ULocale( "de", "LU" ), "[$-407]" ); locale2Code.put( new ULocale( "de", "CH" ), "[$-807]" ); locale2Code.put( new ULocale( "el", "" ), "[$-408]" ); locale2Code.put( new ULocale( "el", "GR" ), "[$-408]" ); locale2Code.put( new ULocale( "iw", "" ), "[$-40D]" ); locale2Code.put( new ULocale( "iw", "IL" ), "[$-40D]" ); locale2Code.put( new ULocale( "hi", "IN" ), "[$-3010439]" ); locale2Code.put( new ULocale( "hu", "" ), "[$-40E]" ); locale2Code.put( new ULocale( "hu", "HU" ), "[$-40E]" ); locale2Code.put( new ULocale( "is", "" ), "[$-40F]" ); locale2Code.put( new ULocale( "is", "IS" ), "[$-40F]" ); locale2Code.put( new ULocale( "it", "" ), "[$-410]" ); locale2Code.put( new ULocale( "it", "IT" ), "[$-410]" ); locale2Code.put( new ULocale( "it", "CH" ), "[$-410]" ); locale2Code.put( new ULocale( "ja", "" ), "[$-411]" ); locale2Code.put( new ULocale( "ja", "JP" ), "[$-411]" ); locale2Code.put( new ULocale( "ko", "" ), "[$-412]" ); locale2Code.put( new ULocale( "ko", "KR" ), "[$-412]" ); locale2Code.put( new ULocale( "lv", "" ), "[$-426]" ); locale2Code.put( new ULocale( "lv", "LV" ), "[$-426]" ); locale2Code.put( new ULocale( "lt", "" ), "[$-427]" ); locale2Code.put( new ULocale( "lt", "LT" ), "[$-427]" ); locale2Code.put( new ULocale( "mk", "" ), "[$-42F]" ); locale2Code.put( new ULocale( "mk", "MK" ), "[$-42F]" ); locale2Code.put( new ULocale( "no", "" ), "[$-414]" ); locale2Code.put( new ULocale( "no", "NO" ), "[$-414]" ); locale2Code.put( new ULocale( "pl", "" ), "[$-415]" ); locale2Code.put( new ULocale( "pl", "PL" ), "[$-415]" ); locale2Code.put( new ULocale( "pt", "" ), "[$-816]" ); locale2Code.put( new ULocale( "pt", "BR" ), "[$-416]" ); locale2Code.put( new ULocale( "pt", "PT" ), "[$-816]" ); locale2Code.put( new ULocale( "ro", "" ), "[$-418]" ); locale2Code.put( new ULocale( "ro", "RO" ), "[$-418]" ); locale2Code.put( new ULocale( "ru", "" ), "[$-419]" ); locale2Code.put( new ULocale( "ru", "RU" ), "[$-419]" ); locale2Code.put( new ULocale( "sk", "" ), "[$-41B]" ); locale2Code.put( new ULocale( "sk", "SK" ), "[$-41B]" ); locale2Code.put( new ULocale( "sl", "" ), "[$-424]" ); locale2Code.put( new ULocale( "sl", "SI" ), "[$-424]" ); locale2Code.put( new ULocale( "es", "" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "AR" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "BO" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "CL" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "CO" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "CR" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "DO" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "EC" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "SV" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "GT" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "HN" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "MX" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "NI" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "PA" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "PY" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "PE" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "PR" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "ES" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "UY" ), "[$-C0A]" ); locale2Code.put( new ULocale( "es", "VE" ), "[$-C0A]" ); locale2Code.put( new ULocale( "sv", "" ), "[$-41D]" ); locale2Code.put( new ULocale( "sv", "SE" ), "[$-41D]" ); locale2Code.put( new ULocale( "th", "" ), "[$-41E]" ); locale2Code.put( new ULocale( "th", "TH" ), "[$-41E]" ); locale2Code.put( new ULocale( "tr", "" ), "[$-41F]" ); locale2Code.put( new ULocale( "tr", "TR" ), "[$-41F]" ); locale2Code.put( new ULocale( "uk", "" ), "[$-422]" ); locale2Code.put( new ULocale( "uk", "UA" ), "[$-422]" ); locale2Code.put( new ULocale( "vi", "" ), "[$-042A]" ); locale2Code.put( new ULocale( "vi", "VN" ), "[$-042A]" ); } public static String formatDateTime( String format, ULocale locale ) { String language = locale.getLanguage( ); String code = locale2Code.get( locale ); if ( code == null ) { code = locale2Code.get( new Locale( language ) ); } + if ( code == null ) + { + return format; + } return code + format; } }
true
true
public static String formatDateTime( String format, ULocale locale ) { String language = locale.getLanguage( ); String code = locale2Code.get( locale ); if ( code == null ) { code = locale2Code.get( new Locale( language ) ); } return code + format; }
public static String formatDateTime( String format, ULocale locale ) { String language = locale.getLanguage( ); String code = locale2Code.get( locale ); if ( code == null ) { code = locale2Code.get( new Locale( language ) ); } if ( code == null ) { return format; } return code + format; }
diff --git a/srcj/com/sun/electric/tool/io/input/LTSpiceOut.java b/srcj/com/sun/electric/tool/io/input/LTSpiceOut.java index 6676812c0..66226302f 100644 --- a/srcj/com/sun/electric/tool/io/input/LTSpiceOut.java +++ b/srcj/com/sun/electric/tool/io/input/LTSpiceOut.java @@ -1,319 +1,320 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: LTSpiceOut.java * Input/output tool: reader for LTSpice output (.raw) * Written by Steven M. Rubin, Sun Microsystems. * * Copyright (c) 2009 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.io.input; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.text.TextUtils; import com.sun.electric.tool.simulation.AnalogAnalysis; import com.sun.electric.tool.simulation.AnalogSignal; import com.sun.electric.tool.simulation.Stimuli; import com.sun.electric.tool.simulation.Waveform; import com.sun.electric.tool.simulation.WaveformImpl; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Class for reading and displaying waveforms from LTSpice Raw output. * These are contained in .raw files. */ public class LTSpiceOut extends Simulate { private static final boolean DEBUG = false; private boolean complexValues; /** * Class for handling swept signals. */ private static class SweepAnalysisLT extends AnalogAnalysis { double [][] commonTime; // sweep, signal List<List<double[]>> theSweeps = new ArrayList<List<double[]>>(); // sweep, event, signal private SweepAnalysisLT(Stimuli sd, AnalogAnalysis.AnalysisType type) { super(sd, type, false); } protected Waveform[] loadWaveforms(AnalogSignal signal) { int sigIndex = signal.getIndexInAnalysis(); Waveform[] waveforms = new Waveform[commonTime.length]; for (int sweep = 0; sweep < waveforms.length; sweep++) { double[] times = commonTime[sweep]; List<double[]> theSweep = theSweeps.get(sweep); Waveform waveform = new WaveformImpl(times, theSweep.get(sigIndex)); waveforms[sweep] = waveform; } return waveforms; } } LTSpiceOut() {} /** * Method to read an LTSpice output file. */ protected Stimuli readSimulationOutput(URL fileURL, Cell cell) throws IOException { // open the file if (openBinaryInput(fileURL)) return null; // show progress reading .raw file startProgressDialog("LTSpice output", fileURL.getFile()); // read the actual signal data from the .raw file Stimuli sd = readRawLTSpiceFile(cell); // stop progress dialog, close the file stopProgressDialog(); closeInput(); // return the simulation data return sd; } private Stimuli readRawLTSpiceFile(Cell cell) throws IOException { complexValues = false; boolean realValues = false; int signalCount = -1; String[] signalNames = null; int rowCount = -1; AnalogAnalysis.AnalysisType aType = AnalogAnalysis.ANALYSIS_TRANS; for(;;) { String line = getLineFromBinary(); if (line == null) break; updateProgressDialog(line.length()); // find the ":" separator int colonPos = line.indexOf(':'); if (colonPos < 0) continue; String keyWord = line.substring(0, colonPos); String restOfLine = line.substring(colonPos+1).trim(); if (keyWord.equals("Plotname")) { // see if known analysis is specified if (restOfLine.equals("AC Analysis")) aType = AnalogAnalysis.ANALYSIS_AC; continue; } if (keyWord.equals("Flags")) { // the first signal is Time int complex = restOfLine.indexOf("complex"); if (complex >= 0) complexValues = true; int r = restOfLine.indexOf("real"); if (r >= 0) realValues = true; continue; } if (keyWord.equals("No. Variables")) { // the first signal is Time signalCount = TextUtils.atoi(restOfLine) - 1; continue; } if (keyWord.equals("No. Points")) { rowCount = TextUtils.atoi(restOfLine); continue; } if (keyWord.equals("Variables")) { if (signalCount < 0) { System.out.println("Missing variable count in file"); return null; } signalNames = new String[signalCount]; for(int i=0; i<=signalCount; i++) { restOfLine = getLineFromBinary(); if (restOfLine == null) break; updateProgressDialog(restOfLine.length()); restOfLine = restOfLine.trim(); int indexOnLine = TextUtils.atoi(restOfLine); if (indexOnLine != i) System.out.println("Warning: Variable " + i + " has number " + indexOnLine); int nameStart = 0; while (nameStart < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++; while (nameStart < restOfLine.length() && Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++; int nameEnd = nameStart; while (nameEnd < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameEnd))) nameEnd++; String name = restOfLine.substring(nameStart, nameEnd); if (name.startsWith("V(") && name.endsWith(")")) { name = name.substring(2, name.length()-1); } if (i > 0) signalNames[i-1] = name; } continue; } if (keyWord.equals("Binary")) { if (signalCount < 0) { System.out.println("Missing variable count in file"); return null; } if (rowCount < 0) { System.out.println("Missing point count in file"); return null; } // initialize the stimuli object Stimuli sd = new Stimuli(); SweepAnalysisLT an = new SweepAnalysisLT(sd, aType); sd.setCell(cell); if (DEBUG) { System.out.println(signalCount+" VARIABLES, "+rowCount+" SAMPLES"); for(int i=0; i<signalCount; i++) System.out.println("VARIABLE "+i+" IS "+signalNames[i]); } // read all of the data in the RAW file double[][] values = new double[signalCount][rowCount]; double [] timeValues = new double[rowCount]; for(int j=0; j<rowCount; j++) { double time = getNextDouble(); if (DEBUG) System.out.println("TIME AT "+j+" IS "+time); timeValues[j] = Math.abs(time); for(int i=0; i<signalCount; i++) { double value = 0; if (realValues) value = getNextFloat(); else value = getNextDouble(); if (DEBUG) System.out.println(" DATA POINT "+i+" ("+signalNames[i]+") IS "+value); values[i][j] = value; } } // figure out where the sweep breaks occur - int sweepLength = -1; + List<Integer> sweepLengths = new ArrayList<Integer>(); +// int sweepLength = -1; int sweepStart = 0; int sweepCount = 0; for(int j=1; j<=rowCount; j++) { if (j == rowCount || timeValues[j] < timeValues[j-1]) { int sl = j - sweepStart; - if (sweepLength >= 0 && sweepLength != sl) - System.out.println("ERROR! Sweeps have different length (" + sweepLength + " and " + sl + ")"); - sweepLength = sl; + sweepLengths.add(new Integer(sl)); sweepStart = j; sweepCount++; an.addSweep(Integer.toString(sweepCount)); } } - if (DEBUG) System.out.println("FOUND " + sweepCount + " SWEEPS OF LENGTH " + sweepLength); + if (DEBUG) System.out.println("FOUND " + sweepCount + " SWEEPS"); // place data into the Analysis object an.commonTime = new double[sweepCount][]; + int offset = 0; for(int s=0; s<sweepCount; s++) { - int offset = s * sweepLength; + int sweepLength = sweepLengths.get(s).intValue(); an.commonTime[s] = new double[sweepLength]; for (int j = 0; j < sweepLength; j++) an.commonTime[s][j] = timeValues[j + offset]; List<double[]> allTheData = new ArrayList<double[]>(); for(int i=0; i<signalCount; i++) { double[] oneSetOfData = new double[sweepLength]; for(int j=0; j<sweepLength; j++) oneSetOfData[j] = values[i][j+offset]; allTheData.add(oneSetOfData); } an.theSweeps.add(allTheData); + offset += sweepLength; } // add signal names to the analysis for (int i = 0; i < signalCount; i++) { String name = signalNames[i]; int lastDotPos = name.lastIndexOf('.'); String context = null; if (lastDotPos >= 0) { context = name.substring(0, lastDotPos); name = name.substring(lastDotPos + 1); } double minTime = 0, maxTime = 0, minValues = 0, maxValues = 0; an.addSignal(signalNames[i], context, minTime, maxTime, minValues, maxValues); } return sd; } } return null; } private double getNextDouble() throws IOException { // double values appear with reversed bytes long lt = dataInputStream.readLong(); lt = Long.reverseBytes(lt); double t = Double.longBitsToDouble(lt); int amtRead = 8; // for complex plots, ignore imaginary part if (complexValues) { amtRead *= 2; dataInputStream.readLong(); } updateProgressDialog(amtRead); return t; } private float getNextFloat() throws IOException { // float values appear with reversed bytes int lt = dataInputStream.readInt(); lt = Integer.reverseBytes(lt); float t = Float.intBitsToFloat(lt); int amtRead = 4; // for complex plots, ignore imaginary part if (complexValues) { amtRead *= 2; dataInputStream.readInt(); } updateProgressDialog(amtRead); return t; } }
false
true
private Stimuli readRawLTSpiceFile(Cell cell) throws IOException { complexValues = false; boolean realValues = false; int signalCount = -1; String[] signalNames = null; int rowCount = -1; AnalogAnalysis.AnalysisType aType = AnalogAnalysis.ANALYSIS_TRANS; for(;;) { String line = getLineFromBinary(); if (line == null) break; updateProgressDialog(line.length()); // find the ":" separator int colonPos = line.indexOf(':'); if (colonPos < 0) continue; String keyWord = line.substring(0, colonPos); String restOfLine = line.substring(colonPos+1).trim(); if (keyWord.equals("Plotname")) { // see if known analysis is specified if (restOfLine.equals("AC Analysis")) aType = AnalogAnalysis.ANALYSIS_AC; continue; } if (keyWord.equals("Flags")) { // the first signal is Time int complex = restOfLine.indexOf("complex"); if (complex >= 0) complexValues = true; int r = restOfLine.indexOf("real"); if (r >= 0) realValues = true; continue; } if (keyWord.equals("No. Variables")) { // the first signal is Time signalCount = TextUtils.atoi(restOfLine) - 1; continue; } if (keyWord.equals("No. Points")) { rowCount = TextUtils.atoi(restOfLine); continue; } if (keyWord.equals("Variables")) { if (signalCount < 0) { System.out.println("Missing variable count in file"); return null; } signalNames = new String[signalCount]; for(int i=0; i<=signalCount; i++) { restOfLine = getLineFromBinary(); if (restOfLine == null) break; updateProgressDialog(restOfLine.length()); restOfLine = restOfLine.trim(); int indexOnLine = TextUtils.atoi(restOfLine); if (indexOnLine != i) System.out.println("Warning: Variable " + i + " has number " + indexOnLine); int nameStart = 0; while (nameStart < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++; while (nameStart < restOfLine.length() && Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++; int nameEnd = nameStart; while (nameEnd < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameEnd))) nameEnd++; String name = restOfLine.substring(nameStart, nameEnd); if (name.startsWith("V(") && name.endsWith(")")) { name = name.substring(2, name.length()-1); } if (i > 0) signalNames[i-1] = name; } continue; } if (keyWord.equals("Binary")) { if (signalCount < 0) { System.out.println("Missing variable count in file"); return null; } if (rowCount < 0) { System.out.println("Missing point count in file"); return null; } // initialize the stimuli object Stimuli sd = new Stimuli(); SweepAnalysisLT an = new SweepAnalysisLT(sd, aType); sd.setCell(cell); if (DEBUG) { System.out.println(signalCount+" VARIABLES, "+rowCount+" SAMPLES"); for(int i=0; i<signalCount; i++) System.out.println("VARIABLE "+i+" IS "+signalNames[i]); } // read all of the data in the RAW file double[][] values = new double[signalCount][rowCount]; double [] timeValues = new double[rowCount]; for(int j=0; j<rowCount; j++) { double time = getNextDouble(); if (DEBUG) System.out.println("TIME AT "+j+" IS "+time); timeValues[j] = Math.abs(time); for(int i=0; i<signalCount; i++) { double value = 0; if (realValues) value = getNextFloat(); else value = getNextDouble(); if (DEBUG) System.out.println(" DATA POINT "+i+" ("+signalNames[i]+") IS "+value); values[i][j] = value; } } // figure out where the sweep breaks occur int sweepLength = -1; int sweepStart = 0; int sweepCount = 0; for(int j=1; j<=rowCount; j++) { if (j == rowCount || timeValues[j] < timeValues[j-1]) { int sl = j - sweepStart; if (sweepLength >= 0 && sweepLength != sl) System.out.println("ERROR! Sweeps have different length (" + sweepLength + " and " + sl + ")"); sweepLength = sl; sweepStart = j; sweepCount++; an.addSweep(Integer.toString(sweepCount)); } } if (DEBUG) System.out.println("FOUND " + sweepCount + " SWEEPS OF LENGTH " + sweepLength); // place data into the Analysis object an.commonTime = new double[sweepCount][]; for(int s=0; s<sweepCount; s++) { int offset = s * sweepLength; an.commonTime[s] = new double[sweepLength]; for (int j = 0; j < sweepLength; j++) an.commonTime[s][j] = timeValues[j + offset]; List<double[]> allTheData = new ArrayList<double[]>(); for(int i=0; i<signalCount; i++) { double[] oneSetOfData = new double[sweepLength]; for(int j=0; j<sweepLength; j++) oneSetOfData[j] = values[i][j+offset]; allTheData.add(oneSetOfData); } an.theSweeps.add(allTheData); } // add signal names to the analysis for (int i = 0; i < signalCount; i++) { String name = signalNames[i]; int lastDotPos = name.lastIndexOf('.'); String context = null; if (lastDotPos >= 0) { context = name.substring(0, lastDotPos); name = name.substring(lastDotPos + 1); } double minTime = 0, maxTime = 0, minValues = 0, maxValues = 0; an.addSignal(signalNames[i], context, minTime, maxTime, minValues, maxValues); } return sd; } } return null; }
private Stimuli readRawLTSpiceFile(Cell cell) throws IOException { complexValues = false; boolean realValues = false; int signalCount = -1; String[] signalNames = null; int rowCount = -1; AnalogAnalysis.AnalysisType aType = AnalogAnalysis.ANALYSIS_TRANS; for(;;) { String line = getLineFromBinary(); if (line == null) break; updateProgressDialog(line.length()); // find the ":" separator int colonPos = line.indexOf(':'); if (colonPos < 0) continue; String keyWord = line.substring(0, colonPos); String restOfLine = line.substring(colonPos+1).trim(); if (keyWord.equals("Plotname")) { // see if known analysis is specified if (restOfLine.equals("AC Analysis")) aType = AnalogAnalysis.ANALYSIS_AC; continue; } if (keyWord.equals("Flags")) { // the first signal is Time int complex = restOfLine.indexOf("complex"); if (complex >= 0) complexValues = true; int r = restOfLine.indexOf("real"); if (r >= 0) realValues = true; continue; } if (keyWord.equals("No. Variables")) { // the first signal is Time signalCount = TextUtils.atoi(restOfLine) - 1; continue; } if (keyWord.equals("No. Points")) { rowCount = TextUtils.atoi(restOfLine); continue; } if (keyWord.equals("Variables")) { if (signalCount < 0) { System.out.println("Missing variable count in file"); return null; } signalNames = new String[signalCount]; for(int i=0; i<=signalCount; i++) { restOfLine = getLineFromBinary(); if (restOfLine == null) break; updateProgressDialog(restOfLine.length()); restOfLine = restOfLine.trim(); int indexOnLine = TextUtils.atoi(restOfLine); if (indexOnLine != i) System.out.println("Warning: Variable " + i + " has number " + indexOnLine); int nameStart = 0; while (nameStart < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++; while (nameStart < restOfLine.length() && Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++; int nameEnd = nameStart; while (nameEnd < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameEnd))) nameEnd++; String name = restOfLine.substring(nameStart, nameEnd); if (name.startsWith("V(") && name.endsWith(")")) { name = name.substring(2, name.length()-1); } if (i > 0) signalNames[i-1] = name; } continue; } if (keyWord.equals("Binary")) { if (signalCount < 0) { System.out.println("Missing variable count in file"); return null; } if (rowCount < 0) { System.out.println("Missing point count in file"); return null; } // initialize the stimuli object Stimuli sd = new Stimuli(); SweepAnalysisLT an = new SweepAnalysisLT(sd, aType); sd.setCell(cell); if (DEBUG) { System.out.println(signalCount+" VARIABLES, "+rowCount+" SAMPLES"); for(int i=0; i<signalCount; i++) System.out.println("VARIABLE "+i+" IS "+signalNames[i]); } // read all of the data in the RAW file double[][] values = new double[signalCount][rowCount]; double [] timeValues = new double[rowCount]; for(int j=0; j<rowCount; j++) { double time = getNextDouble(); if (DEBUG) System.out.println("TIME AT "+j+" IS "+time); timeValues[j] = Math.abs(time); for(int i=0; i<signalCount; i++) { double value = 0; if (realValues) value = getNextFloat(); else value = getNextDouble(); if (DEBUG) System.out.println(" DATA POINT "+i+" ("+signalNames[i]+") IS "+value); values[i][j] = value; } } // figure out where the sweep breaks occur List<Integer> sweepLengths = new ArrayList<Integer>(); // int sweepLength = -1; int sweepStart = 0; int sweepCount = 0; for(int j=1; j<=rowCount; j++) { if (j == rowCount || timeValues[j] < timeValues[j-1]) { int sl = j - sweepStart; sweepLengths.add(new Integer(sl)); sweepStart = j; sweepCount++; an.addSweep(Integer.toString(sweepCount)); } } if (DEBUG) System.out.println("FOUND " + sweepCount + " SWEEPS"); // place data into the Analysis object an.commonTime = new double[sweepCount][]; int offset = 0; for(int s=0; s<sweepCount; s++) { int sweepLength = sweepLengths.get(s).intValue(); an.commonTime[s] = new double[sweepLength]; for (int j = 0; j < sweepLength; j++) an.commonTime[s][j] = timeValues[j + offset]; List<double[]> allTheData = new ArrayList<double[]>(); for(int i=0; i<signalCount; i++) { double[] oneSetOfData = new double[sweepLength]; for(int j=0; j<sweepLength; j++) oneSetOfData[j] = values[i][j+offset]; allTheData.add(oneSetOfData); } an.theSweeps.add(allTheData); offset += sweepLength; } // add signal names to the analysis for (int i = 0; i < signalCount; i++) { String name = signalNames[i]; int lastDotPos = name.lastIndexOf('.'); String context = null; if (lastDotPos >= 0) { context = name.substring(0, lastDotPos); name = name.substring(lastDotPos + 1); } double minTime = 0, maxTime = 0, minValues = 0, maxValues = 0; an.addSignal(signalNames[i], context, minTime, maxTime, minValues, maxValues); } return sd; } } return null; }
diff --git a/dsl-project/ashigel-compiler/src/main/java/com/asakusafw/compiler/flow/stage/ShufflePartitionerEmitter.java b/dsl-project/ashigel-compiler/src/main/java/com/asakusafw/compiler/flow/stage/ShufflePartitionerEmitter.java index 684eefcda..f28a5f187 100644 --- a/dsl-project/ashigel-compiler/src/main/java/com/asakusafw/compiler/flow/stage/ShufflePartitionerEmitter.java +++ b/dsl-project/ashigel-compiler/src/main/java/com/asakusafw/compiler/flow/stage/ShufflePartitionerEmitter.java @@ -1,270 +1,270 @@ /** * Copyright 2011-2012 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.compiler.flow.stage; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.hadoop.mapreduce.Partitioner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.asakusafw.compiler.common.Naming; import com.asakusafw.compiler.common.Precondition; import com.asakusafw.compiler.flow.FlowCompilingEnvironment; import com.asakusafw.compiler.flow.stage.ShuffleModel.Arrangement; import com.asakusafw.compiler.flow.stage.ShuffleModel.Segment; import com.asakusafw.compiler.flow.stage.ShuffleModel.Term; import com.asakusafw.runtime.flow.SegmentedWritable; import com.asakusafw.utils.collections.Lists; import com.asakusafw.utils.java.model.syntax.Comment; import com.asakusafw.utils.java.model.syntax.CompilationUnit; import com.asakusafw.utils.java.model.syntax.Expression; import com.asakusafw.utils.java.model.syntax.FormalParameterDeclaration; import com.asakusafw.utils.java.model.syntax.InfixOperator; import com.asakusafw.utils.java.model.syntax.Javadoc; import com.asakusafw.utils.java.model.syntax.MethodDeclaration; import com.asakusafw.utils.java.model.syntax.ModelFactory; import com.asakusafw.utils.java.model.syntax.Name; import com.asakusafw.utils.java.model.syntax.SimpleName; import com.asakusafw.utils.java.model.syntax.Statement; import com.asakusafw.utils.java.model.syntax.Type; import com.asakusafw.utils.java.model.syntax.TypeBodyDeclaration; import com.asakusafw.utils.java.model.syntax.TypeDeclaration; import com.asakusafw.utils.java.model.syntax.TypeParameterDeclaration; import com.asakusafw.utils.java.model.util.AttributeBuilder; import com.asakusafw.utils.java.model.util.ExpressionBuilder; import com.asakusafw.utils.java.model.util.ImportBuilder; import com.asakusafw.utils.java.model.util.JavadocBuilder; import com.asakusafw.utils.java.model.util.Models; import com.asakusafw.utils.java.model.util.TypeBuilder; /** * シャッフルフェーズで利用するパーティショナーを生成する。 */ public class ShufflePartitionerEmitter { static final Logger LOG = LoggerFactory.getLogger(ShufflePartitionerEmitter.class); private FlowCompilingEnvironment environment; /** * インスタンスを生成する。 * @param environment 環境オブジェクト * @throws IllegalArgumentException 引数に{@code null}が指定された場合 */ public ShufflePartitionerEmitter(FlowCompilingEnvironment environment) { Precondition.checkMustNotBeNull(environment, "environment"); //$NON-NLS-1$ this.environment = environment; } /** * 指定のモデルに対するパーティショナーを表すクラスを生成し、生成したクラスの完全限定名を返す。 * @param model 対象のモデル * @param keyTypeName キー型の完全限定名 * @param valueTypeName 値型の完全限定名 * @return 生成したクラスの完全限定名 * @throws IOException クラスの生成に失敗した場合 * @throws IllegalArgumentException 引数に{@code null}が指定された場合 */ public Name emit( ShuffleModel model, Name keyTypeName, Name valueTypeName) throws IOException { Precondition.checkMustNotBeNull(model, "model"); //$NON-NLS-1$ Precondition.checkMustNotBeNull(keyTypeName, "keyTypeName"); //$NON-NLS-1$ LOG.debug("{}に対するパーティショナーを生成します", model.getStageBlock()); Engine engine = new Engine(environment, model, keyTypeName, valueTypeName); CompilationUnit source = engine.generate(); environment.emit(source); Name packageName = source.getPackageDeclaration().getName(); SimpleName simpleName = source.getTypeDeclarations().get(0).getName(); Name name = environment.getModelFactory().newQualifiedName(packageName, simpleName); LOG.debug("{}のパーティショニングには{}が利用されます", model.getStageBlock(), name); return name; } private static class Engine { private static final String HASH_CODE_METHOD_NAME = "getHashCode"; private ShuffleModel model; private ModelFactory factory; private ImportBuilder importer; private Type keyType; private Type valueType; public Engine( FlowCompilingEnvironment environment, ShuffleModel model, Name keyTypeName, Name valueTypeName) { assert environment != null; assert model != null; assert keyTypeName != null; assert valueTypeName != null; this.model = model; this.factory = environment.getModelFactory(); Name packageName = environment.getStagePackageName(model.getStageBlock().getStageNumber()); this.importer = new ImportBuilder( factory, factory.newPackageDeclaration(packageName), ImportBuilder.Strategy.TOP_LEVEL); this.keyType = importer.resolve(factory.newNamedType(keyTypeName)); this.valueType = importer.resolve(factory.newNamedType(valueTypeName)); } public CompilationUnit generate() { TypeDeclaration type = createType(); return factory.newCompilationUnit( importer.getPackageDeclaration(), importer.toImportDeclarations(), Collections.singletonList(type), Collections.<Comment>emptyList()); } private TypeDeclaration createType() { SimpleName name = factory.newSimpleName(Naming.getShufflePartitionerClass()); importer.resolvePackageMember(name); List<TypeBodyDeclaration> members = Lists.create(); members.add(createPartition()); members.add(createHashCode()); members.add(ShuffleEmiterUtil.createPortToElement(factory, model)); return factory.newClassDeclaration( createJavadoc(), new AttributeBuilder(factory) .annotation(t(SuppressWarnings.class), v("deprecation")) .Public() .Final() .toAttributes(), name, Collections.<TypeParameterDeclaration>emptyList(), importer.resolve(factory.newParameterizedType( t(Partitioner.class), Arrays.asList(keyType, valueType))), Collections.<Type>emptyList(), members); } private MethodDeclaration createPartition() { SimpleName key = factory.newSimpleName("key"); SimpleName value = factory.newSimpleName("value"); SimpleName partitions = factory.newSimpleName("numPartitions"); List<Statement> statements = Lists.create(); statements.add(new ExpressionBuilder(factory, factory.newThis()) .method(HASH_CODE_METHOD_NAME, key) .apply(InfixOperator.AND, new TypeBuilder(factory, t(Integer.class)) .field("MAX_VALUE") .toExpression()) .apply(InfixOperator.REMAINDER, partitions) .toReturnStatement()); return factory.newMethodDeclaration( null, new AttributeBuilder(factory) .annotation(t(Override.class)) .Public() .toAttributes(), t(int.class), factory.newSimpleName("getPartition"), Arrays.asList(new FormalParameterDeclaration[] { factory.newFormalParameterDeclaration(keyType, key), factory.newFormalParameterDeclaration(valueType, value), factory.newFormalParameterDeclaration(t(int.class), partitions), }), statements); } private MethodDeclaration createHashCode() { SimpleName key = factory.newSimpleName("key"); List<Statement> statements = Lists.create(); SimpleName portId = factory.newSimpleName("portId"); SimpleName result = factory.newSimpleName("result"); statements.add(new ExpressionBuilder(factory, key) .method(SegmentedWritable.ID_GETTER) .toLocalVariableDeclaration(t(int.class), portId)); statements.add(new ExpressionBuilder(factory, factory.newThis()) .method(ShuffleEmiterUtil.PORT_TO_ELEMENT, portId) .toLocalVariableDeclaration(t(int.class), result)); List<Statement> cases = Lists.create(); for (Segment segment : model.getSegments()) { cases.add(factory.newSwitchCaseLabel(v(segment.getPortId()))); for (Term term : segment.getTerms()) { if (term.getArrangement() != Arrangement.GROUPING) { continue; } Expression hash = term.getSource().createHashCode( new ExpressionBuilder(factory, key) .field(ShuffleEmiterUtil.getPropertyName(segment, term)) .toExpression()); cases.add(new ExpressionBuilder(factory, result) - .assignFrom(InfixOperator.PLUS, + .assignFrom( new ExpressionBuilder(factory, result) .apply(InfixOperator.TIMES, v(31)) .apply(InfixOperator.PLUS, hash) .toExpression()) .toStatement()); } cases.add(factory.newBreakStatement()); } cases.add(factory.newSwitchDefaultLabel()); cases.add(new TypeBuilder(factory, t(AssertionError.class)) .newObject(portId) .toThrowStatement()); statements.add(factory.newSwitchStatement(portId, cases)); statements.add(new ExpressionBuilder(factory, result) .toReturnStatement()); return factory.newMethodDeclaration( null, new AttributeBuilder(factory) .Private() .toAttributes(), t(int.class), factory.newSimpleName(HASH_CODE_METHOD_NAME), Collections.singletonList( factory.newFormalParameterDeclaration(keyType, key)), statements); } private Javadoc createJavadoc() { return new JavadocBuilder(factory) .text("ステージ#{0}シャッフルで利用するパーティショナー。", model.getStageBlock().getStageNumber()) .toJavadoc(); } private Type t(java.lang.reflect.Type type) { return importer.resolve(Models.toType(factory, type)); } private Expression v(Object value) { return Models.toLiteral(factory, value); } } }
true
true
private MethodDeclaration createHashCode() { SimpleName key = factory.newSimpleName("key"); List<Statement> statements = Lists.create(); SimpleName portId = factory.newSimpleName("portId"); SimpleName result = factory.newSimpleName("result"); statements.add(new ExpressionBuilder(factory, key) .method(SegmentedWritable.ID_GETTER) .toLocalVariableDeclaration(t(int.class), portId)); statements.add(new ExpressionBuilder(factory, factory.newThis()) .method(ShuffleEmiterUtil.PORT_TO_ELEMENT, portId) .toLocalVariableDeclaration(t(int.class), result)); List<Statement> cases = Lists.create(); for (Segment segment : model.getSegments()) { cases.add(factory.newSwitchCaseLabel(v(segment.getPortId()))); for (Term term : segment.getTerms()) { if (term.getArrangement() != Arrangement.GROUPING) { continue; } Expression hash = term.getSource().createHashCode( new ExpressionBuilder(factory, key) .field(ShuffleEmiterUtil.getPropertyName(segment, term)) .toExpression()); cases.add(new ExpressionBuilder(factory, result) .assignFrom(InfixOperator.PLUS, new ExpressionBuilder(factory, result) .apply(InfixOperator.TIMES, v(31)) .apply(InfixOperator.PLUS, hash) .toExpression()) .toStatement()); } cases.add(factory.newBreakStatement()); } cases.add(factory.newSwitchDefaultLabel()); cases.add(new TypeBuilder(factory, t(AssertionError.class)) .newObject(portId) .toThrowStatement()); statements.add(factory.newSwitchStatement(portId, cases)); statements.add(new ExpressionBuilder(factory, result) .toReturnStatement()); return factory.newMethodDeclaration( null, new AttributeBuilder(factory) .Private() .toAttributes(), t(int.class), factory.newSimpleName(HASH_CODE_METHOD_NAME), Collections.singletonList( factory.newFormalParameterDeclaration(keyType, key)), statements); }
private MethodDeclaration createHashCode() { SimpleName key = factory.newSimpleName("key"); List<Statement> statements = Lists.create(); SimpleName portId = factory.newSimpleName("portId"); SimpleName result = factory.newSimpleName("result"); statements.add(new ExpressionBuilder(factory, key) .method(SegmentedWritable.ID_GETTER) .toLocalVariableDeclaration(t(int.class), portId)); statements.add(new ExpressionBuilder(factory, factory.newThis()) .method(ShuffleEmiterUtil.PORT_TO_ELEMENT, portId) .toLocalVariableDeclaration(t(int.class), result)); List<Statement> cases = Lists.create(); for (Segment segment : model.getSegments()) { cases.add(factory.newSwitchCaseLabel(v(segment.getPortId()))); for (Term term : segment.getTerms()) { if (term.getArrangement() != Arrangement.GROUPING) { continue; } Expression hash = term.getSource().createHashCode( new ExpressionBuilder(factory, key) .field(ShuffleEmiterUtil.getPropertyName(segment, term)) .toExpression()); cases.add(new ExpressionBuilder(factory, result) .assignFrom( new ExpressionBuilder(factory, result) .apply(InfixOperator.TIMES, v(31)) .apply(InfixOperator.PLUS, hash) .toExpression()) .toStatement()); } cases.add(factory.newBreakStatement()); } cases.add(factory.newSwitchDefaultLabel()); cases.add(new TypeBuilder(factory, t(AssertionError.class)) .newObject(portId) .toThrowStatement()); statements.add(factory.newSwitchStatement(portId, cases)); statements.add(new ExpressionBuilder(factory, result) .toReturnStatement()); return factory.newMethodDeclaration( null, new AttributeBuilder(factory) .Private() .toAttributes(), t(int.class), factory.newSimpleName(HASH_CODE_METHOD_NAME), Collections.singletonList( factory.newFormalParameterDeclaration(keyType, key)), statements); }
diff --git a/framework/src/play/templates/FastTags.java b/framework/src/play/templates/FastTags.java index 6f9c29d4..40f8d7b4 100644 --- a/framework/src/play/templates/FastTags.java +++ b/framework/src/play/templates/FastTags.java @@ -1,291 +1,291 @@ package play.templates; import groovy.lang.Closure; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import play.data.validation.Error; import play.data.validation.Validation; import play.exceptions.TagInternalException; import play.exceptions.TemplateExecutionException; import play.exceptions.TemplateNotFoundException; import play.libs.Codec; import play.mvc.Router.ActionDefinition; import play.templates.Template.ExecutableTemplate; /** * Fast tags implementation */ public class FastTags { public static void _verbatim(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { out.println(JavaExtensions.toString(body)); } public static void _jsAction(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { out.println("function(options) {var pattern = '" + args.get("arg").toString() + "'; for(key in options) { pattern = pattern.replace(':'+key, options[key]); } return pattern };"); } public static void _select(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { String name = args.get("arg").toString(); String size = args.containsKey("size") ? args.get("size").toString() : "1"; Object value = args.get("value"); TagContext.current().data.put("selected", value); out.print("<select name=\"" + name +"\" size=\""+size+"\" "+serialize(args, "name", "size")+">"); if(body != null) { out.println(JavaExtensions.toString(body)); } out.print("</select>"); } public static void _option(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { Object value = args.get("arg"); Object selectedValue = TagContext.parent("select").data.get("selected"); boolean selected = selectedValue != null && value != null && selectedValue.equals(value); out.print("<option value=\""+(value == null ? "" : value)+"\" "+(selected ? "selected" : "")+""+serialize(args, "selected", "value")+">"); out.println(JavaExtensions.toString(body)); out.print("</option>"); } /** * Generates a html form element linked to a controller action * @param args tag attributes * @param body tag inner body * @param out the output writer * @param template encloding template * @param fromLine template line number where the tag is defined */ public static void _form(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { ActionDefinition actionDef = (ActionDefinition) args.get("arg"); if (actionDef == null) { actionDef = (ActionDefinition) args.get("action"); } String enctype = (String) args.get("enctype"); if (enctype == null) { enctype = "application/x-www-form-urlencoded"; } if (actionDef.star) { actionDef.method = "POST"; // prefer POST for form .... } if (args.containsKey("method")) { actionDef.method = args.get("method").toString(); } if (!("GET".equals(actionDef.method) || "POST".equals(actionDef.method))) { String separator = actionDef.url.indexOf('?') != -1 ? "&" : "?"; - actionDef.url += separator + "x-http-method-override=" + actionDef.method; + actionDef.url += separator + "x-http-method-override=" + actionDef.method.toUpperCase(); actionDef.method = "POST"; } - out.print("<form action=\"" + actionDef.url + "\" method=\"" + actionDef.method + "\" accept-charset=\"utf-8\" enctype=\"" + enctype + "\" "+serialize(args, "action", "method", "accept-charset", "enctype")+">"); + out.print("<form action=\"" + actionDef.url + "\" method=\"" + actionDef.method.toUpperCase() + "\" accept-charset=\"utf-8\" enctype=\"" + enctype + "\" "+serialize(args, "action", "method", "accept-charset", "enctype")+">"); out.println(JavaExtensions.toString(body)); out.print("</form>"); } /** * Generates a html link to a controller action * @param args tag attributes * @param body tag inner body * @param out the output writer * @param template encloding template * @param fromLine template line number where the tag is defined */ public static void _a(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { ActionDefinition actionDef = (ActionDefinition) args.get("arg"); if (actionDef == null) { actionDef = (ActionDefinition) args.get("action"); } if (!("GET".equals(actionDef.method))) { if (!("POST".equals(actionDef.method))) { String separator = actionDef.url.indexOf('?') != -1 ? "&" : "?"; actionDef.url += separator + "x-http-method-override=" + actionDef.method; actionDef.method = "POST"; } String id = Codec.UUID(); out.print("<form method=\"POST\" id=\"" + id + "\" style=\"display:none\" action=\"" + actionDef.url + "\"></form>"); out.print("<a href=\"javascript:document.getElementById('" + id + "').submit();\" "+serialize(args, "href")+">"); out.print(JavaExtensions.toString(body)); out.print("</a>"); } else { out.print("<a href=\"" + actionDef.url + "\" "+serialize(args, "href")+">"); out.print(JavaExtensions.toString(body)); out.print("</a>"); } } public static void _ifErrors(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { if (Validation.hasErrors()) { body.call(); TagContext.parent().data.put("_executeNextElse", false); } else { TagContext.parent().data.put("_executeNextElse", true); } } public static void _ifError(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { if (args.get("arg") == null) { throw new TemplateExecutionException(template.template, fromLine, "Please specify the error key", new TagInternalException("Please specify the error key")); } if (Validation.hasError(args.get("arg").toString())) { body.call(); TagContext.parent().data.put("_executeNextElse", false); } else { TagContext.parent().data.put("_executeNextElse", true); } } public static void _errorClass(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { if (args.get("arg") == null) { throw new TemplateExecutionException(template.template, fromLine, "Please specify the error key", new TagInternalException("Please specify the error key")); } if (Validation.hasError(args.get("arg").toString())) { out.print("hasError"); } } public static void _error(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { if (args.get("arg") == null && args.get("key") == null) { throw new TemplateExecutionException(template.template, fromLine, "Please specify the error key", new TagInternalException("Please specify the error key")); } String key = args.get("arg") == null ? args.get("key") + "" : args.get("arg") + ""; Error error = Validation.error(key); if (error != null) { if (args.get("field") == null) { out.print(error.message()); } else { out.print(error.message(args.get("field") + "")); } } } static boolean _evaluateCondition(Object test) { if (test != null) { if (test instanceof Boolean) { return ((Boolean) test).booleanValue(); } else if (test instanceof String) { return ((String) test).length() > 0; } else if (test instanceof Number) { return ((Number) test).intValue() != 0; } else if (test instanceof Collection) { return ((Collection) test).size() != 0; } else { return true; } } return false; } public static void _doLayout(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { out.print("____%LAYOUT%____"); } public static void _get(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { Object name = args.get("arg"); if (name == null) { throw new TemplateExecutionException(template.template, fromLine, "Specify a variable name", new TagInternalException("Specify a variable name")); } Object value = Template.layoutData.get().get(name); if (value != null) { out.print(value); } else { if (body != null) { out.print(JavaExtensions.toString(body)); } } } public static void _set(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { // Simple case : #{set title:'Yop' /} for (Map.Entry<?, ?> entry : args.entrySet()) { Object key = entry.getKey(); if (!key.toString().equals("arg")) { Template.layoutData.get().put(key, entry.getValue()); return; } } // Body case Object name = args.get("arg"); if (name != null && body != null) { Object oldOut = body.getProperty("out"); StringWriter sw = new StringWriter(); body.setProperty("out", new PrintWriter(sw)); body.call(); Template.layoutData.get().put(name, sw.toString()); body.setProperty("out", oldOut); } } public static void _extends(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { try { if (!args.containsKey("arg") || args.get("arg") == null) { throw new TemplateExecutionException(template.template, fromLine, "Specify a template name", new TagInternalException("Specify a template name")); } String name = args.get("arg").toString(); if (name.startsWith("./")) { String ct = Template.currentTemplate.get().name; if (ct.matches("^/lib/[^/]+/app/views/.*")) { ct = ct.substring(ct.indexOf("/", 5)); } ct = ct.substring(0, ct.lastIndexOf("/")); name = ct + name.substring(1); } Template.layout.set(TemplateLoader.load(name)); } catch (TemplateNotFoundException e) { throw new TemplateNotFoundException(e.getPath(), template.template, fromLine); } } public static void _include(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { try { if (!args.containsKey("arg") || args.get("arg") == null) { throw new TemplateExecutionException(template.template, fromLine, "Specify a template name", new TagInternalException("Specify a template name")); } String name = args.get("arg").toString(); if (name.startsWith("./")) { String ct = Template.currentTemplate.get().name; if (ct.matches("^/lib/[^/]+/app/views/.*")) { ct = ct.substring(ct.indexOf("/", 5)); } ct = ct.substring(0, ct.lastIndexOf("/")); name = ct + name.substring(1); } Template t = TemplateLoader.load(name); Map newArgs = new HashMap(); newArgs.putAll(template.getBinding().getVariables()); newArgs.put("_isInclude", true); t.render(newArgs); } catch (TemplateNotFoundException e) { throw new TemplateNotFoundException(e.getPath(), template.template, fromLine); } } static String serialize(Map<?, ?> args, String... unless) { StringBuffer attrs = new StringBuffer(); for(Object o : args.keySet()) { String attr = o.toString(); String value = args.get(o) == null ? "" : args.get(o).toString(); if(Arrays.binarySearch(unless, attr) < 0 && !attr.equals("arg")) { attrs.append(attr); attrs.append("=\""); attrs.append(value); attrs.append("\" "); } } return attrs.toString(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public static @interface Namespace { String value() default ""; } }
false
true
public static void _form(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { ActionDefinition actionDef = (ActionDefinition) args.get("arg"); if (actionDef == null) { actionDef = (ActionDefinition) args.get("action"); } String enctype = (String) args.get("enctype"); if (enctype == null) { enctype = "application/x-www-form-urlencoded"; } if (actionDef.star) { actionDef.method = "POST"; // prefer POST for form .... } if (args.containsKey("method")) { actionDef.method = args.get("method").toString(); } if (!("GET".equals(actionDef.method) || "POST".equals(actionDef.method))) { String separator = actionDef.url.indexOf('?') != -1 ? "&" : "?"; actionDef.url += separator + "x-http-method-override=" + actionDef.method; actionDef.method = "POST"; } out.print("<form action=\"" + actionDef.url + "\" method=\"" + actionDef.method + "\" accept-charset=\"utf-8\" enctype=\"" + enctype + "\" "+serialize(args, "action", "method", "accept-charset", "enctype")+">"); out.println(JavaExtensions.toString(body)); out.print("</form>"); }
public static void _form(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { ActionDefinition actionDef = (ActionDefinition) args.get("arg"); if (actionDef == null) { actionDef = (ActionDefinition) args.get("action"); } String enctype = (String) args.get("enctype"); if (enctype == null) { enctype = "application/x-www-form-urlencoded"; } if (actionDef.star) { actionDef.method = "POST"; // prefer POST for form .... } if (args.containsKey("method")) { actionDef.method = args.get("method").toString(); } if (!("GET".equals(actionDef.method) || "POST".equals(actionDef.method))) { String separator = actionDef.url.indexOf('?') != -1 ? "&" : "?"; actionDef.url += separator + "x-http-method-override=" + actionDef.method.toUpperCase(); actionDef.method = "POST"; } out.print("<form action=\"" + actionDef.url + "\" method=\"" + actionDef.method.toUpperCase() + "\" accept-charset=\"utf-8\" enctype=\"" + enctype + "\" "+serialize(args, "action", "method", "accept-charset", "enctype")+">"); out.println(JavaExtensions.toString(body)); out.print("</form>"); }
diff --git a/src/main/java/com/mojang/minecraft/gui/HUDScreen.java b/src/main/java/com/mojang/minecraft/gui/HUDScreen.java index 10152c6..3681d8b 100644 --- a/src/main/java/com/mojang/minecraft/gui/HUDScreen.java +++ b/src/main/java/com/mojang/minecraft/gui/HUDScreen.java @@ -1,233 +1,233 @@ package com.mojang.minecraft.gui; import com.mojang.minecraft.ChatLine; import com.mojang.minecraft.Minecraft; import com.mojang.minecraft.gamemode.SurvivalGameMode; import com.mojang.minecraft.level.tile.Block; import com.mojang.minecraft.player.Inventory; import com.mojang.minecraft.render.ShapeRenderer; import com.mojang.minecraft.render.TextureManager; import com.mojang.util.MathHelper; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.List; import java.util.Random; public final class HUDScreen extends Screen { public List chat = new ArrayList(); private Random random = new Random(); private Minecraft mc; public int width; public int height; public String hoveredPlayer = null; public int ticks = 0; public static String Compass = ""; public static String ServerName = ""; public static String UserDetail = ""; public HUDScreen(Minecraft var1, int var2, int var3) { this.mc = var1; this.width = var2 * 240 / var3; this.height = var3 * 240 / var3; } public final void render(float var1, boolean var2, int var3, int var4) { FontRenderer var5 = this.mc.fontRenderer; this.mc.renderer.enableGuiMode(); TextureManager var6 = this.mc.textureManager; GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/gui.png")); ShapeRenderer var7 = ShapeRenderer.instance; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glEnable(3042); Inventory var8 = this.mc.player.inventory; this.imgZ = -90.0F; this.drawImage(this.width / 2 - 91, this.height - 22, 0, 0, 182, 22); this.drawImage(this.width / 2 - 91 - 1 + var8.selected * 20, this.height - 22 - 1, 0, 22, 24, 22); GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/icons.png")); this.drawImage(this.width / 2 - 7, this.height / 2 - 7, 0, 0, 16, 16); boolean var9 = this.mc.player.invulnerableTime / 3 % 2 == 1; if(this.mc.player.invulnerableTime < 10) { var9 = false; } int var10 = this.mc.player.health; int var11 = this.mc.player.lastHealth; this.random.setSeed((long)(this.ticks * 312871)); int var12; int var14; int var15; int var26; if(this.mc.gamemode.isSurvival()) { for(var12 = 0; var12 < 10; ++var12) { byte var13 = 0; if(var9) { var13 = 1; } var14 = this.width / 2 - 91 + (var12 << 3); var15 = this.height - 32; if(var10 <= 4) { var15 += this.random.nextInt(2); } this.drawImage(var14, var15, 16 + var13 * 9, 0, 9, 9); if(var9) { if((var12 << 1) + 1 < var11) { this.drawImage(var14, var15, 70, 0, 9, 9); } if((var12 << 1) + 1 == var11) { this.drawImage(var14, var15, 79, 0, 9, 9); } } if((var12 << 1) + 1 < var10) { this.drawImage(var14, var15, 52, 0, 9, 9); } if((var12 << 1) + 1 == var10) { this.drawImage(var14, var15, 61, 0, 9, 9); } } if(this.mc.player.isUnderWater()) { var12 = (int)Math.ceil((double)(this.mc.player.airSupply - 2) * 10.0D / 300.0D); var26 = (int)Math.ceil((double)this.mc.player.airSupply * 10.0D / 300.0D) - var12; for(var14 = 0; var14 < var12 + var26; ++var14) { if(var14 < var12) { this.drawImage(this.width / 2 - 91 + (var14 << 3), this.height - 32 - 9, 16, 18, 9, 9); } else { this.drawImage(this.width / 2 - 91 + (var14 << 3), this.height - 32 - 9, 25, 18, 9, 9); } } } } GL11.glDisable(3042); String var23; for(var12 = 0; var12 < var8.slots.length; ++var12) { var26 = this.width / 2 - 90 + var12 * 20; var14 = this.height - 16; if((var15 = var8.slots[var12]) > 0) { GL11.glPushMatrix(); GL11.glTranslatef((float)var26, (float)var14, -50.0F); if(var8.popTime[var12] > 0) { float var18; float var21 = -MathHelper.sin((var18 = ((float)var8.popTime[var12] - var1) / 5.0F) * var18 * 3.1415927F) * 8.0F; float var19 = MathHelper.sin(var18 * var18 * 3.1415927F) + 1.0F; float var16 = MathHelper.sin(var18 * 3.1415927F) + 1.0F; GL11.glTranslatef(10.0F, var21 + 10.0F, 0.0F); GL11.glScalef(var19, var16, 1.0F); GL11.glTranslatef(-10.0F, -10.0F, 0.0F); } GL11.glScalef(10.0F, 10.0F, 10.0F); GL11.glTranslatef(1.0F, 0.5F, 0.0F); GL11.glRotatef(-30.0F, 1.0F, 0.0F, 0.0F); GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(-1.5F, 0.5F, 0.5F); GL11.glScalef(-1.0F, -1.0F, -1.0F); int var20 = var6.load("/terrain.png"); GL11.glBindTexture(3553, var20); var7.begin(); Block.blocks[var15].renderFullbright(var7); var7.end(); GL11.glPopMatrix(); if(var8.count[var12] > 1) { var23 = "" + var8.count[var12]; var5.render(var23, var26 + 19 - var5.getWidth(var23), var14 + 6, 16777215); } } } var5.render("ClassiCube 0.1", 2, 2, 16777215); // lol fuck that. if(this.mc.settings.showFrameRate) { var5.render(this.mc.debug, 2, 22, 16777215); var5.render(Compass, this.width - (var5.getWidth(Compass) + 2), 12, 16777215); var5.render(ServerName, this.width - (var5.getWidth(ServerName) + 2), 2, 16777215); var5.render(UserDetail, this.width - (var5.getWidth(UserDetail) + 2), 24, 16777215); if(this.mc.player.flyingMode && !this.mc.player.noPhysics) var5.render("Fly: ON.", 2, 32, 16777215); else if(this.mc.player.flyingMode && this.mc.player.noPhysics) var5.render("Fly: ON. NoClip: ON.", 2, 32, 16777215); else if (this.mc.player.noPhysics && !this.mc.player.flyingMode){ var5.render("NoClip: ON.", 2, 32, 16777215); } } if(this.mc.gamemode instanceof SurvivalGameMode) { String var24 = "Score: &e" + this.mc.player.getScore(); var5.render(var24, this.width - var5.getWidth(var24) - 2, 2, 16777215); var5.render("Arrows: " + this.mc.player.arrows, this.width / 2 + 8, this.height - 33, 16777215); } byte var25 = 10; boolean var27 = false; - if(this.mc.currentScreen instanceof ChatInputScreen) { + if(this.mc.currentScreen instanceof ChatInputScreenExtension) { var25 = 20; var27 = true; } for(var14 = 0; var14 < this.chat.size() && var14 < var25; ++var14) { if(((ChatLine)this.chat.get(var14)).time < 200 || var27) { var5.render(((ChatLine)this.chat.get(var14)).message, 2, this.height - 8 - var14 * 9 - 20, 16777215); } } var14 = this.width / 2; var15 = this.height / 2; this.hoveredPlayer = null; if(Keyboard.isKeyDown(15) && this.mc.networkManager != null && this.mc.networkManager.isConnected()) { List var22 = this.mc.networkManager.getPlayers(); GL11.glEnable(3042); GL11.glDisable(3553); GL11.glBlendFunc(770, 771); GL11.glBegin(7); GL11.glColor4f(0.0F, 0.0F, 0.0F, 0.7F); GL11.glVertex2f((float)(var14 + 128), (float)(var15 - 68 - 12)); GL11.glVertex2f((float)(var14 - 128), (float)(var15 - 68 - 12)); GL11.glColor4f(0.2F, 0.2F, 0.2F, 0.8F); GL11.glVertex2f((float)(var14 - 128), (float)(var15 + 68)); GL11.glVertex2f((float)(var14 + 128), (float)(var15 + 68)); GL11.glEnd(); GL11.glDisable(3042); GL11.glEnable(3553); var23 = "Connected players:"; var5.render(var23, var14 - var5.getWidth(var23) / 2, var15 - 64 - 12, 16777215); for(var11 = 0; var11 < var22.size(); ++var11) { int var28 = var14 + var11 % 2 * 120 - 120; int var17 = var15 - 64 + (var11 / 2 << 3); if(var2 && var3 >= var28 && var4 >= var17 && var3 < var28 + 120 && var4 < var17 + 8) { this.hoveredPlayer = (String)var22.get(var11); var5.renderNoShadow((String)var22.get(var11), var28 + 2, var17, 16777215); } else { var5.renderNoShadow((String)var22.get(var11), var28, var17, 15658734); } } } } public final void addChat(String var1) { if(var1.contains("^detail.user=")){ Compass = var1.replace("^detail.user=", ""); //this.mc.fontRenderer.render( var1, (this.mc.width- this.mc.fontRenderer.getWidth(var1)) - 2, this.mc.height - 12, 14737632); return; } this.chat.add(0, new ChatLine(var1)); while(this.chat.size() > 50) { this.chat.remove(this.chat.size() - 1); } } }
true
true
public final void render(float var1, boolean var2, int var3, int var4) { FontRenderer var5 = this.mc.fontRenderer; this.mc.renderer.enableGuiMode(); TextureManager var6 = this.mc.textureManager; GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/gui.png")); ShapeRenderer var7 = ShapeRenderer.instance; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glEnable(3042); Inventory var8 = this.mc.player.inventory; this.imgZ = -90.0F; this.drawImage(this.width / 2 - 91, this.height - 22, 0, 0, 182, 22); this.drawImage(this.width / 2 - 91 - 1 + var8.selected * 20, this.height - 22 - 1, 0, 22, 24, 22); GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/icons.png")); this.drawImage(this.width / 2 - 7, this.height / 2 - 7, 0, 0, 16, 16); boolean var9 = this.mc.player.invulnerableTime / 3 % 2 == 1; if(this.mc.player.invulnerableTime < 10) { var9 = false; } int var10 = this.mc.player.health; int var11 = this.mc.player.lastHealth; this.random.setSeed((long)(this.ticks * 312871)); int var12; int var14; int var15; int var26; if(this.mc.gamemode.isSurvival()) { for(var12 = 0; var12 < 10; ++var12) { byte var13 = 0; if(var9) { var13 = 1; } var14 = this.width / 2 - 91 + (var12 << 3); var15 = this.height - 32; if(var10 <= 4) { var15 += this.random.nextInt(2); } this.drawImage(var14, var15, 16 + var13 * 9, 0, 9, 9); if(var9) { if((var12 << 1) + 1 < var11) { this.drawImage(var14, var15, 70, 0, 9, 9); } if((var12 << 1) + 1 == var11) { this.drawImage(var14, var15, 79, 0, 9, 9); } } if((var12 << 1) + 1 < var10) { this.drawImage(var14, var15, 52, 0, 9, 9); } if((var12 << 1) + 1 == var10) { this.drawImage(var14, var15, 61, 0, 9, 9); } } if(this.mc.player.isUnderWater()) { var12 = (int)Math.ceil((double)(this.mc.player.airSupply - 2) * 10.0D / 300.0D); var26 = (int)Math.ceil((double)this.mc.player.airSupply * 10.0D / 300.0D) - var12; for(var14 = 0; var14 < var12 + var26; ++var14) { if(var14 < var12) { this.drawImage(this.width / 2 - 91 + (var14 << 3), this.height - 32 - 9, 16, 18, 9, 9); } else { this.drawImage(this.width / 2 - 91 + (var14 << 3), this.height - 32 - 9, 25, 18, 9, 9); } } } } GL11.glDisable(3042); String var23; for(var12 = 0; var12 < var8.slots.length; ++var12) { var26 = this.width / 2 - 90 + var12 * 20; var14 = this.height - 16; if((var15 = var8.slots[var12]) > 0) { GL11.glPushMatrix(); GL11.glTranslatef((float)var26, (float)var14, -50.0F); if(var8.popTime[var12] > 0) { float var18; float var21 = -MathHelper.sin((var18 = ((float)var8.popTime[var12] - var1) / 5.0F) * var18 * 3.1415927F) * 8.0F; float var19 = MathHelper.sin(var18 * var18 * 3.1415927F) + 1.0F; float var16 = MathHelper.sin(var18 * 3.1415927F) + 1.0F; GL11.glTranslatef(10.0F, var21 + 10.0F, 0.0F); GL11.glScalef(var19, var16, 1.0F); GL11.glTranslatef(-10.0F, -10.0F, 0.0F); } GL11.glScalef(10.0F, 10.0F, 10.0F); GL11.glTranslatef(1.0F, 0.5F, 0.0F); GL11.glRotatef(-30.0F, 1.0F, 0.0F, 0.0F); GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(-1.5F, 0.5F, 0.5F); GL11.glScalef(-1.0F, -1.0F, -1.0F); int var20 = var6.load("/terrain.png"); GL11.glBindTexture(3553, var20); var7.begin(); Block.blocks[var15].renderFullbright(var7); var7.end(); GL11.glPopMatrix(); if(var8.count[var12] > 1) { var23 = "" + var8.count[var12]; var5.render(var23, var26 + 19 - var5.getWidth(var23), var14 + 6, 16777215); } } } var5.render("ClassiCube 0.1", 2, 2, 16777215); // lol fuck that. if(this.mc.settings.showFrameRate) { var5.render(this.mc.debug, 2, 22, 16777215); var5.render(Compass, this.width - (var5.getWidth(Compass) + 2), 12, 16777215); var5.render(ServerName, this.width - (var5.getWidth(ServerName) + 2), 2, 16777215); var5.render(UserDetail, this.width - (var5.getWidth(UserDetail) + 2), 24, 16777215); if(this.mc.player.flyingMode && !this.mc.player.noPhysics) var5.render("Fly: ON.", 2, 32, 16777215); else if(this.mc.player.flyingMode && this.mc.player.noPhysics) var5.render("Fly: ON. NoClip: ON.", 2, 32, 16777215); else if (this.mc.player.noPhysics && !this.mc.player.flyingMode){ var5.render("NoClip: ON.", 2, 32, 16777215); } } if(this.mc.gamemode instanceof SurvivalGameMode) { String var24 = "Score: &e" + this.mc.player.getScore(); var5.render(var24, this.width - var5.getWidth(var24) - 2, 2, 16777215); var5.render("Arrows: " + this.mc.player.arrows, this.width / 2 + 8, this.height - 33, 16777215); } byte var25 = 10; boolean var27 = false; if(this.mc.currentScreen instanceof ChatInputScreen) { var25 = 20; var27 = true; } for(var14 = 0; var14 < this.chat.size() && var14 < var25; ++var14) { if(((ChatLine)this.chat.get(var14)).time < 200 || var27) { var5.render(((ChatLine)this.chat.get(var14)).message, 2, this.height - 8 - var14 * 9 - 20, 16777215); } } var14 = this.width / 2; var15 = this.height / 2; this.hoveredPlayer = null; if(Keyboard.isKeyDown(15) && this.mc.networkManager != null && this.mc.networkManager.isConnected()) { List var22 = this.mc.networkManager.getPlayers(); GL11.glEnable(3042); GL11.glDisable(3553); GL11.glBlendFunc(770, 771); GL11.glBegin(7); GL11.glColor4f(0.0F, 0.0F, 0.0F, 0.7F); GL11.glVertex2f((float)(var14 + 128), (float)(var15 - 68 - 12)); GL11.glVertex2f((float)(var14 - 128), (float)(var15 - 68 - 12)); GL11.glColor4f(0.2F, 0.2F, 0.2F, 0.8F); GL11.glVertex2f((float)(var14 - 128), (float)(var15 + 68)); GL11.glVertex2f((float)(var14 + 128), (float)(var15 + 68)); GL11.glEnd(); GL11.glDisable(3042); GL11.glEnable(3553); var23 = "Connected players:"; var5.render(var23, var14 - var5.getWidth(var23) / 2, var15 - 64 - 12, 16777215); for(var11 = 0; var11 < var22.size(); ++var11) { int var28 = var14 + var11 % 2 * 120 - 120; int var17 = var15 - 64 + (var11 / 2 << 3); if(var2 && var3 >= var28 && var4 >= var17 && var3 < var28 + 120 && var4 < var17 + 8) { this.hoveredPlayer = (String)var22.get(var11); var5.renderNoShadow((String)var22.get(var11), var28 + 2, var17, 16777215); } else { var5.renderNoShadow((String)var22.get(var11), var28, var17, 15658734); } } } }
public final void render(float var1, boolean var2, int var3, int var4) { FontRenderer var5 = this.mc.fontRenderer; this.mc.renderer.enableGuiMode(); TextureManager var6 = this.mc.textureManager; GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/gui.png")); ShapeRenderer var7 = ShapeRenderer.instance; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glEnable(3042); Inventory var8 = this.mc.player.inventory; this.imgZ = -90.0F; this.drawImage(this.width / 2 - 91, this.height - 22, 0, 0, 182, 22); this.drawImage(this.width / 2 - 91 - 1 + var8.selected * 20, this.height - 22 - 1, 0, 22, 24, 22); GL11.glBindTexture(3553, this.mc.textureManager.load("/gui/icons.png")); this.drawImage(this.width / 2 - 7, this.height / 2 - 7, 0, 0, 16, 16); boolean var9 = this.mc.player.invulnerableTime / 3 % 2 == 1; if(this.mc.player.invulnerableTime < 10) { var9 = false; } int var10 = this.mc.player.health; int var11 = this.mc.player.lastHealth; this.random.setSeed((long)(this.ticks * 312871)); int var12; int var14; int var15; int var26; if(this.mc.gamemode.isSurvival()) { for(var12 = 0; var12 < 10; ++var12) { byte var13 = 0; if(var9) { var13 = 1; } var14 = this.width / 2 - 91 + (var12 << 3); var15 = this.height - 32; if(var10 <= 4) { var15 += this.random.nextInt(2); } this.drawImage(var14, var15, 16 + var13 * 9, 0, 9, 9); if(var9) { if((var12 << 1) + 1 < var11) { this.drawImage(var14, var15, 70, 0, 9, 9); } if((var12 << 1) + 1 == var11) { this.drawImage(var14, var15, 79, 0, 9, 9); } } if((var12 << 1) + 1 < var10) { this.drawImage(var14, var15, 52, 0, 9, 9); } if((var12 << 1) + 1 == var10) { this.drawImage(var14, var15, 61, 0, 9, 9); } } if(this.mc.player.isUnderWater()) { var12 = (int)Math.ceil((double)(this.mc.player.airSupply - 2) * 10.0D / 300.0D); var26 = (int)Math.ceil((double)this.mc.player.airSupply * 10.0D / 300.0D) - var12; for(var14 = 0; var14 < var12 + var26; ++var14) { if(var14 < var12) { this.drawImage(this.width / 2 - 91 + (var14 << 3), this.height - 32 - 9, 16, 18, 9, 9); } else { this.drawImage(this.width / 2 - 91 + (var14 << 3), this.height - 32 - 9, 25, 18, 9, 9); } } } } GL11.glDisable(3042); String var23; for(var12 = 0; var12 < var8.slots.length; ++var12) { var26 = this.width / 2 - 90 + var12 * 20; var14 = this.height - 16; if((var15 = var8.slots[var12]) > 0) { GL11.glPushMatrix(); GL11.glTranslatef((float)var26, (float)var14, -50.0F); if(var8.popTime[var12] > 0) { float var18; float var21 = -MathHelper.sin((var18 = ((float)var8.popTime[var12] - var1) / 5.0F) * var18 * 3.1415927F) * 8.0F; float var19 = MathHelper.sin(var18 * var18 * 3.1415927F) + 1.0F; float var16 = MathHelper.sin(var18 * 3.1415927F) + 1.0F; GL11.glTranslatef(10.0F, var21 + 10.0F, 0.0F); GL11.glScalef(var19, var16, 1.0F); GL11.glTranslatef(-10.0F, -10.0F, 0.0F); } GL11.glScalef(10.0F, 10.0F, 10.0F); GL11.glTranslatef(1.0F, 0.5F, 0.0F); GL11.glRotatef(-30.0F, 1.0F, 0.0F, 0.0F); GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(-1.5F, 0.5F, 0.5F); GL11.glScalef(-1.0F, -1.0F, -1.0F); int var20 = var6.load("/terrain.png"); GL11.glBindTexture(3553, var20); var7.begin(); Block.blocks[var15].renderFullbright(var7); var7.end(); GL11.glPopMatrix(); if(var8.count[var12] > 1) { var23 = "" + var8.count[var12]; var5.render(var23, var26 + 19 - var5.getWidth(var23), var14 + 6, 16777215); } } } var5.render("ClassiCube 0.1", 2, 2, 16777215); // lol fuck that. if(this.mc.settings.showFrameRate) { var5.render(this.mc.debug, 2, 22, 16777215); var5.render(Compass, this.width - (var5.getWidth(Compass) + 2), 12, 16777215); var5.render(ServerName, this.width - (var5.getWidth(ServerName) + 2), 2, 16777215); var5.render(UserDetail, this.width - (var5.getWidth(UserDetail) + 2), 24, 16777215); if(this.mc.player.flyingMode && !this.mc.player.noPhysics) var5.render("Fly: ON.", 2, 32, 16777215); else if(this.mc.player.flyingMode && this.mc.player.noPhysics) var5.render("Fly: ON. NoClip: ON.", 2, 32, 16777215); else if (this.mc.player.noPhysics && !this.mc.player.flyingMode){ var5.render("NoClip: ON.", 2, 32, 16777215); } } if(this.mc.gamemode instanceof SurvivalGameMode) { String var24 = "Score: &e" + this.mc.player.getScore(); var5.render(var24, this.width - var5.getWidth(var24) - 2, 2, 16777215); var5.render("Arrows: " + this.mc.player.arrows, this.width / 2 + 8, this.height - 33, 16777215); } byte var25 = 10; boolean var27 = false; if(this.mc.currentScreen instanceof ChatInputScreenExtension) { var25 = 20; var27 = true; } for(var14 = 0; var14 < this.chat.size() && var14 < var25; ++var14) { if(((ChatLine)this.chat.get(var14)).time < 200 || var27) { var5.render(((ChatLine)this.chat.get(var14)).message, 2, this.height - 8 - var14 * 9 - 20, 16777215); } } var14 = this.width / 2; var15 = this.height / 2; this.hoveredPlayer = null; if(Keyboard.isKeyDown(15) && this.mc.networkManager != null && this.mc.networkManager.isConnected()) { List var22 = this.mc.networkManager.getPlayers(); GL11.glEnable(3042); GL11.glDisable(3553); GL11.glBlendFunc(770, 771); GL11.glBegin(7); GL11.glColor4f(0.0F, 0.0F, 0.0F, 0.7F); GL11.glVertex2f((float)(var14 + 128), (float)(var15 - 68 - 12)); GL11.glVertex2f((float)(var14 - 128), (float)(var15 - 68 - 12)); GL11.glColor4f(0.2F, 0.2F, 0.2F, 0.8F); GL11.glVertex2f((float)(var14 - 128), (float)(var15 + 68)); GL11.glVertex2f((float)(var14 + 128), (float)(var15 + 68)); GL11.glEnd(); GL11.glDisable(3042); GL11.glEnable(3553); var23 = "Connected players:"; var5.render(var23, var14 - var5.getWidth(var23) / 2, var15 - 64 - 12, 16777215); for(var11 = 0; var11 < var22.size(); ++var11) { int var28 = var14 + var11 % 2 * 120 - 120; int var17 = var15 - 64 + (var11 / 2 << 3); if(var2 && var3 >= var28 && var4 >= var17 && var3 < var28 + 120 && var4 < var17 + 8) { this.hoveredPlayer = (String)var22.get(var11); var5.renderNoShadow((String)var22.get(var11), var28 + 2, var17, 16777215); } else { var5.renderNoShadow((String)var22.get(var11), var28, var17, 15658734); } } } }
diff --git a/src/plugins/WebOfTrust/WebOfTrust.java b/src/plugins/WebOfTrust/WebOfTrust.java index a2637ecc..bf4999ed 100644 --- a/src/plugins/WebOfTrust/WebOfTrust.java +++ b/src/plugins/WebOfTrust/WebOfTrust.java @@ -1,3573 +1,3575 @@ /* This code is part of WoT, a plugin for Freenet. It is distributed * under the GNU General Public License, version 2 (or at your option * any later version). See http://www.gnu.org/ for details of the GPL. */ package plugins.WebOfTrust; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Random; import plugins.WebOfTrust.Identity.FetchState; import plugins.WebOfTrust.Identity.IdentityID; import plugins.WebOfTrust.Score.ScoreID; import plugins.WebOfTrust.Trust.TrustID; import plugins.WebOfTrust.exceptions.DuplicateIdentityException; import plugins.WebOfTrust.exceptions.DuplicateScoreException; import plugins.WebOfTrust.exceptions.DuplicateTrustException; import plugins.WebOfTrust.exceptions.InvalidParameterException; import plugins.WebOfTrust.exceptions.NotInTrustTreeException; import plugins.WebOfTrust.exceptions.NotTrustedException; import plugins.WebOfTrust.exceptions.UnknownIdentityException; import plugins.WebOfTrust.introduction.IntroductionClient; import plugins.WebOfTrust.introduction.IntroductionPuzzle; import plugins.WebOfTrust.introduction.IntroductionPuzzleStore; import plugins.WebOfTrust.introduction.IntroductionServer; import plugins.WebOfTrust.introduction.OwnIntroductionPuzzle; import plugins.WebOfTrust.ui.fcp.FCPInterface; import plugins.WebOfTrust.ui.web.WebInterface; import com.db4o.Db4o; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.defragment.Defragment; import com.db4o.defragment.DefragmentConfig; import com.db4o.ext.ExtObjectContainer; import com.db4o.query.Query; import com.db4o.reflect.jdk.JdkReflector; import freenet.keys.FreenetURI; import freenet.keys.USK; import freenet.l10n.BaseL10n; import freenet.l10n.BaseL10n.LANGUAGE; import freenet.l10n.PluginL10n; import freenet.node.RequestClient; import freenet.pluginmanager.FredPlugin; import freenet.pluginmanager.FredPluginBaseL10n; import freenet.pluginmanager.FredPluginFCP; import freenet.pluginmanager.FredPluginL10n; import freenet.pluginmanager.FredPluginRealVersioned; import freenet.pluginmanager.FredPluginThreadless; import freenet.pluginmanager.FredPluginVersioned; import freenet.pluginmanager.PluginReplySender; import freenet.pluginmanager.PluginRespirator; import freenet.support.CurrentTimeUTC; import freenet.support.Logger; import freenet.support.Logger.LogLevel; import freenet.support.SimpleFieldSet; import freenet.support.SizeUtil; import freenet.support.api.Bucket; import freenet.support.io.FileUtil; /** * A web of trust plugin based on Freenet. * * @author xor ([email protected]), Julien Cornuwel ([email protected]) */ public class WebOfTrust implements FredPlugin, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginRealVersioned, FredPluginL10n, FredPluginBaseL10n { /* Constants */ public static final boolean FAST_DEBUG_MODE = false; /** The relative path of the plugin on Freenet's web interface */ public static final String SELF_URI = "/WebOfTrust"; /** Package-private method to allow unit tests to bypass some assert()s */ /** * The "name" of this web of trust. It is included in the document name of identity URIs. For an example, see the SEED_IDENTITIES * constant below. The purpose of this constant is to allow anyone to create his own custom web of trust which is completely disconnected * from the "official" web of trust of the Freenet project. It is also used as the session cookie namespace. */ public static final String WOT_NAME = "WebOfTrust"; public static final String DATABASE_FILENAME = WOT_NAME + ".db4o"; public static final int DATABASE_FORMAT_VERSION = 2; /** * The official seed identities of the WoT plugin: If a newbie wants to download the whole offficial web of trust, he needs at least one * trust list from an identity which is well-connected to the web of trust. To prevent newbies from having to add this identity manually, * the Freenet development team provides a list of seed identities - each of them is one of the developers. */ private static final String[] SEED_IDENTITIES = new String[] { "USK@QeTBVWTwBldfI-lrF~xf0nqFVDdQoSUghT~PvhyJ1NE,OjEywGD063La2H-IihD7iYtZm3rC0BP6UTvvwyF5Zh4,AQACAAE/WebOfTrust/1344", // xor "USK@z9dv7wqsxIBCiFLW7VijMGXD9Gl-EXAqBAwzQ4aq26s,4Uvc~Fjw3i9toGeQuBkDARUV5mF7OTKoAhqOA9LpNdo,AQACAAE/WebOfTrust/1270", // Toad "USK@o2~q8EMoBkCNEgzLUL97hLPdddco9ix1oAnEa~VzZtg,X~vTpL2LSyKvwQoYBx~eleI2RF6QzYJpzuenfcKDKBM,AQACAAE/WebOfTrust/9379", // Bombe // "USK@cI~w2hrvvyUa1E6PhJ9j5cCoG1xmxSooi7Nez4V2Gd4,A3ArC3rrJBHgAJV~LlwY9kgxM8kUR2pVYXbhGFtid78,AQACAAE/WebOfTrust/19", // TheSeeker. Disabled because he is using LCWoT and it does not support identity introduction ATM. "USK@D3MrAR-AVMqKJRjXnpKW2guW9z1mw5GZ9BB15mYVkVc,xgddjFHx2S~5U6PeFkwqO5V~1gZngFLoM-xaoMKSBI8,AQACAAE/WebOfTrust/4959", // zidel }; /* References from the node */ /** The node's interface to connect the plugin with the node, needed for retrieval of all other interfaces */ private PluginRespirator mPR; private static PluginL10n l10n; /* References from the plugin itself */ /* Database & configuration of the plugin */ private ExtObjectContainer mDB; private Configuration mConfig; private IntroductionPuzzleStore mPuzzleStore; /** Used for exporting identities, identity introductions and introduction puzzles to XML and importing them from XML. */ private XMLTransformer mXMLTransformer; private RequestClient mRequestClient; /* Worker objects which actually run the plugin */ /** * Clients can subscribe to certain events such as identity creation, trust changes, etc. with the {@link SubscriptionManager} */ private SubscriptionManager mSubscriptionManager; /** * Periodically wakes up and inserts any OwnIdentity which needs to be inserted. */ private IdentityInserter mInserter; /** * Fetches identities when it is told to do so by the plugin: * - At startup, all known identities are fetched * - When a new identity is received from a trust list it is fetched * - When a new identity is received by the IntrouductionServer it is fetched * - When an identity is manually added it is also fetched. * - ... */ private IdentityFetcher mFetcher; /** * Uploads captchas belonging to our own identities which others can solve to get on the trust list of them. Checks whether someone * uploaded solutions for them periodically and adds the new identities if a solution is received. */ private IntroductionServer mIntroductionServer; /** * Downloads captchas which the user can solve to announce his identities on other people's trust lists, provides the interface for * the UI to obtain the captchas and enter solutions. Uploads the solutions if the UI enters them. */ private IntroductionClient mIntroductionClient; /* Actual data of the WoT */ private boolean mFullScoreComputationNeeded = false; private boolean mTrustListImportInProgress = false; /* User interfaces */ private WebInterface mWebInterface; private FCPInterface mFCPInterface; /* Statistics */ private int mFullScoreRecomputationCount = 0; private long mFullScoreRecomputationMilliseconds = 0; private int mIncrementalScoreRecomputationCount = 0; private long mIncrementalScoreRecomputationMilliseconds = 0; /* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */ private static transient volatile boolean logDEBUG = false; private static transient volatile boolean logMINOR = false; static { Logger.registerClass(WebOfTrust.class); } public void runPlugin(PluginRespirator myPR) { try { Logger.normal(this, "Web Of Trust plugin version " + Version.getMarketingVersion() + " starting up..."); /* Catpcha generation needs headless mode on linux */ System.setProperty("java.awt.headless", "true"); mPR = myPR; /* TODO: This can be used for clean copies of the database to get rid of corrupted internal db4o structures. /* We should provide an option on the web interface to run this once during next startup and switch to the cloned database */ // cloneDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME), new File(getUserDataDirectory(), DATABASE_FILENAME + ".clone")); mDB = openDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() > WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("The WoT plugin's database format is newer than the WoT plugin which is being used."); mSubscriptionManager = new SubscriptionManager(this); mPuzzleStore = new IntroductionPuzzleStore(this); // Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager while this is executing. upgradeDB(); mXMLTransformer = new XMLTransformer(this); mRequestClient = new RequestClient() { public boolean persistent() { return false; } public void removeFrom(ObjectContainer container) { throw new UnsupportedOperationException(); } public boolean realTimeFlag() { return false; } }; mInserter = new IdentityInserter(this); mFetcher = new IdentityFetcher(this, getPluginRespirator()); // We only do this if debug logging is enabled since the integrity verification cannot repair anything anyway, // if the user does not read his logs there is no need to check the integrity. // TODO: Do this once every few startups and notify the user in the web ui if errors are found. if(logDEBUG) verifyDatabaseIntegrity(); // TODO: Only do this once every few startups once we are certain that score computation does not have any serious bugs. verifyAndCorrectStoredScores(); // Database is up now, integrity is checked. We can start to actually do stuff // TODO: This can be used for doing backups. Implement auto backup, maybe once a week or month //backupDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME + ".backup")); mSubscriptionManager.start(); createSeedIdentities(); Logger.normal(this, "Starting fetches of all identities..."); synchronized(this) { synchronized(mFetcher) { for(Identity identity : getAllIdentities()) { if(shouldFetchIdentity(identity)) { try { mFetcher.fetch(identity.getID()); } catch(Exception e) { Logger.error(this, "Fetching identity failed!", e); } } } } } mInserter.start(); mIntroductionServer = new IntroductionServer(this, mFetcher); mIntroductionServer.start(); mIntroductionClient = new IntroductionClient(this); mIntroductionClient.start(); mWebInterface = new WebInterface(this, SELF_URI); mFCPInterface = new FCPInterface(this); Logger.normal(this, "Web Of Trust plugin starting up completed."); } catch(RuntimeException e){ Logger.error(this, "Error during startup", e); /* We call it so the database is properly closed */ terminate(); throw e; } } /** * Constructor for being used by the node and unit tests. Does not do anything. */ public WebOfTrust() { } /** * Constructor which does not generate an IdentityFetcher, IdentityInster, IntroductionPuzzleStore, user interface, etc. * For use by the unit tests to be able to run WoT without a node. * @param databaseFilename The filename of the database. */ public WebOfTrust(String databaseFilename) { mDB = openDatabase(new File(databaseFilename)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Database format version mismatch. Found: " + mConfig.getDatabaseFormatVersion() + "; expected: " + WebOfTrust.DATABASE_FORMAT_VERSION); mPuzzleStore = new IntroductionPuzzleStore(this); mSubscriptionManager = new SubscriptionManager(this); mFetcher = new IdentityFetcher(this, null); } private File getUserDataDirectory() { final File wotDirectory = new File(mPR.getNode().getUserDir(), WOT_NAME); if(!wotDirectory.exists() && !wotDirectory.mkdir()) throw new RuntimeException("Unable to create directory " + wotDirectory); return wotDirectory; } private com.db4o.config.Configuration getNewDatabaseConfiguration() { com.db4o.config.Configuration cfg = Db4o.newConfiguration(); // Required config options: cfg.reflectWith(new JdkReflector(getPluginClassLoader())); // TODO: Optimization: We do explicit activation everywhere. We could change this to 0 and test whether everything still works. // Ideally, we would benchmark both 0 and 1 and make it configurable. cfg.activationDepth(1); cfg.updateDepth(1); // This must not be changed: We only activate(this, 1) before store(this). Logger.normal(this, "Default activation depth: " + cfg.activationDepth()); cfg.exceptionsOnNotStorable(true); // The shutdown hook does auto-commit. We do NOT want auto-commit: if a transaction hasn't commit()ed, it's not safe to commit it. cfg.automaticShutDown(false); // Performance config options: cfg.callbacks(false); // We don't use callbacks yet. TODO: Investigate whether we might want to use them cfg.classActivationDepthConfigurable(false); // Registration of indices (also performance) // ATTENTION: Also update cloneDatabase() when adding new classes! @SuppressWarnings("unchecked") final Class<? extends Persistent>[] persistentClasses = new Class[] { Configuration.class, Identity.class, OwnIdentity.class, Trust.class, Score.class, IdentityFetcher.IdentityFetcherCommand.class, IdentityFetcher.AbortFetchCommand.class, IdentityFetcher.StartFetchCommand.class, IdentityFetcher.UpdateEditionHintCommand.class, SubscriptionManager.Subscription.class, SubscriptionManager.IdentitiesSubscription.class, SubscriptionManager.ScoresSubscription.class, SubscriptionManager.TrustsSubscription.class, SubscriptionManager.Notification.class, SubscriptionManager.InitialSynchronizationNotification.class, SubscriptionManager.IdentityChangedNotification.class, SubscriptionManager.ScoreChangedNotification.class, SubscriptionManager.TrustChangedNotification.class, IntroductionPuzzle.class, OwnIntroductionPuzzle.class }; for(Class<? extends Persistent> clazz : persistentClasses) { boolean classHasIndex = clazz.getAnnotation(Persistent.IndexedClass.class) != null; // TODO: We enable class indexes for all classes to make sure nothing breaks because it is the db4o default, check whether enabling // them only for the classes where we need them does not cause any harm. classHasIndex = true; if(logDEBUG) Logger.debug(this, "Persistent class: " + clazz.getCanonicalName() + "; hasIndex==" + classHasIndex); // TODO: Make very sure that it has no negative side effects if we disable class indices for some classes // Maybe benchmark in comparison to a database which has class indices enabled for ALL classes. cfg.objectClass(clazz).indexed(classHasIndex); // Check the class' fields for @IndexedField annotations for(Field field : clazz.getDeclaredFields()) { if(field.getAnnotation(Persistent.IndexedField.class) != null) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + field.getName()); cfg.objectClass(clazz).objectField(field.getName()).indexed(true); } } // Check whether the class itself has an @IndexedField annotation final Persistent.IndexedField annotation = clazz.getAnnotation(Persistent.IndexedField.class); if(annotation != null) { for(String fieldName : annotation.names()) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + fieldName); cfg.objectClass(clazz).objectField(fieldName).indexed(true); } } } // TODO: We should check whether db4o inherits the indexed attribute to child classes, for example for this one: // Unforunately, db4o does not provide any way to query the indexed() property of fields, you can only set it // We might figure out whether inheritance works by writing a benchmark. return cfg; } private synchronized void restoreDatabaseBackup(File databaseFile, File backupFile) throws IOException { Logger.warning(this, "Trying to restore database backup: " + backupFile.getAbsolutePath()); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(backupFile.exists()) { try { FileUtil.secureDelete(databaseFile, mPR.getNode().fastWeakRandom); } catch(IOException e) { Logger.warning(this, "Deleting of the database failed: " + databaseFile.getAbsolutePath()); } if(backupFile.renameTo(databaseFile)) { Logger.warning(this, "Backup restored!"); } else { throw new IOException("Unable to rename backup file back to database file: " + databaseFile.getAbsolutePath()); } } else { throw new IOException("Cannot restore backup, it does not exist!"); } } private synchronized void defragmentDatabase(File databaseFile) throws IOException { Logger.normal(this, "Defragmenting database ..."); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(mPR == null) { Logger.normal(this, "No PluginRespirator found, probably running as unit test, not defragmenting."); return; } final Random random = mPR.getNode().fastWeakRandom; // Open it first, because defrag will throw if it needs to upgrade the file. { final ObjectContainer database = Db4o.openFile(getNewDatabaseConfiguration(), databaseFile.getAbsolutePath()); // Db4o will throw during defragmentation if new fields were added to classes and we didn't initialize their values on existing // objects before defragmenting. So we just don't defragment if the database format version has changed. final boolean canDefragment = peekDatabaseFormatVersion(this, database.ext()) == WebOfTrust.DATABASE_FORMAT_VERSION; while(!database.close()); if(!canDefragment) { Logger.normal(this, "Not defragmenting, database format version changed!"); return; } if(!databaseFile.exists()) { Logger.error(this, "Database file does not exist after openFile: " + databaseFile.getAbsolutePath()); return; } } final File backupFile = new File(databaseFile.getAbsolutePath() + ".backup"); if(backupFile.exists()) { Logger.error(this, "Not defragmenting database: Backup file exists, maybe the node was shot during defrag: " + backupFile.getAbsolutePath()); return; } final File tmpFile = new File(databaseFile.getAbsolutePath() + ".temp"); FileUtil.secureDelete(tmpFile, random); /* As opposed to the default, BTreeIDMapping uses an on-disk file instead of in-memory for mapping IDs. /* Reduces memory usage during defragmentation while being slower. /* However as of db4o 7.4.63.11890, it is bugged and prevents defragmentation from succeeding for my database, so we don't use it for now. */ final DefragmentConfig config = new DefragmentConfig(databaseFile.getAbsolutePath(), backupFile.getAbsolutePath() // ,new BTreeIDMapping(tmpFile.getAbsolutePath()) ); /* Delete classes which are not known to the classloader anymore - We do NOT do this because: /* - It is buggy and causes exceptions often as of db4o 7.4.63.11890 /* - WOT has always had proper database upgrade code (function upgradeDB()) and does not rely on automatic schema evolution. /* If we need to get rid of certain objects we should do it in the database upgrade code, */ // config.storedClassFilter(new AvailableClassFilter()); config.db4oConfig(getNewDatabaseConfiguration()); try { Defragment.defrag(config); } catch (Exception e) { Logger.error(this, "Defragment failed", e); try { restoreDatabaseBackup(databaseFile, backupFile); return; } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e); } } final long oldSize = backupFile.length(); final long newSize = databaseFile.length(); if(newSize <= 0) { Logger.error(this, "Defrag produced an empty file! Trying to restore old database file..."); databaseFile.delete(); try { restoreDatabaseBackup(databaseFile, backupFile); } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e2); } } else { final double change = 100.0 * (((double)(oldSize - newSize)) / ((double)oldSize)); FileUtil.secureDelete(tmpFile, random); FileUtil.secureDelete(backupFile, random); Logger.normal(this, "Defragment completed. "+SizeUtil.formatSize(oldSize)+" ("+oldSize+") -> " +SizeUtil.formatSize(newSize)+" ("+newSize+") ("+(int)change+"% shrink)"); } } /** * ATTENTION: This function is duplicated in the Freetalk plugin, please backport any changes. * * Initializes the plugin's db4o database. */ private synchronized ExtObjectContainer openDatabase(File file) { Logger.normal(this, "Opening database using db4o " + Db4o.version()); if(mDB != null) throw new RuntimeException("Database is opened already!"); try { defragmentDatabase(file); } catch (IOException e) { throw new RuntimeException(e); } return Db4o.openFile(getNewDatabaseConfiguration(), file.getAbsolutePath()).ext(); } /** * ATTENTION: Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager while this is executing. * It doesn't synchronize on the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager because it assumes that they are not being used yet. * (I didn't upgrade this function to do the locking because it would be much work to test the changes for little benefit) */ @SuppressWarnings("deprecation") private synchronized void upgradeDB() { int databaseVersion = mConfig.getDatabaseFormatVersion(); if(databaseVersion == WebOfTrust.DATABASE_FORMAT_VERSION) return; // Insert upgrade code here. See Freetalk.java for a skeleton. if(databaseVersion == 1) { Logger.normal(this, "Upgrading database version " + databaseVersion); //synchronized(this) { // Already done at function level //synchronized(mPuzzleStore) { // Normally would be needed for deleteWithoutCommit(Identity) but IntroductionClient/Server are not running yet //synchronized(mFetcher) { // Normally would be needed for deleteWithoutCommit(Identity) but the IdentityFetcher is not running yet //synchronized(mSubscriptionManager) { // Normally would be needed for deleteWithoutCommit(Identity) but the SubscriptionManager is not running yet synchronized(Persistent.transactionLock(mDB)) { try { Logger.normal(this, "Generating Score IDs..."); for(Score score : getAllScores()) { score.generateID(); score.storeWithoutCommit(); } Logger.normal(this, "Generating Trust IDs..."); for(Trust trust : getAllTrusts()) { trust.generateID(); trust.storeWithoutCommit(); } Logger.normal(this, "Searching for identities with mixed up insert/request URIs..."); for(Identity identity : getAllIdentities()) { try { USK.create(identity.getRequestURI()); } catch (MalformedURLException e) { if(identity instanceof OwnIdentity) { Logger.error(this, "Insert URI specified as request URI for OwnIdentity, not correcting the URIs as the insert URI" + "might have been published by solving captchas - the identity could be compromised: " + identity); } else { Logger.error(this, "Insert URI specified as request URI for non-own Identity, deleting: " + identity); deleteWithoutCommit(identity); } } } mConfig.setDatabaseFormatVersion(++databaseVersion); mConfig.storeAndCommit(); Logger.normal(this, "Upgraded database to version " + databaseVersion); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } //} } if(databaseVersion != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Your database is too outdated to be upgraded automatically, please create a new one by deleting " + DATABASE_FILENAME + ". Contact the developers if you really need your old data."); } /** * DO NOT USE THIS FUNCTION ON A DATABASE WHICH YOU WANT TO CONTINUE TO USE! * * Debug function for finding object leaks in the database. * * - Deletes all identities in the database - This should delete ALL objects in the database. * - Then it checks for whether any objects still exist - those are leaks. */ private synchronized void checkForDatabaseLeaks() { Logger.normal(this, "Checking for database leaks... This will delete all identities!"); { Logger.debug(this, "Checking FetchState leakage..."); final Query query = mDB.query(); query.constrain(FetchState.class); @SuppressWarnings("unchecked") ObjectSet<FetchState> result = (ObjectSet<FetchState>)query.execute(); for(FetchState state : result) { Logger.debug(this, "Checking " + state); final Query query2 = mDB.query(); query2.constrain(Identity.class); query.descend("mCurrentEditionFetchState").constrain(state).identity(); @SuppressWarnings("unchecked") ObjectSet<FetchState> result2 = (ObjectSet<FetchState>)query.execute(); switch(result2.size()) { case 0: Logger.error(this, "Found leaked FetchState!"); break; case 1: break; default: Logger.error(this, "Found re-used FetchState, count: " + result2.size()); break; } } Logger.debug(this, "Finished checking FetchState leakage, amount:" + result.size()); } Logger.normal(this, "Deleting ALL identities..."); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { beginTrustListImport(); for(Identity identity : getAllIdentities()) { deleteWithoutCommit(identity); } finishTrustListImport(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); // abortTrustListImport() does rollback already // Persistent.checkedRollbackAndThrow(mDB, this, e); throw e; } } } } } Logger.normal(this, "Deleting ALL identities finished."); Query query = mDB.query(); query.constrain(Object.class); @SuppressWarnings("unchecked") ObjectSet<Object> result = query.execute(); for(Object leak : result) { Logger.error(this, "Found leaked object: " + leak); } Logger.warning(this, "Finished checking for database leaks. This database is empty now, delete it."); } private synchronized boolean verifyDatabaseIntegrity() { // Take locks of all objects which deal with persistent stuff because we act upon ALL persistent objects. synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { deleteDuplicateObjects(); deleteOrphanObjects(); Logger.debug(this, "Testing database integrity..."); final Query q = mDB.query(); q.constrain(Persistent.class); boolean result = true; for(final Persistent p : new Persistent.InitializingObjectSet<Persistent>(this, q)) { try { p.startupDatabaseIntegrityTest(); } catch(Exception e) { result = false; try { Logger.error(this, "Integrity test failed for " + p, e); } catch(Exception e2) { Logger.error(this, "Integrity test failed for Persistent of class " + p.getClass(), e); Logger.error(this, "Exception thrown by toString() was:", e2); } } } Logger.debug(this, "Database integrity test finished."); return result; } } } } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Does a backup of the database using db4o's backup mechanism. * * This will NOT fix corrupted internal structures of databases - use cloneDatabase if you need to fix your database. */ private synchronized void backupDatabase(File newDatabase) { Logger.normal(this, "Backing up database to " + newDatabase.getAbsolutePath()); if(newDatabase.exists()) throw new RuntimeException("Target exists already: " + newDatabase.getAbsolutePath()); WebOfTrust backup = null; boolean success = false; try { mDB.backup(newDatabase.getAbsolutePath()); if(logDEBUG) { backup = new WebOfTrust(newDatabase.getAbsolutePath()); // We do not throw to make the clone mechanism more robust in case it is being used for creating backups Logger.debug(this, "Checking database integrity of clone..."); if(backup.verifyDatabaseIntegrity()) Logger.debug(this, "Checking database integrity of clone finished."); else Logger.error(this, "Database integrity check of clone failed!"); Logger.debug(this, "Checking this.equals(clone)..."); if(equals(backup)) Logger.normal(this, "Clone is equal!"); else Logger.error(this, "Clone is not equal!"); } success = true; } finally { if(backup != null) backup.terminate(); if(!success) newDatabase.delete(); } Logger.normal(this, "Backing up database finished."); } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Creates a clone of the source database by reading all objects of it into memory and then writing them out to the target database. * Does NOT copy the Configuration, the IntroductionPuzzles or the IdentityFetcher command queue. * * The difference to backupDatabase is that it does NOT use db4o's backup mechanism, instead it creates the whole database from scratch. * This is useful because the backup mechanism of db4o does nothing but copying the raw file: * It wouldn't fix databases which cannot be defragmented anymore due to internal corruption. * - Databases which were cloned by this function CAN be defragmented even if the original database couldn't. * * HOWEVER this function uses lots of memory as the whole database is copied into memory. */ private synchronized void cloneDatabase(File sourceDatabase, File targetDatabase) { Logger.normal(this, "Cloning " + sourceDatabase.getAbsolutePath() + " to " + targetDatabase.getAbsolutePath()); if(targetDatabase.exists()) throw new RuntimeException("Target exists already: " + targetDatabase.getAbsolutePath()); WebOfTrust original = null; WebOfTrust clone = null; boolean success = false; try { original = new WebOfTrust(sourceDatabase.getAbsolutePath()); // We need to copy all objects into memory and then close & unload the source database before writing the objects to the target one. // - I tried implementing this function in a way where it directly takes the objects from the source database and stores them // in the target database while the source is still open. This did not work: Identity objects disappeared magically, resulting // in Trust objects .storeWithoutCommit throwing "Mandatory object not found" on their associated identities. // FIXME: Clone the Configuration object final HashSet<Identity> allIdentities = new HashSet<Identity>(original.getAllIdentities()); final HashSet<Trust> allTrusts = new HashSet<Trust>(original.getAllTrusts()); final HashSet<Score> allScores = new HashSet<Score>(original.getAllScores()); for(Identity identity : allIdentities) { identity.checkedActivate(16); identity.mWebOfTrust = null; identity.mDB = null; } for(Trust trust : allTrusts) { trust.checkedActivate(16); trust.mWebOfTrust = null; trust.mDB = null; } for(Score score : allScores) { score.checkedActivate(16); score.mWebOfTrust = null; score.mDB = null; } // We don't clone: // - Introduction puzzles because we can just download new ones // - IdentityFetcher commands because they aren't persistent across startups anyway // - Subscription and Notification objects because subscriptions are also not persistent across startups. original.terminate(); original = null; System.gc(); // Now we write out the in-memory copies ... clone = new WebOfTrust(targetDatabase.getAbsolutePath()); for(Identity identity : allIdentities) { identity.initializeTransient(clone); identity.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Trust trust : allTrusts) { trust.initializeTransient(clone); trust.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Score score : allScores) { score.initializeTransient(clone); score.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); // And because cloning is a complex operation we do a mandatory database integrity check Logger.normal(this, "Checking database integrity of clone..."); if(clone.verifyDatabaseIntegrity()) Logger.normal(this, "Checking database integrity of clone finished."); else throw new RuntimeException("Database integrity check of clone failed!"); // ... and also test whether the Web Of Trust is equals() to the clone. This does a deep check of all identities, scores & trusts! original = new WebOfTrust(sourceDatabase.getAbsolutePath()); Logger.normal(this, "Checking original.equals(clone)..."); if(original.equals(clone)) Logger.normal(this, "Clone is equal!"); else throw new RuntimeException("Clone is not equal!"); success = true; } finally { if(original != null) original.terminate(); if(clone != null) clone.terminate(); if(!success) targetDatabase.delete(); } Logger.normal(this, "Cloning database finished."); } /** * Recomputes the {@link Score} of all identities and checks whether the score which is stored in the database is correct. * Incorrect scores are corrected & stored. * * The function is synchronized and does a transaction, no outer synchronization is needed. */ protected synchronized void verifyAndCorrectStoredScores() { Logger.normal(this, "Veriying all stored scores ..."); synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "Veriying all stored scores finished."); } /** * Debug function for deleting duplicate identities etc. which might have been created due to bugs :) */ private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity) synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity) synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity) synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { } // synchronized(mPuzzleStore) { // synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); // No need to update subscriptions as the trust is broken anyway. } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); // No need to update subscriptions as the score is broken anyway. } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { // FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually // need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert. if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * </code> * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); final Score oldScore = currentStoredScore.clone(); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { synchronized(mSubscriptionManager) { for(String seedURI : SEED_IDENTITIES) { synchronized(Persistent.transactionLock(mDB)) { try { final Identity existingSeed = getIdentityByURI(seedURI); final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager if(existingSeed instanceof OwnIdentity) { final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed; ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed); ownExistingSeed.storeAndCommit(); } else { try { existingSeed.setEdition(new FreenetURI(seedURI).getEdition()); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed); existingSeed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { final Identity newSeed = new Identity(this, seedURI, null, true); // We have to explicitly set the edition number because the constructor only considers the given edition as a hint. newSeed.setEdition(new FreenetURI(seedURI).getEdition()); newSeed.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed); Persistent.checkedCommit(mDB, this); } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mSubscriptionManager != null) mSubscriptionManager.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); } if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); // TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't. // As soon as we have notification-coalescing we might do it. // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called. * * ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)} * for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Finishes the import of the current trust list and performs score computation. * * ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it! * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; boolean scoreExistedBefore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); scoreExistedBefore = true; } catch(NotInTrustTreeException e) { scoreExistedBefore = false; currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) { currentStoredTrusteeScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore); } // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); synchronized(Persistent.transactionLock(mDB)) { try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e2) { Persistent.checkedRollbackAndThrow(mDB, this, e2); } } // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. Logger.normal(this, "addIdentity(): " + identity); return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); // Nothing has changed about the actual score so we do not notify. // mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function abortTrustListImport(e); // Does rollback for us throw e; } else { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { + synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } + } } /** * Enables or disables the publishing of the trust list of an {@link OwnIdentity}. * The trust list contains all trust values which the OwnIdentity has assigned to other identities. * * @see OwnIdentity#setPublishTrustList(boolean) * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishTrustList Whether to publish the trust list. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}. */ public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setPublishTrustList(publishTrustList); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity); } /** * Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}. * * If publishIntroductionPuzzles==true adds, if false removes: * - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT} * - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT} * * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishIntroductionPuzzles Whether to publish introduction puzzles. * @throws UnknownIdentityException If there is no identity with the given ownIdentityID * @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list. */ public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager if(!identity.doesPublishTrustList()) throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!"); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { if(publishIntroductionPuzzles) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } else { identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY); } mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity); } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.addContext(newContext); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeContext(context); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setProperty(property, value); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeProperty(property); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public SubscriptionManager getSubscriptionManager() { return mSubscriptionManager; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } protected FCPInterface getFCPInterface() { return mFCPInterface; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
false
true
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity) synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity) synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity) synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { } // synchronized(mPuzzleStore) { // synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); // No need to update subscriptions as the trust is broken anyway. } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); // No need to update subscriptions as the score is broken anyway. } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { // FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually // need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert. if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * </code> * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); final Score oldScore = currentStoredScore.clone(); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { synchronized(mSubscriptionManager) { for(String seedURI : SEED_IDENTITIES) { synchronized(Persistent.transactionLock(mDB)) { try { final Identity existingSeed = getIdentityByURI(seedURI); final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager if(existingSeed instanceof OwnIdentity) { final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed; ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed); ownExistingSeed.storeAndCommit(); } else { try { existingSeed.setEdition(new FreenetURI(seedURI).getEdition()); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed); existingSeed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { final Identity newSeed = new Identity(this, seedURI, null, true); // We have to explicitly set the edition number because the constructor only considers the given edition as a hint. newSeed.setEdition(new FreenetURI(seedURI).getEdition()); newSeed.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed); Persistent.checkedCommit(mDB, this); } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mSubscriptionManager != null) mSubscriptionManager.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); } if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); // TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't. // As soon as we have notification-coalescing we might do it. // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called. * * ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)} * for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Finishes the import of the current trust list and performs score computation. * * ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it! * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; boolean scoreExistedBefore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); scoreExistedBefore = true; } catch(NotInTrustTreeException e) { scoreExistedBefore = false; currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) { currentStoredTrusteeScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore); } // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); synchronized(Persistent.transactionLock(mDB)) { try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e2) { Persistent.checkedRollbackAndThrow(mDB, this, e2); } } // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. Logger.normal(this, "addIdentity(): " + identity); return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); // Nothing has changed about the actual score so we do not notify. // mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function abortTrustListImport(e); // Does rollback for us throw e; } else { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Enables or disables the publishing of the trust list of an {@link OwnIdentity}. * The trust list contains all trust values which the OwnIdentity has assigned to other identities. * * @see OwnIdentity#setPublishTrustList(boolean) * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishTrustList Whether to publish the trust list. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}. */ public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setPublishTrustList(publishTrustList); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity); } /** * Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}. * * If publishIntroductionPuzzles==true adds, if false removes: * - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT} * - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT} * * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishIntroductionPuzzles Whether to publish introduction puzzles. * @throws UnknownIdentityException If there is no identity with the given ownIdentityID * @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list. */ public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager if(!identity.doesPublishTrustList()) throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!"); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { if(publishIntroductionPuzzles) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } else { identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY); } mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity); } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.addContext(newContext); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeContext(context); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setProperty(property, value); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeProperty(property); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public SubscriptionManager getSubscriptionManager() { return mSubscriptionManager; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } protected FCPInterface getFCPInterface() { return mFCPInterface; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity) synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity) synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity) synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { } // synchronized(mPuzzleStore) { // synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); // No need to update subscriptions as the trust is broken anyway. } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); // No need to update subscriptions as the score is broken anyway. } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { // FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually // need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert. if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * </code> * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); final Score oldScore = currentStoredScore.clone(); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { synchronized(mSubscriptionManager) { for(String seedURI : SEED_IDENTITIES) { synchronized(Persistent.transactionLock(mDB)) { try { final Identity existingSeed = getIdentityByURI(seedURI); final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager if(existingSeed instanceof OwnIdentity) { final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed; ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed); ownExistingSeed.storeAndCommit(); } else { try { existingSeed.setEdition(new FreenetURI(seedURI).getEdition()); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed); existingSeed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { final Identity newSeed = new Identity(this, seedURI, null, true); // We have to explicitly set the edition number because the constructor only considers the given edition as a hint. newSeed.setEdition(new FreenetURI(seedURI).getEdition()); newSeed.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed); Persistent.checkedCommit(mDB, this); } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mSubscriptionManager != null) mSubscriptionManager.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); } if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); // TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't. // As soon as we have notification-coalescing we might do it. // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called. * * ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)} * for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Finishes the import of the current trust list and performs score computation. * * ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it! * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}}} * </code> */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; boolean scoreExistedBefore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); scoreExistedBefore = true; } catch(NotInTrustTreeException e) { scoreExistedBefore = false; currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) { currentStoredTrusteeScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore); } // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); synchronized(Persistent.transactionLock(mDB)) { try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e2) { Persistent.checkedRollbackAndThrow(mDB, this, e2); } } // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. Logger.normal(this, "addIdentity(): " + identity); return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); // Nothing has changed about the actual score so we do not notify. // mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function abortTrustListImport(e); // Does rollback for us throw e; } else { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } /** * Enables or disables the publishing of the trust list of an {@link OwnIdentity}. * The trust list contains all trust values which the OwnIdentity has assigned to other identities. * * @see OwnIdentity#setPublishTrustList(boolean) * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishTrustList Whether to publish the trust list. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}. */ public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setPublishTrustList(publishTrustList); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity); } /** * Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}. * * If publishIntroductionPuzzles==true adds, if false removes: * - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT} * - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT} * * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishIntroductionPuzzles Whether to publish introduction puzzles. * @throws UnknownIdentityException If there is no identity with the given ownIdentityID * @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list. */ public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager if(!identity.doesPublishTrustList()) throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!"); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { if(publishIntroductionPuzzles) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } else { identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY); } mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity); } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.addContext(newContext); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeContext(context); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setProperty(property, value); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeProperty(property); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public SubscriptionManager getSubscriptionManager() { return mSubscriptionManager; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } protected FCPInterface getFCPInterface() { return mFCPInterface; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
diff --git a/src/se/chalmers/tda367/std/utilities/ExtendedClassLoader.java b/src/se/chalmers/tda367/std/utilities/ExtendedClassLoader.java index 184ac9e..807e580 100644 --- a/src/se/chalmers/tda367/std/utilities/ExtendedClassLoader.java +++ b/src/se/chalmers/tda367/std/utilities/ExtendedClassLoader.java @@ -1,65 +1,65 @@ package se.chalmers.tda367.std.utilities; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.util.logging.Logger; /** * A class used for loading java classes from files on the hard drive. * @author Emil Edholm * @date Apr 22, 2012 */ public final class ExtendedClassLoader extends ClassLoader { private final String intendedPackage; private final Path containingFolder; /** * The extended class loader. Used for retrieving class files from the hard drive. * @param intendedPackage the package of the files about the be read. * @param containingFolder the path to the */ public ExtendedClassLoader(String intendedPackage, Path containingFolder) { super(); this.intendedPackage = intendedPackage; this.containingFolder = containingFolder; } @Override public Class<?> findClass (String binaryName) { byte[] classData = loadClassData (containingFolder, binaryName); // This is where the actual conversion between a heap of bytes to an actual class. return defineClass(intendedPackage + "." + binaryName, classData, 0, classData.length); } /** * Loads the data of a specified file and path. * @param searchPath the path to the folder where {@code className} resides in * @param className the name of the class to try to load (without the extension) * @return a byte array of the read class file. Empty if file not found, etc. */ private byte[] loadClassData (Path searchPath, String className) { - File f = new File(searchPath.toString() + className + ".class"); + File f = searchPath.resolve(className + ".class").toFile(); if(!f.isFile()){ Logger.getLogger("se.chalmers.tda367.std.utilities").severe("Unable to load the class data from file: " + f.toString()); return new byte[0]; } ByteArrayOutputStream classBuffer = new ByteArrayOutputStream(); try { InputStream stream = new FileInputStream(f); int readByte = 0; while((readByte = stream.read()) != -1){ classBuffer.write(readByte); } } catch (IOException e) { e.printStackTrace(); } return classBuffer.toByteArray(); } }
true
true
private byte[] loadClassData (Path searchPath, String className) { File f = new File(searchPath.toString() + className + ".class"); if(!f.isFile()){ Logger.getLogger("se.chalmers.tda367.std.utilities").severe("Unable to load the class data from file: " + f.toString()); return new byte[0]; } ByteArrayOutputStream classBuffer = new ByteArrayOutputStream(); try { InputStream stream = new FileInputStream(f); int readByte = 0; while((readByte = stream.read()) != -1){ classBuffer.write(readByte); } } catch (IOException e) { e.printStackTrace(); } return classBuffer.toByteArray(); }
private byte[] loadClassData (Path searchPath, String className) { File f = searchPath.resolve(className + ".class").toFile(); if(!f.isFile()){ Logger.getLogger("se.chalmers.tda367.std.utilities").severe("Unable to load the class data from file: " + f.toString()); return new byte[0]; } ByteArrayOutputStream classBuffer = new ByteArrayOutputStream(); try { InputStream stream = new FileInputStream(f); int readByte = 0; while((readByte = stream.read()) != -1){ classBuffer.write(readByte); } } catch (IOException e) { e.printStackTrace(); } return classBuffer.toByteArray(); }
diff --git a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/wizards/MylarPreferenceWizardPage.java b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/wizards/MylarPreferenceWizardPage.java index 764f8161c..bcb4ef00f 100644 --- a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/wizards/MylarPreferenceWizardPage.java +++ b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/wizards/MylarPreferenceWizardPage.java @@ -1,263 +1,263 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.java.ui.wizards; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.mylar.internal.tasks.ui.TaskListColorsAndFonts; import org.eclipse.mylar.internal.tasks.ui.TaskUiUtil; import org.eclipse.mylar.internal.tasks.ui.views.TaskListView; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.events.IHyperlinkListener; import org.eclipse.ui.forms.widgets.Hyperlink; /** * @author Shawn Minto * @author Mik Kersten */ public class MylarPreferenceWizardPage extends WizardPage { private static final String DESCRIPTION = "Configures Mylar preferences to the recommended defaults. To alter these\n" + "re-invoke this wizard via the File -> New menu."; private static final String AUTO_FOLDING = "Turn automatic Java editor folding on"; private static final String AUTO_CLOSE = "Automatically manage open editors to match task context"; // private static final String WORKING_SET = "Add the \"active task context\" working set"; private static final String CONTENT_ASSIST = "Enable task-context ranked content assist, requires Eclipse restart."; private static final String CONTENT_ASSIST_WARNING = "Toggle via Preferences->Java->Editor->Content Assist->Advanced "; private static final String OPEN_TASK_LIST = "Open the " + TaskListView.LABEL_VIEW + " view"; private Button contentAssistButton; private Button turnOnAutoFoldingButton; private boolean autoFolding = true; // private Button addMylarActiveWorkingSetButton; // TODO: remove private boolean createWorkingSet = false; private Button closeEditorsOnDeactivationButton; private boolean closeEditors = true; private Button openTaskListButton; private boolean openTaskList = true; protected MylarPreferenceWizardPage(String pageName) { super(pageName); setTitle(pageName); setDescription(DESCRIPTION); } public void createControl(Composite parent) { Composite containerComposite = new Composite(parent, SWT.NULL); containerComposite.setLayout(new GridLayout()); Composite buttonComposite = new Composite(containerComposite, SWT.NULL); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.makeColumnsEqualWidth = false; buttonComposite.setLayout(layout); contentAssistButton = new Button(buttonComposite, SWT.CHECK); GridData gd = new GridData(); contentAssistButton.setLayoutData(gd); contentAssistButton.setSelection(true); Label label = new Label(buttonComposite, SWT.NONE); label.setText(CONTENT_ASSIST); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); label.setText(CONTENT_ASSIST_WARNING); - label = new Label(buttonComposite, SWT.NONE); - label = new Label(buttonComposite, SWT.NONE); - label.setText("NOTE: if Mylar is uninstalled you must Restore Defaults on above page "); - label.setForeground(TaskListColorsAndFonts.COLOR_LABEL_CAUTION); +// label = new Label(buttonComposite, SWT.NONE); +// label = new Label(buttonComposite, SWT.NONE); +// label.setText("NOTE: if Mylar is uninstalled you must Restore Defaults on above page "); +// label.setForeground(TaskListColorsAndFonts.COLOR_LABEL_CAUTION); gd = new GridData(); label.setLayoutData(gd); turnOnAutoFoldingButton = new Button(buttonComposite, SWT.CHECK); gd = new GridData(); turnOnAutoFoldingButton.setLayoutData(gd); turnOnAutoFoldingButton.setSelection(true); turnOnAutoFoldingButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { autoFolding = turnOnAutoFoldingButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // don't care about this event } }); label = new Label(buttonComposite, SWT.NONE); label.setText(AUTO_FOLDING); gd = new GridData(); label.setLayoutData(gd); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); label.setText("Toggle via toolbar button "); closeEditorsOnDeactivationButton = new Button(buttonComposite, SWT.CHECK); gd = new GridData(); closeEditorsOnDeactivationButton.setLayoutData(gd); closeEditorsOnDeactivationButton.setSelection(true); closeEditorsOnDeactivationButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { closeEditors = closeEditorsOnDeactivationButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // don't care about this event } }); label = new Label(buttonComposite, SWT.NONE); label.setText(AUTO_CLOSE); gd = new GridData(); label.setLayoutData(gd); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); label.setText("Toggle via Mylar preferences page "); // addMylarActiveWorkingSetButton = new Button(buttonComposite, SWT.CHECK); // gd = new GridData(); // addMylarActiveWorkingSetButton.setSelection(true); // addMylarActiveWorkingSetButton.addSelectionListener(new SelectionListener() { // // public void widgetSelected(SelectionEvent e) { // workingSet = addMylarActiveWorkingSetButton.getSelection(); // } // // public void widgetDefaultSelected(SelectionEvent e) { // // don't care about this event // } // }); // label = new Label(buttonComposite, SWT.NONE); // label.setText(WORKING_SET); // gd = new GridData(); // label.setLayoutData(gd); // setControl(buttonComposite); // label = new Label(buttonComposite, SWT.NONE); // label = new Label(buttonComposite, SWT.NONE); // label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); // label.setText("Remove via Window->Working Sets "); openTaskListButton = new Button(buttonComposite, SWT.CHECK); gd = new GridData(); openTaskListButton.setLayoutData(gd); openTaskListButton.setSelection(true); openTaskListButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { openTaskList = openTaskListButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // don't care about this event } }); label = new Label(buttonComposite, SWT.NONE); label.setText(OPEN_TASK_LIST); gd = new GridData(); label.setLayoutData(gd); Label spacer = new Label(buttonComposite, SWT.NONE); spacer.setText(" "); spacer = new Label(buttonComposite, SWT.NONE); spacer.setText(" "); Hyperlink hyperlink = new Hyperlink(containerComposite, SWT.NULL); hyperlink.setUnderlined(true); hyperlink.setForeground(TaskListColorsAndFonts.COLOR_HYPERLINK); hyperlink.setText("If this is your first time using Mylar please watch the short Getting Started video"); hyperlink.addHyperlinkListener(new IHyperlinkListener() { public void linkActivated(HyperlinkEvent e) { TaskUiUtil.openUrl("http://eclipse.org/mylar/start.php"); } public void linkEntered(HyperlinkEvent e) { // ignore } public void linkExited(HyperlinkEvent e) { // ignore } }); // Composite browserComposite = new Composite(containerComposite, SWT.NULL); // browserComposite.setLayout(new GridLayout()); // try { // Browser browser = new Browser(browserComposite, SWT.NONE); // browser.setText(htmlDocs); // GridData browserLayout = new GridData(GridData.FILL_HORIZONTAL); // browserLayout.heightHint = 100; // browserLayout.widthHint = 600; // browser.setLayoutData(browserLayout); // } catch (Throwable t) { // // fail silently if there is no browser // } setControl(containerComposite); } public boolean isAutoFolding() { return autoFolding; } public boolean closeEditors() { return closeEditors; } public boolean isMylarContentAssistDefault() { return contentAssistButton.getSelection(); } public boolean isCreateWorkingSet() { return createWorkingSet; } public boolean isOpenTaskList() { return openTaskList; } }
true
true
public void createControl(Composite parent) { Composite containerComposite = new Composite(parent, SWT.NULL); containerComposite.setLayout(new GridLayout()); Composite buttonComposite = new Composite(containerComposite, SWT.NULL); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.makeColumnsEqualWidth = false; buttonComposite.setLayout(layout); contentAssistButton = new Button(buttonComposite, SWT.CHECK); GridData gd = new GridData(); contentAssistButton.setLayoutData(gd); contentAssistButton.setSelection(true); Label label = new Label(buttonComposite, SWT.NONE); label.setText(CONTENT_ASSIST); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); label.setText(CONTENT_ASSIST_WARNING); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setText("NOTE: if Mylar is uninstalled you must Restore Defaults on above page "); label.setForeground(TaskListColorsAndFonts.COLOR_LABEL_CAUTION); gd = new GridData(); label.setLayoutData(gd); turnOnAutoFoldingButton = new Button(buttonComposite, SWT.CHECK); gd = new GridData(); turnOnAutoFoldingButton.setLayoutData(gd); turnOnAutoFoldingButton.setSelection(true); turnOnAutoFoldingButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { autoFolding = turnOnAutoFoldingButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // don't care about this event } }); label = new Label(buttonComposite, SWT.NONE); label.setText(AUTO_FOLDING); gd = new GridData(); label.setLayoutData(gd); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); label.setText("Toggle via toolbar button "); closeEditorsOnDeactivationButton = new Button(buttonComposite, SWT.CHECK); gd = new GridData(); closeEditorsOnDeactivationButton.setLayoutData(gd); closeEditorsOnDeactivationButton.setSelection(true); closeEditorsOnDeactivationButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { closeEditors = closeEditorsOnDeactivationButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // don't care about this event } }); label = new Label(buttonComposite, SWT.NONE); label.setText(AUTO_CLOSE); gd = new GridData(); label.setLayoutData(gd); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); label.setText("Toggle via Mylar preferences page "); // addMylarActiveWorkingSetButton = new Button(buttonComposite, SWT.CHECK); // gd = new GridData(); // addMylarActiveWorkingSetButton.setSelection(true); // addMylarActiveWorkingSetButton.addSelectionListener(new SelectionListener() { // // public void widgetSelected(SelectionEvent e) { // workingSet = addMylarActiveWorkingSetButton.getSelection(); // } // // public void widgetDefaultSelected(SelectionEvent e) { // // don't care about this event // } // }); // label = new Label(buttonComposite, SWT.NONE); // label.setText(WORKING_SET); // gd = new GridData(); // label.setLayoutData(gd); // setControl(buttonComposite); // label = new Label(buttonComposite, SWT.NONE); // label = new Label(buttonComposite, SWT.NONE); // label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); // label.setText("Remove via Window->Working Sets "); openTaskListButton = new Button(buttonComposite, SWT.CHECK); gd = new GridData(); openTaskListButton.setLayoutData(gd); openTaskListButton.setSelection(true); openTaskListButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { openTaskList = openTaskListButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // don't care about this event } }); label = new Label(buttonComposite, SWT.NONE); label.setText(OPEN_TASK_LIST); gd = new GridData(); label.setLayoutData(gd); Label spacer = new Label(buttonComposite, SWT.NONE); spacer.setText(" "); spacer = new Label(buttonComposite, SWT.NONE); spacer.setText(" "); Hyperlink hyperlink = new Hyperlink(containerComposite, SWT.NULL); hyperlink.setUnderlined(true); hyperlink.setForeground(TaskListColorsAndFonts.COLOR_HYPERLINK); hyperlink.setText("If this is your first time using Mylar please watch the short Getting Started video"); hyperlink.addHyperlinkListener(new IHyperlinkListener() { public void linkActivated(HyperlinkEvent e) { TaskUiUtil.openUrl("http://eclipse.org/mylar/start.php"); } public void linkEntered(HyperlinkEvent e) { // ignore } public void linkExited(HyperlinkEvent e) { // ignore } }); // Composite browserComposite = new Composite(containerComposite, SWT.NULL); // browserComposite.setLayout(new GridLayout()); // try { // Browser browser = new Browser(browserComposite, SWT.NONE); // browser.setText(htmlDocs); // GridData browserLayout = new GridData(GridData.FILL_HORIZONTAL); // browserLayout.heightHint = 100; // browserLayout.widthHint = 600; // browser.setLayoutData(browserLayout); // } catch (Throwable t) { // // fail silently if there is no browser // } setControl(containerComposite); }
public void createControl(Composite parent) { Composite containerComposite = new Composite(parent, SWT.NULL); containerComposite.setLayout(new GridLayout()); Composite buttonComposite = new Composite(containerComposite, SWT.NULL); GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.makeColumnsEqualWidth = false; buttonComposite.setLayout(layout); contentAssistButton = new Button(buttonComposite, SWT.CHECK); GridData gd = new GridData(); contentAssistButton.setLayoutData(gd); contentAssistButton.setSelection(true); Label label = new Label(buttonComposite, SWT.NONE); label.setText(CONTENT_ASSIST); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); label.setText(CONTENT_ASSIST_WARNING); // label = new Label(buttonComposite, SWT.NONE); // label = new Label(buttonComposite, SWT.NONE); // label.setText("NOTE: if Mylar is uninstalled you must Restore Defaults on above page "); // label.setForeground(TaskListColorsAndFonts.COLOR_LABEL_CAUTION); gd = new GridData(); label.setLayoutData(gd); turnOnAutoFoldingButton = new Button(buttonComposite, SWT.CHECK); gd = new GridData(); turnOnAutoFoldingButton.setLayoutData(gd); turnOnAutoFoldingButton.setSelection(true); turnOnAutoFoldingButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { autoFolding = turnOnAutoFoldingButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // don't care about this event } }); label = new Label(buttonComposite, SWT.NONE); label.setText(AUTO_FOLDING); gd = new GridData(); label.setLayoutData(gd); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); label.setText("Toggle via toolbar button "); closeEditorsOnDeactivationButton = new Button(buttonComposite, SWT.CHECK); gd = new GridData(); closeEditorsOnDeactivationButton.setLayoutData(gd); closeEditorsOnDeactivationButton.setSelection(true); closeEditorsOnDeactivationButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { closeEditors = closeEditorsOnDeactivationButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // don't care about this event } }); label = new Label(buttonComposite, SWT.NONE); label.setText(AUTO_CLOSE); gd = new GridData(); label.setLayoutData(gd); label = new Label(buttonComposite, SWT.NONE); label = new Label(buttonComposite, SWT.NONE); label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); label.setText("Toggle via Mylar preferences page "); // addMylarActiveWorkingSetButton = new Button(buttonComposite, SWT.CHECK); // gd = new GridData(); // addMylarActiveWorkingSetButton.setSelection(true); // addMylarActiveWorkingSetButton.addSelectionListener(new SelectionListener() { // // public void widgetSelected(SelectionEvent e) { // workingSet = addMylarActiveWorkingSetButton.getSelection(); // } // // public void widgetDefaultSelected(SelectionEvent e) { // // don't care about this event // } // }); // label = new Label(buttonComposite, SWT.NONE); // label.setText(WORKING_SET); // gd = new GridData(); // label.setLayoutData(gd); // setControl(buttonComposite); // label = new Label(buttonComposite, SWT.NONE); // label = new Label(buttonComposite, SWT.NONE); // label.setFont(JFaceResources.getFontRegistry().getItalic(JFaceResources.DEFAULT_FONT)); // label.setText("Remove via Window->Working Sets "); openTaskListButton = new Button(buttonComposite, SWT.CHECK); gd = new GridData(); openTaskListButton.setLayoutData(gd); openTaskListButton.setSelection(true); openTaskListButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { openTaskList = openTaskListButton.getSelection(); } public void widgetDefaultSelected(SelectionEvent e) { // don't care about this event } }); label = new Label(buttonComposite, SWT.NONE); label.setText(OPEN_TASK_LIST); gd = new GridData(); label.setLayoutData(gd); Label spacer = new Label(buttonComposite, SWT.NONE); spacer.setText(" "); spacer = new Label(buttonComposite, SWT.NONE); spacer.setText(" "); Hyperlink hyperlink = new Hyperlink(containerComposite, SWT.NULL); hyperlink.setUnderlined(true); hyperlink.setForeground(TaskListColorsAndFonts.COLOR_HYPERLINK); hyperlink.setText("If this is your first time using Mylar please watch the short Getting Started video"); hyperlink.addHyperlinkListener(new IHyperlinkListener() { public void linkActivated(HyperlinkEvent e) { TaskUiUtil.openUrl("http://eclipse.org/mylar/start.php"); } public void linkEntered(HyperlinkEvent e) { // ignore } public void linkExited(HyperlinkEvent e) { // ignore } }); // Composite browserComposite = new Composite(containerComposite, SWT.NULL); // browserComposite.setLayout(new GridLayout()); // try { // Browser browser = new Browser(browserComposite, SWT.NONE); // browser.setText(htmlDocs); // GridData browserLayout = new GridData(GridData.FILL_HORIZONTAL); // browserLayout.heightHint = 100; // browserLayout.widthHint = 600; // browser.setLayoutData(browserLayout); // } catch (Throwable t) { // // fail silently if there is no browser // } setControl(containerComposite); }
diff --git a/android/src/org/coolreader/crengine/Scanner.java b/android/src/org/coolreader/crengine/Scanner.java index 230718f9..91c43d5a 100644 --- a/android/src/org/coolreader/crengine/Scanner.java +++ b/android/src/org/coolreader/crengine/Scanner.java @@ -1,542 +1,542 @@ package org.coolreader.crengine; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.zip.ZipEntry; import org.coolreader.CoolReader; import org.coolreader.R; import org.coolreader.crengine.Engine.EngineTask; import android.os.Environment; import android.util.Log; public class Scanner { HashMap<String, FileInfo> mFileList = new HashMap<String, FileInfo>(); ArrayList<FileInfo> mFilesForParsing = new ArrayList<FileInfo>(); FileInfo mRoot; boolean mHideEmptyDirs = true; void setHideEmptyDirs( boolean flgHide ) { mHideEmptyDirs = flgHide; } // private boolean scanDirectories( FileInfo baseDir ) // { // try { // File dir = new File(baseDir.pathname); // File[] items = dir.listFiles(); // // process normal files // for ( File f : items ) { // if ( !f.isDirectory() ) { // FileInfo item = new FileInfo( f ); // if ( item.format!=null ) { // item.parent = baseDir; // baseDir.addFile(item); // mFileList.add(item); // } // } // } // // process directories // for ( File f : items ) { // if ( f.isDirectory() ) { // FileInfo item = new FileInfo( f ); // item.parent = baseDir; // scanDirectories(item); // if ( !item.isEmpty() ) { // baseDir.addDir(item); // } // } // } // return !baseDir.isEmpty(); // } catch ( Exception e ) { // Log.e("cr3", "Exception while scanning directory " + baseDir.pathname, e); // return false; // } // } private boolean dirScanEnabled = true; public boolean getDirScanEnabled() { return dirScanEnabled; } public void setDirScanEnabled(boolean dirScanEnabled) { this.dirScanEnabled = dirScanEnabled; } private FileInfo scanZip( FileInfo zip ) { try { File zf = new File(zip.pathname); //ZipFile file = new ZipFile(zf); ArrayList<ZipEntry> entries = engine.getArchiveItems(zip.pathname); ArrayList<FileInfo> items = new ArrayList<FileInfo>(); //for ( Enumeration<?> e = file.entries(); e.hasMoreElements(); ) { for ( ZipEntry entry : entries ) { if ( entry.isDirectory() ) continue; String name = entry.getName(); FileInfo item = new FileInfo(); item.format = DocumentFormat.byExtension(name); if ( item.format==null ) continue; File f = new File(name); item.filename = f.getName(); item.path = f.getPath(); item.pathname = entry.getName(); item.size = (int)entry.getSize(); //item.createTime = entry.getTime(); item.createTime = zf.lastModified(); item.arcname = zip.pathname; item.arcsize = (int)entry.getSize(); //getCompressedSize(); item.isArchive = true; items.add(item); } if ( items.size()==0 ) { Log.i("cr3", "Supported files not found in " + zip.pathname); return null; } else if ( items.size()==1 ) { // single supported file in archive FileInfo item = items.get(0); item.isArchive = true; item.isDirectory = false; return item; } else { zip.isArchive = true; zip.isDirectory = true; zip.isListed = true; for ( FileInfo item : items ) { item.parent = zip; zip.addFile(item); } return zip; } } catch ( Exception e ) { Log.e("cr3", "IOException while opening " + zip.pathname + " " + e.getMessage()); } return null; } /** * Adds dir and file children to directory FileInfo item. * @param baseDir is directory to list files and dirs for * @return true if successful. */ public boolean listDirectory( FileInfo baseDir ) { if ( baseDir.isListed ) return true; try { File dir = new File(baseDir.pathname); File[] items = dir.listFiles(); // process normal files if ( items!=null ) { for ( File f : items ) { if ( !f.isDirectory() ) { if ( f.getName().startsWith(".") ) continue; // treat files beginning with '.' as hidden String pathName = f.getAbsolutePath(); boolean isZip = pathName.toLowerCase().endsWith(".zip"); FileInfo item = mFileList.get(pathName); boolean isNew = false; if ( item==null ) { item = new FileInfo( f ); if ( isZip ) { item = scanZip( item ); if ( item==null ) continue; if ( item.isDirectory ) { // many supported files in ZIP item.parent = baseDir; baseDir.addDir(item); for ( int i=0; i<item.fileCount(); i++ ) { FileInfo file = item.getFile(i); mFileList.put(file.getPathName(), file); } } else { item.parent = baseDir; baseDir.addFile(item); mFileList.put(pathName, item); } continue; } isNew = true; } if ( item.format!=null ) { item.parent = baseDir; baseDir.addFile(item); if ( isNew ) mFileList.put(pathName, item); } } } // process directories for ( File f : items ) { if ( f.isDirectory() ) { if ( f.getName().startsWith(".") ) continue; // treat dirs beginning with '.' as hidden FileInfo item = new FileInfo( f ); item.parent = baseDir; baseDir.addDir(item); } } } baseDir.isListed = true; return !baseDir.isEmpty(); } catch ( Exception e ) { Log.e("cr3", "Exception while listing directory " + baseDir.pathname, e); baseDir.isListed = true; return false; } } public static class ScanControl { volatile private boolean stopped = false; public boolean isStopped() { return stopped; } public void stop() { stopped = true; } } /** * Scan single directory for dir and file properties in background thread. * @param baseDir is directory to scan * @param readyCallback is called on completion */ public void scanDirectory( final FileInfo baseDir, final Runnable readyCallback, final boolean recursiveScan, final ScanControl scanControl ) { final long startTime = System.currentTimeMillis(); listDirectory(baseDir); listSubtree( baseDir, 2, android.os.SystemClock.uptimeMillis() + 700 ); - if ( (!getDirScanEnabled() && !recursiveScan) || baseDir.isScanned ) { + if ( (!getDirScanEnabled() || baseDir.isScanned) && !recursiveScan ) { readyCallback.run(); return; } engine.execute(new EngineTask() { long nextProgressTime = startTime + 2000; boolean progressShown = false; void progress( int percent ) { if ( recursiveScan ) return; // no progress dialog for recursive scan long ts = System.currentTimeMillis(); if ( ts>=nextProgressTime ) { engine.showProgress(percent, R.string.progress_scanning); nextProgressTime = ts + 1500; progressShown = true; } } public void done() { baseDir.isScanned = true; if ( progressShown ) engine.hideProgress(); readyCallback.run(); } public void fail(Exception e) { Log.e("cr3", "Exception while scanning directory " + baseDir.pathname, e); baseDir.isScanned = true; if ( progressShown ) engine.hideProgress(); readyCallback.run(); } public void scan( FileInfo baseDir ) { if ( baseDir.isRecentDir() ) return; //listDirectory(baseDir); progress(1000); if ( scanControl.isStopped() ) return; for ( int i=baseDir.dirCount()-1; i>=0; i-- ) { if ( scanControl.isStopped() ) return; listDirectory(baseDir.getDir(i)); } progress(2000); if ( mHideEmptyDirs ) baseDir.removeEmptyDirs(); if ( scanControl.isStopped() ) return; ArrayList<FileInfo> filesForParsing = new ArrayList<FileInfo>(); int count = baseDir.fileCount(); for ( int i=0; i<count; i++ ) { FileInfo item = baseDir.getFile(i); boolean found = db.findByPathname(item); if ( found ) Log.v("cr3db", "File " + item.pathname + " is found in DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); boolean saveToDB = true; if ( !found && item.format.canParseProperties() ) { filesForParsing.add(item); saveToDB = false; } if ( !found && saveToDB ) { db.save(item); Log.v("cr3db", "File " + item.pathname + " is added to DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); } progress( 2000 + 3000 * i / count ); } // db lookup files count = filesForParsing.size(); for ( int i=0; i<count; i++ ) { if ( scanControl.isStopped() ) return; FileInfo item = filesForParsing.get(i); engine.scanBookProperties(item); db.save(item); Log.v("cr3db", "File " + item.pathname + " is added to DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); progress( 5000 + 5000 * i / count ); } if ( recursiveScan ) { if ( scanControl.isStopped() ) return; for ( int i=baseDir.dirCount()-1; i>=0; i-- ) scan(baseDir.getDir(i)); } } public void work() throws Exception { // scan (list) directories nextProgressTime = startTime + 1500; scan( baseDir ); } }); } // private int lastPercent = 0; // private long lastProgressUpdate = 0; // private final int PROGRESS_UPDATE_INTERVAL = 2000; // 2 seconds // private void updateProgress( int percent ) // { // long ts = System.currentTimeMillis(); // if ( percent!=lastPercent && ts>lastProgressUpdate+PROGRESS_UPDATE_INTERVAL ) { // engine.showProgress(percent, "Scanning directories..."); // lastPercent = percent; // lastProgressUpdate = ts; // } // } // private void lookupDB() // { // int count = mFileList.size(); // for ( int i=0; i<count; i++ ) { // FileInfo item = mFileList.get(i); // boolean found = db.findByPathname(item); // if ( found ) // Log.v("cr3db", "File " + item.pathname + " is found in DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); // // boolean saveToDB = true; // if ( !found && item.format==DocumentFormat.FB2 ) { // mFilesForParsing.add(item); // saveToDB = false; // } // // if ( !found && saveToDB ) { // db.save(item); // Log.v("cr3db", "File " + item.pathname + " is added to DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); // } // updateProgress( 1000 + 4000 * i / count ); // } // } // // private void parseBookProperties() // { // int count = mFilesForParsing.size(); // for ( int i=0; i<count; i++ ) { // FileInfo item = mFilesForParsing.get(i); // engine.scanBookProperties(item); // db.save(item); // Log.v("cr3db", "File " + item.pathname + " is added to DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); // updateProgress( 5000 + 5000 * i / count ); // } // } private boolean addRoot( String pathname, int resourceId, boolean listIt) { return addRoot( pathname, coolReader.getResources().getString(resourceId), listIt); } private boolean addRoot( String pathname, String filename, boolean listIt) { FileInfo dir = new FileInfo(); dir.isDirectory = true; dir.pathname = pathname; dir.filename = filename; if ( listIt && !listDirectory(dir) ) return false; mRoot.addDir(dir); dir.parent = mRoot; if ( !listIt ) { dir.isListed = true; dir.isScanned = true; } return true; } /** * Lists all directories from root to directory of specified file, returns found directory. * @param file * @param root * @return */ private FileInfo findParentInternal( FileInfo file, FileInfo root ) { if ( root==null || file==null || root.isRecentDir() ) return null; if ( !root.isRootDir() && !file.getPathName().startsWith( root.getPathName() ) ) return null; // to list all directories starting root dir if ( root.isDirectory && !root.isSpecialDir() ) listDirectory(root); for ( int i=0; i<root.dirCount(); i++ ) { FileInfo found = findParentInternal( file, root.getDir(i)); if ( found!=null ) return found; } for ( int i=0; i<root.fileCount(); i++ ) { if ( root.getFile(i).getPathName().equals(file.getPathName()) ) return root; if ( root.getFile(i).getPathName().startsWith(file.getPathName() + "@/") ) return root; } return null; } public final static int MAX_DIR_LIST_TIME = 500; // 0.5 seconds /** * Lists all directories from root to directory of specified file, returns found directory. * @param file * @param root * @return */ public FileInfo findParent( FileInfo file, FileInfo root ) { FileInfo parent = findParentInternal(file, root); if ( parent==null ) return null; long maxTs = android.os.SystemClock.uptimeMillis() + MAX_DIR_LIST_TIME; listSubtrees(root, mHideEmptyDirs ? 5 : 1, maxTs); return parent; } /** * List directories in subtree, limited by runtime and depth; remove empty branches (w/o books). * @param root is directory to start with * @param maxDepth is maximum depth * @param limitTs is limit for android.os.SystemClock.uptimeMillis() * @return true if completed, false if stopped by limit. */ private boolean listSubtree( FileInfo root, int maxDepth, long limitTs ) { long ts = android.os.SystemClock.uptimeMillis(); if ( ts>limitTs || maxDepth<=0 ) return false; listDirectory(root); for ( int i=root.dirCount()-1; i>=-0; i-- ) { boolean res = listSubtree(root.getDir(i), maxDepth-1, limitTs); if ( !res ) return false; } if ( mHideEmptyDirs ) root.removeEmptyDirs(); return true; } /** * List directories in subtree, limited by runtime and depth; remove empty branches (w/o books). * @param root is directory to start with * @param maxDepth is maximum depth * @param limitTs is limit for android.os.SystemClock.uptimeMillis() * @return true if completed, false if stopped by limit. */ public boolean listSubtrees( FileInfo root, int maxDepth, long limitTs ) { for ( int depth = 1; depth<=maxDepth; depth++ ) { boolean res = listSubtree( root, depth, limitTs ); if ( res ) return true; long ts = android.os.SystemClock.uptimeMillis(); if ( ts>limitTs ) return false; // limited by time // iterate deeper } return false; // limited by depth } public void initRoots() { mRoot.clear(); // create recent books dir addRoot( FileInfo.RECENT_DIR_TAG, R.string.dir_recent_books, false); String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath(); if ( "/nand".equals(sdpath) && new File("/sdcard").isDirectory() ) sdpath = "/sdcard"; addRoot( sdpath, R.string.dir_sd_card, true); // internal SD card on Nook addRoot( "/system/media/sdcard", R.string.dir_internal_sd_card, true); // internal SD card on PocketBook 701 IQ addRoot( "/PocketBook701", R.string.dir_internal_sd_card, true); addRoot( "/nand", R.string.dir_internal_memory, true); // external SD card Huawei S7 addRoot( "/sdcard2", R.string.dir_sd_card_2, true); } // public boolean scan() // { // Log.i("cr3", "Started scanning"); // long start = System.currentTimeMillis(); // mFileList.clear(); // mFilesForParsing.clear(); // mRoot.clear(); // // create recent books dir // FileInfo recentDir = new FileInfo(); // recentDir.isDirectory = true; // recentDir.pathname = "@recent"; // recentDir.filename = "Recent Books"; // mRoot.addDir(recentDir); // recentDir.parent = mRoot; // // scan directories // lastPercent = -1; // lastProgressUpdate = System.currentTimeMillis() - 500; // boolean res = scanDirectories( mRoot ); // // process found files // lookupDB(); // parseBookProperties(); // updateProgress(9999); // Log.i("cr3", "Finished scanning (" + (System.currentTimeMillis()-start)+ " ms)"); // return res; // } public FileInfo getRoot() { return mRoot; } public Scanner( CoolReader coolReader, CRDB db, Engine engine ) { this.engine = engine; this.db = db; this.coolReader = coolReader; mRoot = new FileInfo(); mRoot.path = FileInfo.ROOT_DIR_TAG; mRoot.filename = "File Manager"; mRoot.pathname = FileInfo.ROOT_DIR_TAG; mRoot.isListed = true; mRoot.isScanned = true; mRoot.isDirectory = true; } private final Engine engine; private final CRDB db; private final CoolReader coolReader; }
true
true
public void scanDirectory( final FileInfo baseDir, final Runnable readyCallback, final boolean recursiveScan, final ScanControl scanControl ) { final long startTime = System.currentTimeMillis(); listDirectory(baseDir); listSubtree( baseDir, 2, android.os.SystemClock.uptimeMillis() + 700 ); if ( (!getDirScanEnabled() && !recursiveScan) || baseDir.isScanned ) { readyCallback.run(); return; } engine.execute(new EngineTask() { long nextProgressTime = startTime + 2000; boolean progressShown = false; void progress( int percent ) { if ( recursiveScan ) return; // no progress dialog for recursive scan long ts = System.currentTimeMillis(); if ( ts>=nextProgressTime ) { engine.showProgress(percent, R.string.progress_scanning); nextProgressTime = ts + 1500; progressShown = true; } } public void done() { baseDir.isScanned = true; if ( progressShown ) engine.hideProgress(); readyCallback.run(); } public void fail(Exception e) { Log.e("cr3", "Exception while scanning directory " + baseDir.pathname, e); baseDir.isScanned = true; if ( progressShown ) engine.hideProgress(); readyCallback.run(); } public void scan( FileInfo baseDir ) { if ( baseDir.isRecentDir() ) return; //listDirectory(baseDir); progress(1000); if ( scanControl.isStopped() ) return; for ( int i=baseDir.dirCount()-1; i>=0; i-- ) { if ( scanControl.isStopped() ) return; listDirectory(baseDir.getDir(i)); } progress(2000); if ( mHideEmptyDirs ) baseDir.removeEmptyDirs(); if ( scanControl.isStopped() ) return; ArrayList<FileInfo> filesForParsing = new ArrayList<FileInfo>(); int count = baseDir.fileCount(); for ( int i=0; i<count; i++ ) { FileInfo item = baseDir.getFile(i); boolean found = db.findByPathname(item); if ( found ) Log.v("cr3db", "File " + item.pathname + " is found in DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); boolean saveToDB = true; if ( !found && item.format.canParseProperties() ) { filesForParsing.add(item); saveToDB = false; } if ( !found && saveToDB ) { db.save(item); Log.v("cr3db", "File " + item.pathname + " is added to DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); } progress( 2000 + 3000 * i / count ); } // db lookup files count = filesForParsing.size(); for ( int i=0; i<count; i++ ) { if ( scanControl.isStopped() ) return; FileInfo item = filesForParsing.get(i); engine.scanBookProperties(item); db.save(item); Log.v("cr3db", "File " + item.pathname + " is added to DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); progress( 5000 + 5000 * i / count ); } if ( recursiveScan ) { if ( scanControl.isStopped() ) return; for ( int i=baseDir.dirCount()-1; i>=0; i-- ) scan(baseDir.getDir(i)); } } public void work() throws Exception { // scan (list) directories nextProgressTime = startTime + 1500; scan( baseDir ); } }); }
public void scanDirectory( final FileInfo baseDir, final Runnable readyCallback, final boolean recursiveScan, final ScanControl scanControl ) { final long startTime = System.currentTimeMillis(); listDirectory(baseDir); listSubtree( baseDir, 2, android.os.SystemClock.uptimeMillis() + 700 ); if ( (!getDirScanEnabled() || baseDir.isScanned) && !recursiveScan ) { readyCallback.run(); return; } engine.execute(new EngineTask() { long nextProgressTime = startTime + 2000; boolean progressShown = false; void progress( int percent ) { if ( recursiveScan ) return; // no progress dialog for recursive scan long ts = System.currentTimeMillis(); if ( ts>=nextProgressTime ) { engine.showProgress(percent, R.string.progress_scanning); nextProgressTime = ts + 1500; progressShown = true; } } public void done() { baseDir.isScanned = true; if ( progressShown ) engine.hideProgress(); readyCallback.run(); } public void fail(Exception e) { Log.e("cr3", "Exception while scanning directory " + baseDir.pathname, e); baseDir.isScanned = true; if ( progressShown ) engine.hideProgress(); readyCallback.run(); } public void scan( FileInfo baseDir ) { if ( baseDir.isRecentDir() ) return; //listDirectory(baseDir); progress(1000); if ( scanControl.isStopped() ) return; for ( int i=baseDir.dirCount()-1; i>=0; i-- ) { if ( scanControl.isStopped() ) return; listDirectory(baseDir.getDir(i)); } progress(2000); if ( mHideEmptyDirs ) baseDir.removeEmptyDirs(); if ( scanControl.isStopped() ) return; ArrayList<FileInfo> filesForParsing = new ArrayList<FileInfo>(); int count = baseDir.fileCount(); for ( int i=0; i<count; i++ ) { FileInfo item = baseDir.getFile(i); boolean found = db.findByPathname(item); if ( found ) Log.v("cr3db", "File " + item.pathname + " is found in DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); boolean saveToDB = true; if ( !found && item.format.canParseProperties() ) { filesForParsing.add(item); saveToDB = false; } if ( !found && saveToDB ) { db.save(item); Log.v("cr3db", "File " + item.pathname + " is added to DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); } progress( 2000 + 3000 * i / count ); } // db lookup files count = filesForParsing.size(); for ( int i=0; i<count; i++ ) { if ( scanControl.isStopped() ) return; FileInfo item = filesForParsing.get(i); engine.scanBookProperties(item); db.save(item); Log.v("cr3db", "File " + item.pathname + " is added to DB (id="+item.id+", title=" + item.title + ", authors=" + item.authors +")"); progress( 5000 + 5000 * i / count ); } if ( recursiveScan ) { if ( scanControl.isStopped() ) return; for ( int i=baseDir.dirCount()-1; i>=0; i-- ) scan(baseDir.getDir(i)); } } public void work() throws Exception { // scan (list) directories nextProgressTime = startTime + 1500; scan( baseDir ); } }); }
diff --git a/src/com/pokebros/android/pokemononline/NetworkService.java b/src/com/pokebros/android/pokemononline/NetworkService.java index 5fbba012..91844190 100644 --- a/src/com/pokebros/android/pokemononline/NetworkService.java +++ b/src/com/pokebros/android/pokemononline/NetworkService.java @@ -1,719 +1,719 @@ package com.pokebros.android.pokemononline; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.media.MediaPlayer; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.text.Html; import android.util.Log; import android.widget.Toast; import com.pokebros.android.pokemononline.battle.Battle; import com.pokebros.android.pokemononline.player.FullPlayerInfo; import com.pokebros.android.pokemononline.player.PlayerInfo; import com.pokebros.android.pokemononline.poke.ShallowBattlePoke; import com.pokebros.android.utilities.StringUtilities; public class NetworkService extends Service { static final String TAG = "Network Service"; final static String pkgName = "com.pokebros.android.pokemononline"; private final IBinder binder = new LocalBinder(); protected int NOTIFICATION = 4356; protected NotificationManager noteMan; //public Channel currentChannel = null; public LinkedList<Channel> joinedChannels = new LinkedList<Channel>(); Thread sThread, rThread; PokeClientSocket socket = null; boolean findingBattle = false; public ChatActivity chatActivity = null; public BattleActivity battleActivity = null; public LinkedList<IncomingChallenge> challenges = new LinkedList<IncomingChallenge>(); public boolean askedForPass = false; private String salt = null; public boolean failedConnect = false; public DataBaseHelper db; public String serverName = "Not Connected"; public final ProtocolVersion version = new ProtocolVersion(); public boolean serverSupportsZipCompression = false; @SuppressWarnings("unused") private byte []reconnectSecret; public boolean hasBattle() { return battle != null; } private FullPlayerInfo meLoginPlayer; public PlayerInfo mePlayer; public Battle battle = null;// = new Battle(); protected Hashtable<Integer, Channel> channels = new Hashtable<Integer, Channel>(); public Hashtable<Integer, PlayerInfo> players = new Hashtable<Integer, PlayerInfo>(); protected HashSet<Integer> pmedPlayers = new HashSet<Integer>(); Tier superTier = new Tier(); int bID = -1; public class LocalBinder extends Binder { NetworkService getService() { return NetworkService.this; } } /** * Is the player in any of the same channels as us? * @param pid the id of the player we are interested in * @return true if the player shares a channel with us, false otherwise */ public boolean isOnAnyChannel(int pid) { for (Channel c: channels.values()) { if (c.players.contains(pid)) { return true; } } return false; } /** * Called by a channel when a player leaves. If the player is not on any channel * and there's no special circumstances (as in PM), the player will get removed * @param pid The id of the player that left */ public void onPlayerLeaveChannel(int pid) { if (!isOnAnyChannel(pid) && !pmedPlayers.contains(pid)) { removePlayer(pid); } } /** * Removes a player from memory * @param pid The id of the player to remove */ public void removePlayer(int pid) { players.remove(pid); if (pmedPlayers.contains(pid)) { //TODO: close the PM? pmedPlayers.remove(pid); } } @Override // This is *NOT* called every time someone binds to us, I don't really know why // but onServiceConnected is correctly called in the activity sooo.... public IBinder onBind(Intent intent) { return binder; } @Override // This is called once public void onCreate() { db = new DataBaseHelper(NetworkService.this); showNotification(ChatActivity.class, "Chat"); noteMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); super.onCreate(); } @Override public void onDestroy() { // XXX TODO be more graceful Log.d(TAG, "NETWORK SERVICE DESTROYED; EXPECT BAD THINGS TO HAPPEN"); } public void connect(final String ip, final int port) { // XXX This should probably have a timeout new Thread(new Runnable() { public void run() { try { socket = new PokeClientSocket(ip, port); } catch (IOException e) { failedConnect = true; if(chatActivity != null) { chatActivity.notifyFailedConnection(); } return; } //socket.sendMessage(meLoginPlayer.serializeBytes(), Command.Login); Baos loginCmd = new Baos(); loginCmd.putBaos(version); //Protocol version /* Network Flags: hasClientType, hasVersionNumber, hasReconnect, hasDefaultChannel, hasAdditionalChannels, hasColor, hasTrainerInfo, hasNewTeam, hasEventSpecification, hasPluginList. */ loginCmd.putFlags(new boolean []{true,true}); //Network flags loginCmd.putString("android"); short versionCode; try { versionCode = (short)getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; } catch (NameNotFoundException e1) { versionCode = 0; } loginCmd.putShort(versionCode); loginCmd.putString(meLoginPlayer.nick()); /* Data Flags: supportsZipCompression, isLadderEnabled, wantsIdsWithMessages, isIdle */ loginCmd.putFlags(new boolean []{false,true,true}); socket.sendMessage(loginCmd, Command.Login); while(socket.isConnected()) { try { // Get some data from the wire socket.recvMessagePoll(); } catch (IOException e) { // Disconnected break; } catch (ParseException e) { // Got message that overflowed length from server. // No way to recover. // TODO die completely break; } Baos tmp; // Handle any messages that completed while ((tmp = socket.getMsg()) != null) { Bais msg = new Bais(tmp.toByteArray()); handleMsg(msg); } /* Do not use too much CPU */ try { Thread.sleep(50); } catch (InterruptedException e) { // Do nothing } } } }).start(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Bundle bundle = null; if (intent != null) // Intent can be null if service restarts after being killed // XXX We probably don't handle such restarts very gracefully bundle = intent.getExtras(); if (bundle != null && bundle.containsKey("loginPlayer")) { meLoginPlayer = new FullPlayerInfo(new Bais(bundle.getByteArray("loginPlayer"))); mePlayer = new PlayerInfo (meLoginPlayer); } if (bundle != null && bundle.containsKey("ip")) connect(bundle.getString("ip"), bundle.getShort("port")); return START_STICKY; } protected void showNotification(Class<?> toStart, String text, String note) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(R.drawable.icon) .setTicker(note) .setContentText(text) .setWhen(System.currentTimeMillis()) .setContentTitle("Pokemon Online"); // The PendingIntent to launch our activity if the user selects this notification PendingIntent notificationIntent = PendingIntent.getActivity(this, 0, new Intent(this, toStart), Intent.FLAG_ACTIVITY_NEW_TASK); builder.setContentIntent(notificationIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. mNotificationManager.notify(toStart.hashCode(), builder.build()); } protected void showNotification(Class<?> toStart, String text) { showNotification(toStart, text, text); } public void handleMsg(Bais msg) { byte i = msg.readByte(); Command c = Command.values()[i]; System.out.println("Received: " + c); switch (c) { case ChannelPlayers: case JoinChannel: case LeaveChannel: case BattleList: { Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else Log.e(TAG, "Received message for nonexistent channel"); break; } case VersionControl: { ProtocolVersion serverVersion = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { Log.d(TAG, "Server has newer protocol version than we expect"); } else if (serverVersion.compareTo(version) < 0) { Log.d(TAG, "PO Android uses newer protocol than Server"); } serverSupportsZipCompression = msg.readBool(); ProtocolVersion lastVersionWithoutFeatures = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutCompatBreak = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutMajorCompatBreak = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { if (lastVersionWithoutFeatures.compareTo(version) > 0) { Toast.makeText(this, R.string.new_server_features_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.minor_compat_break_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutMajorCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.major_compat_break_warning, Toast.LENGTH_LONG).show(); } } String serverName = msg.readString(); Log.d(TAG, "Server name is " + serverName); break; } case Register: { // Username not registered break; } case Login: { Bais flags = msg.readFlags(); Boolean hasReconnPass = flags.readBool(); if (hasReconnPass) { // Read byte array reconnectSecret = msg.readQByteArray(); } mePlayer = new PlayerInfo(msg); int numTiers = msg.readInt(); for (int j = 0; j < numTiers; j++) { // Tiers for each of our teams // TODO Do something with this info? msg.readString(); } players.put(mePlayer.id, mePlayer); break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier(msg.readByte(), msg.readString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier(msg.readByte(), msg.readString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChannelsList: { int numChannels = msg.readInt(); for(int j = 0; j < numChannels; j++) { int chanId = msg.readInt(); Channel ch = new Channel(chanId, msg.readString(), this); channels.put(chanId, ch); //addChannel(msg.readQString(),chanId); } Log.d(TAG, channels.toString()); break; } case PlayersList: { while (msg.available() != 0) { // While there's playerInfo's available PlayerInfo p = new PlayerInfo(msg); players.put(p.id, p); } break; } case SendMessage: { Bais netFlags = msg.readFlags(); boolean hasChannel = netFlags.readBool(); boolean hasId = netFlags.readBool(); Bais dataFlags = msg.readFlags(); boolean isHtml = dataFlags.readBool(); Channel chan = hasChannel ? channels.get(msg.readInt()) : null; PlayerInfo player = hasId ? players.get(msg.readInt()) : null; CharSequence message = msg.readString(); if (hasId) { CharSequence color = (player == null ? "orange" : player.color.toHexString()); CharSequence name = player.nick(); if (isHtml) { - message = Html.fromHtml("<span style='color:" + color + "'><b>" + name + - ": </b></span>" + message); + message = Html.fromHtml("<font color='" + color + "'><b>" + name + + ": </b></font>" + message); } else { - message = Html.fromHtml("<span style='color:" + color + "'><b>" + name + - ": </b></span>" + StringUtilities.escapeHtml((String)message)); + message = Html.fromHtml("<font color='" + color + "'><b>" + name + + ": </b></font>" + StringUtilities.escapeHtml((String)message)); } } else { message = isHtml ? Html.fromHtml((String)message) : message; } if (!hasChannel) { // Broadcast message if (chatActivity != null && message.toString().contains("Wrong password for this name.")) // XXX Is this still the message sent? chatActivity.makeToast(message.toString(), "long"); else { Iterator<Channel> it = joinedChannels.iterator(); while (it.hasNext()) { it.next().writeToHist(message); } } } else { if (chan == null) { Log.e(TAG, "Received message for nonexistent channel"); } else { chan.writeToHist(message); } } break; } /* case BattleList: case JoinChannel: case LeaveChannel: case ChannelBattle: { // case ChannelMessage: // case HtmlChannel: { Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else System.out.println("Received message for nonexistant channel"); break; // } case ServerName: { // serverName = msg.readQString(); // if (chatActivity != null) // chatActivity.updateTitle(); // break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier((byte)msg.read(), msg.readQString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier((byte)msg.read(), msg.readQString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChallengeStuff: { IncomingChallenge challenge = new IncomingChallenge(msg); challenge.setNick(players.get(challenge.opponent)); System.out.println("CHALLENGE STUFF: " + ChallengeEnums.ChallengeDesc.values()[challenge.desc]); switch(ChallengeEnums.ChallengeDesc.values()[challenge.desc]) { case Sent: if (challenge.isValidChallenge(players)) { challenges.addFirst(challenge); if (chatActivity != null && chatActivity.hasWindowFocus()) { chatActivity.notifyChallenge(); } else { Notification note = new Notification(R.drawable.icon, "You've been challenged by " + challenge.oppName + "!", System.currentTimeMillis()); note.setLatestEventInfo(this, "POAndroid", "You've been challenged!", PendingIntent.getActivity(this, 0, new Intent(NetworkService.this, ChatActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK)); noteMan.cancel(IncomingChallenge.note); noteMan.notify(IncomingChallenge.note, note); } } break; case Refused: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " refused your challenge", "short"); } break; case Busy: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " is busy", "short"); } break; case InvalidTeam: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid team", "long"); break; case InvalidGen: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid gen", "long"); break; } break; } case ChannelsList: { int numChannels = msg.readInt(); for(int k = 0; k < numChannels; k++) { int chanId = msg.readInt(); Channel ch = new Channel(chanId, msg.readQString(), this); channels.put(chanId, ch); //addChannel(msg.readQString(),chanId); } System.out.println(channels.toString()); break; } case ChannelPlayers: { Channel ch = channels.get(msg.readInt()); int numPlayers = msg.readInt(); if(ch != null) { for(int k = 0; k < numPlayers; k++) { int id = msg.readInt(); ch.addPlayer(players.get(id)); } } else System.out.println("Received message for nonexistant channel"); break; // } case HtmlMessage: { // String htmlMessage = msg.readQString(); // System.out.println("Html Message: " + htmlMessage); // break; }*/ case Logout: { // Only sent when player is in a PM with you and logs out int playerID = msg.readInt(); removePlayer(playerID); //System.out.println("Player " + playerID + " logged out."); break; } /*case BattleFinished: { int battleID = msg.readInt(); byte battleDesc = msg.readByte(); int id1 = msg.readInt(); int id2 = msg.readInt(); System.out.println("bID " + battleID + " battleDesc " + battleDesc + " id1 " + id1 + " id2 " + id2); String[] outcome = new String[]{" won by forfeit against ", " won against ", " tied with "}; if (battle != null && battle.bID == battleID) { if (mePlayer.id == id1 && battleDesc < 2) { showNotification(ChatActivity.class, "Chat", "You won!"); } else if (mePlayer.id == id2 && battleDesc < 2) { showNotification(ChatActivity.class, "Chat", "You lost!"); } else if (battleDesc == 2) { showNotification(ChatActivity.class, "Chat", "You tied!"); } if (players.get(id1) != null && players.get(id2) != null && battleDesc < 2) joinedChannels.peek().writeToHist(Html.fromHtml("<b><i>" + escapeHtml(players.get(id1).nick()) + outcome[battleDesc] + escapeHtml(players.get(id2).nick()) + ".</b></i>")); if (battleDesc == 0 || battleDesc == 3) { battle = null; if (battleActivity != null) battleActivity.end(); } } break; }*/ case SendPM: { int playerID = msg.readInt(); pmedPlayers.add(playerID); // Ignore the message String pm = new String("This user is running the Pokemon Online Android client and cannot respond to private messages."); Baos bb = new Baos(); bb.putInt(playerID); bb.putString(pm); socket.sendMessage(bb, Command.SendPM); break; }/* case SendTeam: { PlayerInfo p = new PlayerInfo(msg); if (players.containsKey(p.id)) { PlayerInfo player = players.get(p.id); player.update(p); Enumeration<Channel> e = channels.elements(); while (e.hasMoreElements()) { Channel ch = e.nextElement(); if (ch.players.containsKey(player.id)) { ch.updatePlayer(player); } } } break; } case BattleMessage: { msg.readInt(); // currently support only one battle, unneeded msg.readInt(); // discard the size, unneeded if (battle != null) battle.receiveCommand(msg); break; } case EngageBattle: { bID = msg.readInt(); int pID1 = msg.readInt(); int pID2 = msg.readInt(); if(pID1 == 0) { // This is us! BattleConf conf = new BattleConf(msg); // Start the battle battle = new Battle(conf, msg, players.get(conf.id(0)), players.get(conf.id(1)), mePlayer.id, bID, this); joinedChannels.peek().writeToHist("Battle between " + mePlayer.nick() + " and " + players.get(pID2).nick() + " started!"); Intent in; in = new Intent(this, BattleActivity.class); in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(in); findingBattle = false; } break; } case Login: { mePlayer = new PlayerInfo(msg); players.put(mePlayer.id, mePlayer); break; } case AskForPass: { salt = msg.readQString(); // XXX not sure what the second half is supposed to check // from analyze.cpp : 265 of PO's code if (salt.length() < 6) { // || strlen((" " + salt).toUtf8().data()) < 7) System.out.println("Protocol Error: The server requires insecure authentication"); break; } askedForPass = true; if (chatActivity != null && (chatActivity.hasWindowFocus() || chatActivity.progressDialog.isShowing())) { chatActivity.notifyAskForPass(); } break; } case AddChannel: { addChannel(msg.readQString(),msg.readInt()); break; } case RemoveChannel: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); break; } case ChanNameChange: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); channels.put(chanId, new Channel(chanId, msg.readQString(), this)); break; } case SendMessage: { String message = msg.readQString(); System.out.println(message); if (chatActivity != null && message.contains("Wrong password for this name.")) chatActivity.makeToast(message, "long"); else if (chatActivity != null && joinedChannels.peek() != null) joinedChannels.peek().writeToHist(message); break; } */default: { System.out.println("Unimplented message"); } } if (battle != null && battleActivity != null && battle.histDelta.length() != 0) battleActivity.updateBattleInfo(false); if (chatActivity != null && joinedChannels.peek() != null) chatActivity.updateChat(); } public void sendPass(String s) { askedForPass = false; MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); Baos hashPass = new Baos(); hashPass.putString(toHex(md5.digest(mashBytes(toHex(md5.digest(s.getBytes("ISO-8859-1"))).getBytes("ISO-8859-1"), salt.getBytes("ISO-8859-1"))))); socket.sendMessage(hashPass, Command.AskForPass); } catch (NoSuchAlgorithmException nsae) { System.out.println("Attempting authentication threw an exception: " + nsae); } catch (UnsupportedEncodingException uee) { System.out.println("Attempting authentication threw an exception: " + uee); } } private byte[] mashBytes(final byte[] a, final byte[] b) { byte[] ret = new byte[a.length + b.length]; System.arraycopy(a, 0, ret, 0, a.length); System.arraycopy(b, 0, ret, a.length, b.length); return ret; } private String toHex(byte[] b) { String ret = new BigInteger(1, b).toString(16); while (ret.length() < 32) ret = "0" + ret; return ret; } protected void herp() { System.out.println("HERP"); } protected void addChannel(String chanName, int chanId) { Channel c = new Channel(chanId, chanName, this); channels.put(chanId, c); if(chatActivity != null) chatActivity.addChannel(c); } public void playCry(ShallowBattlePoke poke) { new Thread(new CryPlayer(poke)).start(); } class CryPlayer implements Runnable { ShallowBattlePoke poke; public CryPlayer(ShallowBattlePoke poke) { this.poke = poke; } public void run() { int resID = getResources().getIdentifier("p" + poke.uID.pokeNum, "raw", pkgName); if (resID != 0) { MediaPlayer cryPlayer = MediaPlayer.create(NetworkService.this, resID); cryPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mp) { synchronized (mp) { mp.notify(); } } }); synchronized (cryPlayer) { cryPlayer.start(); try { cryPlayer.wait(10000); } catch (InterruptedException e) {} } cryPlayer.release(); synchronized (battle) { battle.notify(); } cryPlayer = null; } } } public void disconnect() { if (socket != null && socket.isConnected()) { socket.close(); } this.stopForeground(true); this.stopSelf(); } public PlayerInfo getPlayerByName(String playerName) { Enumeration<Integer> e = players.keys(); while(e.hasMoreElements()) { PlayerInfo info = players.get(e.nextElement()); if (info.nick().equals(playerName)) return info; } return null; } }
false
true
public void handleMsg(Bais msg) { byte i = msg.readByte(); Command c = Command.values()[i]; System.out.println("Received: " + c); switch (c) { case ChannelPlayers: case JoinChannel: case LeaveChannel: case BattleList: { Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else Log.e(TAG, "Received message for nonexistent channel"); break; } case VersionControl: { ProtocolVersion serverVersion = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { Log.d(TAG, "Server has newer protocol version than we expect"); } else if (serverVersion.compareTo(version) < 0) { Log.d(TAG, "PO Android uses newer protocol than Server"); } serverSupportsZipCompression = msg.readBool(); ProtocolVersion lastVersionWithoutFeatures = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutCompatBreak = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutMajorCompatBreak = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { if (lastVersionWithoutFeatures.compareTo(version) > 0) { Toast.makeText(this, R.string.new_server_features_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.minor_compat_break_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutMajorCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.major_compat_break_warning, Toast.LENGTH_LONG).show(); } } String serverName = msg.readString(); Log.d(TAG, "Server name is " + serverName); break; } case Register: { // Username not registered break; } case Login: { Bais flags = msg.readFlags(); Boolean hasReconnPass = flags.readBool(); if (hasReconnPass) { // Read byte array reconnectSecret = msg.readQByteArray(); } mePlayer = new PlayerInfo(msg); int numTiers = msg.readInt(); for (int j = 0; j < numTiers; j++) { // Tiers for each of our teams // TODO Do something with this info? msg.readString(); } players.put(mePlayer.id, mePlayer); break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier(msg.readByte(), msg.readString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier(msg.readByte(), msg.readString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChannelsList: { int numChannels = msg.readInt(); for(int j = 0; j < numChannels; j++) { int chanId = msg.readInt(); Channel ch = new Channel(chanId, msg.readString(), this); channels.put(chanId, ch); //addChannel(msg.readQString(),chanId); } Log.d(TAG, channels.toString()); break; } case PlayersList: { while (msg.available() != 0) { // While there's playerInfo's available PlayerInfo p = new PlayerInfo(msg); players.put(p.id, p); } break; } case SendMessage: { Bais netFlags = msg.readFlags(); boolean hasChannel = netFlags.readBool(); boolean hasId = netFlags.readBool(); Bais dataFlags = msg.readFlags(); boolean isHtml = dataFlags.readBool(); Channel chan = hasChannel ? channels.get(msg.readInt()) : null; PlayerInfo player = hasId ? players.get(msg.readInt()) : null; CharSequence message = msg.readString(); if (hasId) { CharSequence color = (player == null ? "orange" : player.color.toHexString()); CharSequence name = player.nick(); if (isHtml) { message = Html.fromHtml("<span style='color:" + color + "'><b>" + name + ": </b></span>" + message); } else { message = Html.fromHtml("<span style='color:" + color + "'><b>" + name + ": </b></span>" + StringUtilities.escapeHtml((String)message)); } } else { message = isHtml ? Html.fromHtml((String)message) : message; } if (!hasChannel) { // Broadcast message if (chatActivity != null && message.toString().contains("Wrong password for this name.")) // XXX Is this still the message sent? chatActivity.makeToast(message.toString(), "long"); else { Iterator<Channel> it = joinedChannels.iterator(); while (it.hasNext()) { it.next().writeToHist(message); } } } else { if (chan == null) { Log.e(TAG, "Received message for nonexistent channel"); } else { chan.writeToHist(message); } } break; } /* case BattleList: case JoinChannel: case LeaveChannel: case ChannelBattle: { // case ChannelMessage: // case HtmlChannel: { Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else System.out.println("Received message for nonexistant channel"); break; // } case ServerName: { // serverName = msg.readQString(); // if (chatActivity != null) // chatActivity.updateTitle(); // break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier((byte)msg.read(), msg.readQString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier((byte)msg.read(), msg.readQString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChallengeStuff: { IncomingChallenge challenge = new IncomingChallenge(msg); challenge.setNick(players.get(challenge.opponent)); System.out.println("CHALLENGE STUFF: " + ChallengeEnums.ChallengeDesc.values()[challenge.desc]); switch(ChallengeEnums.ChallengeDesc.values()[challenge.desc]) { case Sent: if (challenge.isValidChallenge(players)) { challenges.addFirst(challenge); if (chatActivity != null && chatActivity.hasWindowFocus()) { chatActivity.notifyChallenge(); } else { Notification note = new Notification(R.drawable.icon, "You've been challenged by " + challenge.oppName + "!", System.currentTimeMillis()); note.setLatestEventInfo(this, "POAndroid", "You've been challenged!", PendingIntent.getActivity(this, 0, new Intent(NetworkService.this, ChatActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK)); noteMan.cancel(IncomingChallenge.note); noteMan.notify(IncomingChallenge.note, note); } } break; case Refused: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " refused your challenge", "short"); } break; case Busy: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " is busy", "short"); } break; case InvalidTeam: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid team", "long"); break; case InvalidGen: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid gen", "long"); break; } break; } case ChannelsList: { int numChannels = msg.readInt(); for(int k = 0; k < numChannels; k++) { int chanId = msg.readInt(); Channel ch = new Channel(chanId, msg.readQString(), this); channels.put(chanId, ch); //addChannel(msg.readQString(),chanId); } System.out.println(channels.toString()); break; } case ChannelPlayers: { Channel ch = channels.get(msg.readInt()); int numPlayers = msg.readInt(); if(ch != null) { for(int k = 0; k < numPlayers; k++) { int id = msg.readInt(); ch.addPlayer(players.get(id)); } } else System.out.println("Received message for nonexistant channel"); break; // } case HtmlMessage: { // String htmlMessage = msg.readQString(); // System.out.println("Html Message: " + htmlMessage); // break; }*/ case Logout: { // Only sent when player is in a PM with you and logs out int playerID = msg.readInt(); removePlayer(playerID); //System.out.println("Player " + playerID + " logged out."); break; } /*case BattleFinished: { int battleID = msg.readInt(); byte battleDesc = msg.readByte(); int id1 = msg.readInt(); int id2 = msg.readInt(); System.out.println("bID " + battleID + " battleDesc " + battleDesc + " id1 " + id1 + " id2 " + id2); String[] outcome = new String[]{" won by forfeit against ", " won against ", " tied with "}; if (battle != null && battle.bID == battleID) { if (mePlayer.id == id1 && battleDesc < 2) { showNotification(ChatActivity.class, "Chat", "You won!"); } else if (mePlayer.id == id2 && battleDesc < 2) { showNotification(ChatActivity.class, "Chat", "You lost!"); } else if (battleDesc == 2) { showNotification(ChatActivity.class, "Chat", "You tied!"); } if (players.get(id1) != null && players.get(id2) != null && battleDesc < 2) joinedChannels.peek().writeToHist(Html.fromHtml("<b><i>" + escapeHtml(players.get(id1).nick()) + outcome[battleDesc] + escapeHtml(players.get(id2).nick()) + ".</b></i>")); if (battleDesc == 0 || battleDesc == 3) { battle = null; if (battleActivity != null) battleActivity.end(); } } break; }*/ case SendPM: { int playerID = msg.readInt(); pmedPlayers.add(playerID); // Ignore the message String pm = new String("This user is running the Pokemon Online Android client and cannot respond to private messages."); Baos bb = new Baos(); bb.putInt(playerID); bb.putString(pm); socket.sendMessage(bb, Command.SendPM); break; }/* case SendTeam: { PlayerInfo p = new PlayerInfo(msg); if (players.containsKey(p.id)) { PlayerInfo player = players.get(p.id); player.update(p); Enumeration<Channel> e = channels.elements(); while (e.hasMoreElements()) { Channel ch = e.nextElement(); if (ch.players.containsKey(player.id)) { ch.updatePlayer(player); } } } break; } case BattleMessage: { msg.readInt(); // currently support only one battle, unneeded msg.readInt(); // discard the size, unneeded if (battle != null) battle.receiveCommand(msg); break; } case EngageBattle: { bID = msg.readInt(); int pID1 = msg.readInt(); int pID2 = msg.readInt(); if(pID1 == 0) { // This is us! BattleConf conf = new BattleConf(msg); // Start the battle battle = new Battle(conf, msg, players.get(conf.id(0)), players.get(conf.id(1)), mePlayer.id, bID, this); joinedChannels.peek().writeToHist("Battle between " + mePlayer.nick() + " and " + players.get(pID2).nick() + " started!"); Intent in; in = new Intent(this, BattleActivity.class); in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(in); findingBattle = false; } break; } case Login: { mePlayer = new PlayerInfo(msg); players.put(mePlayer.id, mePlayer); break; } case AskForPass: { salt = msg.readQString(); // XXX not sure what the second half is supposed to check // from analyze.cpp : 265 of PO's code if (salt.length() < 6) { // || strlen((" " + salt).toUtf8().data()) < 7) System.out.println("Protocol Error: The server requires insecure authentication"); break; } askedForPass = true; if (chatActivity != null && (chatActivity.hasWindowFocus() || chatActivity.progressDialog.isShowing())) { chatActivity.notifyAskForPass(); } break; } case AddChannel: { addChannel(msg.readQString(),msg.readInt()); break; } case RemoveChannel: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); break; } case ChanNameChange: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); channels.put(chanId, new Channel(chanId, msg.readQString(), this)); break; } case SendMessage: { String message = msg.readQString(); System.out.println(message); if (chatActivity != null && message.contains("Wrong password for this name.")) chatActivity.makeToast(message, "long"); else if (chatActivity != null && joinedChannels.peek() != null) joinedChannels.peek().writeToHist(message); break; } */default: { System.out.println("Unimplented message"); } } if (battle != null && battleActivity != null && battle.histDelta.length() != 0) battleActivity.updateBattleInfo(false); if (chatActivity != null && joinedChannels.peek() != null) chatActivity.updateChat(); }
public void handleMsg(Bais msg) { byte i = msg.readByte(); Command c = Command.values()[i]; System.out.println("Received: " + c); switch (c) { case ChannelPlayers: case JoinChannel: case LeaveChannel: case BattleList: { Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else Log.e(TAG, "Received message for nonexistent channel"); break; } case VersionControl: { ProtocolVersion serverVersion = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { Log.d(TAG, "Server has newer protocol version than we expect"); } else if (serverVersion.compareTo(version) < 0) { Log.d(TAG, "PO Android uses newer protocol than Server"); } serverSupportsZipCompression = msg.readBool(); ProtocolVersion lastVersionWithoutFeatures = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutCompatBreak = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutMajorCompatBreak = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { if (lastVersionWithoutFeatures.compareTo(version) > 0) { Toast.makeText(this, R.string.new_server_features_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.minor_compat_break_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutMajorCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.major_compat_break_warning, Toast.LENGTH_LONG).show(); } } String serverName = msg.readString(); Log.d(TAG, "Server name is " + serverName); break; } case Register: { // Username not registered break; } case Login: { Bais flags = msg.readFlags(); Boolean hasReconnPass = flags.readBool(); if (hasReconnPass) { // Read byte array reconnectSecret = msg.readQByteArray(); } mePlayer = new PlayerInfo(msg); int numTiers = msg.readInt(); for (int j = 0; j < numTiers; j++) { // Tiers for each of our teams // TODO Do something with this info? msg.readString(); } players.put(mePlayer.id, mePlayer); break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier(msg.readByte(), msg.readString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier(msg.readByte(), msg.readString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChannelsList: { int numChannels = msg.readInt(); for(int j = 0; j < numChannels; j++) { int chanId = msg.readInt(); Channel ch = new Channel(chanId, msg.readString(), this); channels.put(chanId, ch); //addChannel(msg.readQString(),chanId); } Log.d(TAG, channels.toString()); break; } case PlayersList: { while (msg.available() != 0) { // While there's playerInfo's available PlayerInfo p = new PlayerInfo(msg); players.put(p.id, p); } break; } case SendMessage: { Bais netFlags = msg.readFlags(); boolean hasChannel = netFlags.readBool(); boolean hasId = netFlags.readBool(); Bais dataFlags = msg.readFlags(); boolean isHtml = dataFlags.readBool(); Channel chan = hasChannel ? channels.get(msg.readInt()) : null; PlayerInfo player = hasId ? players.get(msg.readInt()) : null; CharSequence message = msg.readString(); if (hasId) { CharSequence color = (player == null ? "orange" : player.color.toHexString()); CharSequence name = player.nick(); if (isHtml) { message = Html.fromHtml("<font color='" + color + "'><b>" + name + ": </b></font>" + message); } else { message = Html.fromHtml("<font color='" + color + "'><b>" + name + ": </b></font>" + StringUtilities.escapeHtml((String)message)); } } else { message = isHtml ? Html.fromHtml((String)message) : message; } if (!hasChannel) { // Broadcast message if (chatActivity != null && message.toString().contains("Wrong password for this name.")) // XXX Is this still the message sent? chatActivity.makeToast(message.toString(), "long"); else { Iterator<Channel> it = joinedChannels.iterator(); while (it.hasNext()) { it.next().writeToHist(message); } } } else { if (chan == null) { Log.e(TAG, "Received message for nonexistent channel"); } else { chan.writeToHist(message); } } break; } /* case BattleList: case JoinChannel: case LeaveChannel: case ChannelBattle: { // case ChannelMessage: // case HtmlChannel: { Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else System.out.println("Received message for nonexistant channel"); break; // } case ServerName: { // serverName = msg.readQString(); // if (chatActivity != null) // chatActivity.updateTitle(); // break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier((byte)msg.read(), msg.readQString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier((byte)msg.read(), msg.readQString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChallengeStuff: { IncomingChallenge challenge = new IncomingChallenge(msg); challenge.setNick(players.get(challenge.opponent)); System.out.println("CHALLENGE STUFF: " + ChallengeEnums.ChallengeDesc.values()[challenge.desc]); switch(ChallengeEnums.ChallengeDesc.values()[challenge.desc]) { case Sent: if (challenge.isValidChallenge(players)) { challenges.addFirst(challenge); if (chatActivity != null && chatActivity.hasWindowFocus()) { chatActivity.notifyChallenge(); } else { Notification note = new Notification(R.drawable.icon, "You've been challenged by " + challenge.oppName + "!", System.currentTimeMillis()); note.setLatestEventInfo(this, "POAndroid", "You've been challenged!", PendingIntent.getActivity(this, 0, new Intent(NetworkService.this, ChatActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK)); noteMan.cancel(IncomingChallenge.note); noteMan.notify(IncomingChallenge.note, note); } } break; case Refused: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " refused your challenge", "short"); } break; case Busy: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " is busy", "short"); } break; case InvalidTeam: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid team", "long"); break; case InvalidGen: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid gen", "long"); break; } break; } case ChannelsList: { int numChannels = msg.readInt(); for(int k = 0; k < numChannels; k++) { int chanId = msg.readInt(); Channel ch = new Channel(chanId, msg.readQString(), this); channels.put(chanId, ch); //addChannel(msg.readQString(),chanId); } System.out.println(channels.toString()); break; } case ChannelPlayers: { Channel ch = channels.get(msg.readInt()); int numPlayers = msg.readInt(); if(ch != null) { for(int k = 0; k < numPlayers; k++) { int id = msg.readInt(); ch.addPlayer(players.get(id)); } } else System.out.println("Received message for nonexistant channel"); break; // } case HtmlMessage: { // String htmlMessage = msg.readQString(); // System.out.println("Html Message: " + htmlMessage); // break; }*/ case Logout: { // Only sent when player is in a PM with you and logs out int playerID = msg.readInt(); removePlayer(playerID); //System.out.println("Player " + playerID + " logged out."); break; } /*case BattleFinished: { int battleID = msg.readInt(); byte battleDesc = msg.readByte(); int id1 = msg.readInt(); int id2 = msg.readInt(); System.out.println("bID " + battleID + " battleDesc " + battleDesc + " id1 " + id1 + " id2 " + id2); String[] outcome = new String[]{" won by forfeit against ", " won against ", " tied with "}; if (battle != null && battle.bID == battleID) { if (mePlayer.id == id1 && battleDesc < 2) { showNotification(ChatActivity.class, "Chat", "You won!"); } else if (mePlayer.id == id2 && battleDesc < 2) { showNotification(ChatActivity.class, "Chat", "You lost!"); } else if (battleDesc == 2) { showNotification(ChatActivity.class, "Chat", "You tied!"); } if (players.get(id1) != null && players.get(id2) != null && battleDesc < 2) joinedChannels.peek().writeToHist(Html.fromHtml("<b><i>" + escapeHtml(players.get(id1).nick()) + outcome[battleDesc] + escapeHtml(players.get(id2).nick()) + ".</b></i>")); if (battleDesc == 0 || battleDesc == 3) { battle = null; if (battleActivity != null) battleActivity.end(); } } break; }*/ case SendPM: { int playerID = msg.readInt(); pmedPlayers.add(playerID); // Ignore the message String pm = new String("This user is running the Pokemon Online Android client and cannot respond to private messages."); Baos bb = new Baos(); bb.putInt(playerID); bb.putString(pm); socket.sendMessage(bb, Command.SendPM); break; }/* case SendTeam: { PlayerInfo p = new PlayerInfo(msg); if (players.containsKey(p.id)) { PlayerInfo player = players.get(p.id); player.update(p); Enumeration<Channel> e = channels.elements(); while (e.hasMoreElements()) { Channel ch = e.nextElement(); if (ch.players.containsKey(player.id)) { ch.updatePlayer(player); } } } break; } case BattleMessage: { msg.readInt(); // currently support only one battle, unneeded msg.readInt(); // discard the size, unneeded if (battle != null) battle.receiveCommand(msg); break; } case EngageBattle: { bID = msg.readInt(); int pID1 = msg.readInt(); int pID2 = msg.readInt(); if(pID1 == 0) { // This is us! BattleConf conf = new BattleConf(msg); // Start the battle battle = new Battle(conf, msg, players.get(conf.id(0)), players.get(conf.id(1)), mePlayer.id, bID, this); joinedChannels.peek().writeToHist("Battle between " + mePlayer.nick() + " and " + players.get(pID2).nick() + " started!"); Intent in; in = new Intent(this, BattleActivity.class); in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(in); findingBattle = false; } break; } case Login: { mePlayer = new PlayerInfo(msg); players.put(mePlayer.id, mePlayer); break; } case AskForPass: { salt = msg.readQString(); // XXX not sure what the second half is supposed to check // from analyze.cpp : 265 of PO's code if (salt.length() < 6) { // || strlen((" " + salt).toUtf8().data()) < 7) System.out.println("Protocol Error: The server requires insecure authentication"); break; } askedForPass = true; if (chatActivity != null && (chatActivity.hasWindowFocus() || chatActivity.progressDialog.isShowing())) { chatActivity.notifyAskForPass(); } break; } case AddChannel: { addChannel(msg.readQString(),msg.readInt()); break; } case RemoveChannel: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); break; } case ChanNameChange: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); channels.put(chanId, new Channel(chanId, msg.readQString(), this)); break; } case SendMessage: { String message = msg.readQString(); System.out.println(message); if (chatActivity != null && message.contains("Wrong password for this name.")) chatActivity.makeToast(message, "long"); else if (chatActivity != null && joinedChannels.peek() != null) joinedChannels.peek().writeToHist(message); break; } */default: { System.out.println("Unimplented message"); } } if (battle != null && battleActivity != null && battle.histDelta.length() != 0) battleActivity.updateBattleInfo(false); if (chatActivity != null && joinedChannels.peek() != null) chatActivity.updateChat(); }
diff --git a/android/src/org/microemu/android/device/AndroidDevice.java b/android/src/org/microemu/android/device/AndroidDevice.java index a847fae7..461425af 100644 --- a/android/src/org/microemu/android/device/AndroidDevice.java +++ b/android/src/org/microemu/android/device/AndroidDevice.java @@ -1,186 +1,189 @@ /** * MicroEmulator * Copyright (C) 2008 Bartek Teodorczyk <[email protected]> * * It is licensed under the following two licenses as alternatives: * 1. GNU Lesser General Public License (the "LGPL") version 2.1 or any newer version * 2. Apache License (the "AL") Version 2.0 * * You may not use this file except in compliance with at least one of * the above two licenses. * * You may obtain a copy of the LGPL at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * * You may obtain a copy of the AL 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 LGPL or the AL for the specific language governing permissions and * limitations. * * @version $Id: AndroidDevice.java 2236 2009-12-07 09:49:31Z [email protected] $ */ package org.microemu.android.device; import java.util.HashMap; import java.util.Map; import java.util.Vector; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Image; import javax.microedition.lcdui.Item; import javax.microedition.lcdui.TextBox; import javax.microedition.lcdui.TextField; import org.microemu.android.MicroEmulatorActivity; import org.microemu.android.device.ui.AndroidCanvasUI; import org.microemu.android.device.ui.AndroidCommandUI; import org.microemu.android.device.ui.AndroidTextBoxUI; import org.microemu.android.device.ui.AndroidTextFieldUI; import org.microemu.device.Device; import org.microemu.device.DeviceDisplay; import org.microemu.device.EmulatorContext; import org.microemu.device.FontManager; import org.microemu.device.InputMethod; import org.microemu.device.ui.CanvasUI; import org.microemu.device.ui.CommandUI; import org.microemu.device.ui.EventDispatcher; import org.microemu.device.ui.TextBoxUI; import org.microemu.device.ui.TextFieldUI; import org.microemu.device.ui.UIFactory; import android.content.Context; import android.os.Vibrator; public class AndroidDevice implements Device { private EmulatorContext emulatorContext; private MicroEmulatorActivity activity; private UIFactory ui = new UIFactory() { public EventDispatcher createEventDispatcher(Display display) { EventDispatcher eventDispatcher = new EventDispatcher(); Thread thread = new Thread(eventDispatcher, EventDispatcher.EVENT_DISPATCHER_NAME); thread.setDaemon(true); thread.start(); return eventDispatcher; } public CommandUI createCommandUI(Command command) { return new AndroidCommandUI(activity, command); } public CanvasUI createCanvasUI(Canvas canvas) { return new AndroidCanvasUI(activity, canvas); } public TextBoxUI createTextBoxUI(TextBox textBox) { return new AndroidTextBoxUI(activity, textBox); } public TextFieldUI createTextFieldUI(TextField textField) { return new AndroidTextFieldUI(activity, textField); } }; private Map systemProperties = new HashMap(); private Vector softButtons = new Vector(); public AndroidDevice(EmulatorContext emulatorContext, MicroEmulatorActivity activity) { this.emulatorContext = emulatorContext; this.activity = activity; } public void destroy() { // TODO Auto-generated method stub } public Vector getButtons() { // TODO Auto-generated method stub return null; } public DeviceDisplay getDeviceDisplay() { return emulatorContext.getDeviceDisplay(); } public FontManager getFontManager() { return emulatorContext.getDeviceFontManager(); } public InputMethod getInputMethod() { return emulatorContext.getDeviceInputMethod(); } public UIFactory getUIFactory() { return ui; } public String getName() { // TODO Auto-generated method stub return null; } public Image getNormalImage() { // TODO Auto-generated method stub return null; } public Image getOverImage() { // TODO Auto-generated method stub return null; } public Image getPressedImage() { // TODO Auto-generated method stub return null; } public Vector getSoftButtons() { return softButtons; } public Map getSystemProperties() { return systemProperties; } public boolean hasPointerEvents() { return true; } public boolean hasPointerMotionEvents() { return true; } public boolean hasRepeatEvents() { return true; } public void init() { // TODO Auto-generated method stub } - public boolean vibrate(int duration) { - Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); - if (vibrator != null) { - vibrator.vibrate(duration); - return true; - } else { - return false; - } + public boolean vibrate(final int duration) { + final Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); + if (vibrator == null) + return false; + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + vibrator.vibrate(duration); + } + }); + return true; } }
true
true
public boolean vibrate(int duration) { Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); if (vibrator != null) { vibrator.vibrate(duration); return true; } else { return false; } }
public boolean vibrate(final int duration) { final Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); if (vibrator == null) return false; activity.runOnUiThread(new Runnable() { @Override public void run() { vibrator.vibrate(duration); } }); return true; }
diff --git a/mbt/src/test/org/tigris/mbt/generators/A_StarPathGeneratorTest.java b/mbt/src/test/org/tigris/mbt/generators/A_StarPathGeneratorTest.java index e4d1551..febc4fb 100644 --- a/mbt/src/test/org/tigris/mbt/generators/A_StarPathGeneratorTest.java +++ b/mbt/src/test/org/tigris/mbt/generators/A_StarPathGeneratorTest.java @@ -1,143 +1,143 @@ package test.org.tigris.mbt.generators; import org.tigris.mbt.Util; import org.tigris.mbt.conditions.ReachedEdge; import org.tigris.mbt.conditions.ReachedState; import org.tigris.mbt.generators.PathGenerator; import org.tigris.mbt.generators.A_StarPathGenerator; import org.tigris.mbt.graph.Edge; import org.tigris.mbt.graph.Graph; import org.tigris.mbt.graph.Vertex; import org.tigris.mbt.machines.ExtendedFiniteStateMachine; import org.tigris.mbt.machines.FiniteStateMachine; import junit.framework.TestCase; public class A_StarPathGeneratorTest extends TestCase { Graph graph; Vertex start; Vertex v1; Vertex v2; Edge e0; Edge e1; Edge e2; Edge e3; protected void setUp() throws Exception { super.setUp(); graph = new Graph(); start = Util.addVertexToGraph(graph, "Start"); v1 = Util.addVertexToGraph(graph, "V1"); v2 = Util.addVertexToGraph(graph, "V2"); e0 = Util.addEdgeToGraph(graph, start, v1, "E0", null, null, "x=1;y=new Vector()"); e1 = Util.addEdgeToGraph(graph, v1, v2, "E1", null, null, "x=2"); e2 = Util.addEdgeToGraph(graph, v2, v2, "E2", null, "x<4", "x++"); e3 = Util.addEdgeToGraph(graph, v2, v1, "E3", null, "y.size()<3", "y.add(x)"); } protected void tearDown() throws Exception { super.tearDown(); graph.removeAllEdges(); graph.removeAllVertices(); start = v1 = v2 = null; e0 = e1 = e2 = e3 = null; } public void test_FSM_StateStop() { PathGenerator pathGenerator = new A_StarPathGenerator(); pathGenerator.setStopCondition(new ReachedState("V2")); pathGenerator.setMachine(new FiniteStateMachine(graph)); String[] stepPair; stepPair = pathGenerator.getNext(); assertEquals("E0", stepPair[0]); assertEquals("V1", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2", stepPair[1]); assertFalse(pathGenerator.hasNext()); } public void test_FSM_EdgeStop() { PathGenerator pathGenerator = new A_StarPathGenerator(); pathGenerator.setStopCondition(new ReachedEdge("E2")); pathGenerator.setMachine(new FiniteStateMachine(graph)); String[] stepPair; stepPair = pathGenerator.getNext(); assertEquals("E0", stepPair[0]); assertEquals("V1", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E2", stepPair[0]); assertEquals("V2", stepPair[1]); assertFalse(pathGenerator.hasNext()); } public void test_EFSM_StateStop() { PathGenerator pathGenerator = new A_StarPathGenerator(); - pathGenerator.setStopCondition(new ReachedState("V1/x=3;y=[2, 3, 3];") ); + pathGenerator.setStopCondition(new ReachedState("V1/x=3;y=\\[2, 3, 3\\];") ); pathGenerator.setMachine(new ExtendedFiniteStateMachine(graph)); String[] stepPair; stepPair = pathGenerator.getNext(); assertEquals("E0", stepPair[0]); assertEquals("V1/x=1;y=[];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E3", stepPair[0]); assertEquals("V1/x=2;y=[2];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[2];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E2", stepPair[0]); assertEquals("V2/x=3;y=[2];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E3", stepPair[0]); assertEquals("V1/x=3;y=[2, 3];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[2, 3];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E2", stepPair[0]); assertEquals("V2/x=3;y=[2, 3];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E3", stepPair[0]); assertEquals("V1/x=3;y=[2, 3, 3];", stepPair[1]); assertFalse(pathGenerator.hasNext()); } public void test_EFSM_EdgeStop() { PathGenerator pathGenerator = new A_StarPathGenerator(); pathGenerator.setStopCondition(new ReachedEdge("E2")); pathGenerator.setMachine(new ExtendedFiniteStateMachine(graph)); String[] stepPair; stepPair = pathGenerator.getNext(); assertEquals("E0", stepPair[0]); assertEquals("V1/x=1;y=[];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E2", stepPair[0]); assertEquals("V2/x=3;y=[];", stepPair[1]); assertFalse(pathGenerator.hasNext()); } }
true
true
public void test_EFSM_StateStop() { PathGenerator pathGenerator = new A_StarPathGenerator(); pathGenerator.setStopCondition(new ReachedState("V1/x=3;y=[2, 3, 3];") ); pathGenerator.setMachine(new ExtendedFiniteStateMachine(graph)); String[] stepPair; stepPair = pathGenerator.getNext(); assertEquals("E0", stepPair[0]); assertEquals("V1/x=1;y=[];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E3", stepPair[0]); assertEquals("V1/x=2;y=[2];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[2];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E2", stepPair[0]); assertEquals("V2/x=3;y=[2];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E3", stepPair[0]); assertEquals("V1/x=3;y=[2, 3];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[2, 3];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E2", stepPair[0]); assertEquals("V2/x=3;y=[2, 3];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E3", stepPair[0]); assertEquals("V1/x=3;y=[2, 3, 3];", stepPair[1]); assertFalse(pathGenerator.hasNext()); }
public void test_EFSM_StateStop() { PathGenerator pathGenerator = new A_StarPathGenerator(); pathGenerator.setStopCondition(new ReachedState("V1/x=3;y=\\[2, 3, 3\\];") ); pathGenerator.setMachine(new ExtendedFiniteStateMachine(graph)); String[] stepPair; stepPair = pathGenerator.getNext(); assertEquals("E0", stepPair[0]); assertEquals("V1/x=1;y=[];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E3", stepPair[0]); assertEquals("V1/x=2;y=[2];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[2];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E2", stepPair[0]); assertEquals("V2/x=3;y=[2];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E3", stepPair[0]); assertEquals("V1/x=3;y=[2, 3];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E1", stepPair[0]); assertEquals("V2/x=2;y=[2, 3];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E2", stepPair[0]); assertEquals("V2/x=3;y=[2, 3];", stepPair[1]); stepPair = pathGenerator.getNext(); assertEquals("E3", stepPair[0]); assertEquals("V1/x=3;y=[2, 3, 3];", stepPair[1]); assertFalse(pathGenerator.hasNext()); }
diff --git a/core/src/main/java/org/alveolo/simpa/jdbc/JdbcStore.java b/core/src/main/java/org/alveolo/simpa/jdbc/JdbcStore.java index 453f271..09bcef1 100644 --- a/core/src/main/java/org/alveolo/simpa/jdbc/JdbcStore.java +++ b/core/src/main/java/org/alveolo/simpa/jdbc/JdbcStore.java @@ -1,631 +1,631 @@ package org.alveolo.simpa.jdbc; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.EntityNotFoundException; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NonUniqueResultException; import javax.persistence.PersistenceException; import javax.persistence.SequenceGenerator; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.Attribute.PersistentAttributeType; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.ManagedType; import javax.sql.DataSource; import org.alveolo.simpa.EntityStore; import org.alveolo.simpa.metamodel.AttributeImpl; import org.alveolo.simpa.metamodel.MetamodelImpl; import org.alveolo.simpa.metamodel.SingularAttributeImpl; import org.alveolo.simpa.query.AttrSelect; import org.alveolo.simpa.query.Conjunction; import org.alveolo.simpa.query.Group; import org.alveolo.simpa.query.Order; import org.alveolo.simpa.query.Query; import org.alveolo.simpa.query.Raw; import org.alveolo.simpa.query.Select; import org.alveolo.simpa.query.SqlBuilder; import org.alveolo.simpa.query.WhereBuilder; import org.alveolo.simpa.util.EntityUtil; public class JdbcStore implements EntityStore, RawCallbacks, QueryCallbacks { protected final DefaultNaming naming = new DefaultNaming(); protected final DataSource ds; protected final MetamodelImpl metamodel; public JdbcStore(DataSource ds, List<Class<?>> classes) { this.ds = ds; this.metamodel = new MetamodelImpl(classes); } @Override public MetamodelImpl getMetamodel() { return metamodel; } public long nextval(SequenceGenerator annotation) { try { Connection con = acquireConnection(); try { String name = naming.getQualifiedSequenceName(annotation); PreparedStatement stmt = con.prepareStatement("SELECT nextval('" + name + "')"); try { ResultSet rset = stmt.executeQuery(); try { if (!rset.next()) { throw new PersistenceException("Error fetching sequence value: " + name); } Object id = rset.getObject(1); if (rset.next()) { throw new PersistenceException("Only one sequence value is expected: " + name); } return (Long) id; } finally { rset.close(); } } finally { stmt.close(); } } finally { releaseConnection(con); } } catch (SQLException e) { throw new PersistenceException(e); } } @Override public void insert(Object entity) { EntityType<?> type = metamodel.entity(entity.getClass()); List<AttributeValue> values = getInsertableValues(type, entity); for (AttributeValue av : values) { if (av.attribute.getPersistentAttributeType() != PersistentAttributeType.BASIC) { continue; } SingularAttributeImpl<?, ?> attribute = (SingularAttributeImpl<?, ?>) av.attribute; if (!attribute.isId()) { continue; } } StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO ").append(naming.getQualifiedTableName(type.getJavaType())).append(" ("); for (Iterator<AttributeValue> i = values.iterator(); i.hasNext();) { sql.append(naming.getColumnName(i.next().attribute.getJavaMember())); if (i.hasNext()) { sql.append(','); } } sql.append(") VALUES ("); for (Iterator<AttributeValue> i = values.iterator(); i.hasNext();) { i.next(); sql.append("?"); if (i.hasNext()) { sql.append(','); } } sql.append(")"); try { Connection con = acquireConnection(); try { PreparedStatement stmt = con.prepareStatement(sql.toString()); try { int index = 0; for (AttributeValue cv : values) { JdbcUtil.setParameter(stmt, ++index, cv.attribute, cv.value); } int updated = stmt.executeUpdate(); if (updated == 0) { throw new EntityNotFoundException(type.getName() + " with the given identity is not found"); } } finally { stmt.close(); } } finally { releaseConnection(con); } } catch (SQLException e) { throw new PersistenceException(e); } } @Override public void update(Object entity) { EntityType<?> type = metamodel.entity(entity.getClass()); List<AttributeValue> values = getUpdatableValues(type, entity); StringBuilder sql = new StringBuilder(); sql.append("UPDATE ").append(naming.getQualifiedTableName(type.getJavaType())).append(" SET "); for (Iterator<AttributeValue> i = values.iterator(); i.hasNext();) { sql.append(naming.getColumnName(i.next().attribute.getJavaMember())).append("=?"); if (i.hasNext()) { sql.append(','); } } Conjunction conjunction = EntityUtil.conditionsForEntity(type, entity); appendWhereSection(new JdbcSqlAppendVisitor(sql), conjunction); try { Connection con = acquireConnection(); try { PreparedStatement stmt = con.prepareStatement(sql.toString()); try { JdbcSetParameterVisitor visitor = new JdbcSetParameterVisitor(stmt); for (AttributeValue av : values) { visitor.visit(av); } conjunction.accept(visitor); int updated = stmt.executeUpdate(); if (updated == 0) { throw new EntityNotFoundException(type.getName() + " with the given identity is not found"); } } finally { stmt.close(); } } finally { releaseConnection(con); } } catch (SQLException e) { throw new PersistenceException(e); } } @Override public void delete(Object entity) { EntityType<?> type = metamodel.entity(entity.getClass()); delete(type, EntityUtil.conditionsForEntity(type, entity)); } @Override public <T> void delete(Class<T> javaType, Object id) { EntityType<T> type = metamodel.entity(javaType); delete(type, EntityUtil.conditionsForId(type, id)); } private <T> void delete(EntityType<T> type, Conjunction conjunction) { StringBuilder sql = new StringBuilder(); sql.append("DELETE"); JdbcSqlAppendVisitor visitor = new JdbcSqlAppendVisitor(sql); appendFromSection(visitor, type); appendWhereSection(visitor, conjunction); try { Connection con = acquireConnection(); try { PreparedStatement stmt = con.prepareStatement(sql.toString()); try { conjunction.accept(new JdbcSetParameterVisitor(stmt)); int updated = stmt.executeUpdate(); if (updated == 0) { throw new EntityNotFoundException(type.getName() + " with the given identity is not found"); } } finally { stmt.close(); } } finally { releaseConnection(con); } } catch (SQLException e) { throw new PersistenceException(e); } } @Override public <T> T find(Class<T> javaType, Object id) { EntityType<T> type = metamodel.entity(javaType); return from(javaType).eq(type.getId(type.getIdType().getJavaType()), id).find(); } @Override public <T> SqlBuilder sql(String sql, Object... values) { SqlBuilder builder = new SqlBuilder(this); builder.sql(sql, values); return builder; } @Override public <T> WhereBuilder<T> from(Class<T> type) { return new WhereBuilder<>(this, type); } @Override public <T> T find(Class<T> javaType, List<Raw> fragments) { List<T> list = list(javaType, fragments); int size = list.size(); if (size == 0) { return null; } if (size > 1) { throw new NonUniqueResultException("Expecting single result but found: " + size); } return list.get(0); } @Override public <T> List<T> list(Class<T> javaType, List<Raw> fragments) { StringBuilder sql = new StringBuilder(); for (Iterator<Raw> i = fragments.iterator(); i.hasNext();) { sql.append(i.next().sql); if (i.hasNext()) { sql.append(' '); } } List<T> list = new ArrayList<>(); try { Connection con = acquireConnection(); try { PreparedStatement stmt = con.prepareStatement(sql.toString()); try { JdbcSetParameterVisitor visitor = new JdbcSetParameterVisitor(stmt); for (Raw r : fragments) { visitor.visit(r); } ResultSet rset = stmt.executeQuery(); try { RawMapper<T> mapper = new RawMapper<>(rset.getMetaData(), javaType); while (rset.next()) { T entity = newInstance(javaType); mapper.setEntityValues(rset, entity); list.add(entity); } } finally { rset.close(); } } finally { stmt.close(); } } finally { releaseConnection(con); } } catch (ReflectiveOperationException | SQLException e) { throw new PersistenceException(e); } return list; } @Override public <T> int delete(Query<T> query) { EntityType<T> type = metamodel.entity(query.type); StringBuilder sql = new StringBuilder(); sql.append("DELETE"); JdbcSqlAppendVisitor visitor = new JdbcSqlAppendVisitor(sql); appendFromSection(visitor, type); appendWhereSection(visitor, query.where); try { Connection con = acquireConnection(); try { PreparedStatement stmt = con.prepareStatement(sql.toString()); try { query.where.accept(new JdbcSetParameterVisitor(stmt)); return stmt.executeUpdate(); } finally { stmt.close(); } } finally { releaseConnection(con); } } catch (SQLException e) { throw new PersistenceException(e); } } @Override public <T> T find(Query<T> query) { List<T> list = list(query); int size = list.size(); if (size == 0) { return null; } if (size > 1) { throw new NonUniqueResultException("Expecting single result but found: " + size); } return list.get(0); } @Override public <T> List<T> list(Query<T> query) { EntityType<T> type = metamodel.entity(query.type); StringBuilder sql = new StringBuilder(); List<Select> select = query.select; if (select == null) { select = new ArrayList<>(); for (Attribute<? super T, ?> a : type.getAttributes()) { select.add(new AttrSelect(a)); } } { JdbcSqlAppendVisitor visitor = new JdbcSqlAppendVisitor(sql); appendSelectSection(visitor, select); appendFromSection(visitor, type); appendWhereSection(visitor, query.where); appendGroupBySection(visitor, query.groups); appendHavingSection(visitor, query.having); appendOrderBySection(visitor, query.order); } if (query.offset != null) { sql.append(" OFFSET " + query.offset); } - if (query.offset != null) { + if (query.fetch != null) { sql.append(" LIMIT " + query.fetch); } List<T> list = new ArrayList<>(); try { Connection con = acquireConnection(); try { PreparedStatement stmt = con.prepareStatement(sql.toString()); try { JdbcSetParameterVisitor visitor = new JdbcSetParameterVisitor(stmt); query.where.accept(visitor); for (Group g : query.groups) g.accept(visitor); query.having.accept(visitor); for (Order o : query.order) o.accept(visitor); ResultSet rset = stmt.executeQuery(); try { JdbcRowMapperVisitor<T> results = (query.select != null && select.size() == 1) ? new JdbcSingleValueMapperVisitor<>(rset, type.getJavaType()) : new JdbcRowMapperVisitor<>(rset, type.getJavaType()); while (rset.next()) { for (Select s : select) s.accept(results); // if (query.select != null && select.size() == 1) { // Select s = select.iterator().next(); // AttrSelect as = (AttrSelect) s; // @SuppressWarnings("unchecked") // A hack, Path<X> should fix type problems // T value = (T) EntityUtil.getValue(as.attribute, results.getEntity()); // list.add(value); // } else { list.add(results.getEntity()); // } results.reset(); } } finally { rset.close(); } } finally { stmt.close(); } } finally { releaseConnection(con); } } catch (SQLException e) { throw new PersistenceException(e); } return list; } protected Connection acquireConnection() throws SQLException { // TODO: Better transactions: JTA, Spring return ds.getConnection(); } protected void releaseConnection(Connection con) throws SQLException { // TODO: Better transactions: JTA, Spring con.close(); } // TODO: for collecting insertable/updatable valued use single function with custom filter as parameter private List<AttributeValue> getInsertableValues(EntityType<?> type, Object entity) { return addInsertableValues(new ArrayList<AttributeValue>(), type, entity); } private List<AttributeValue> addInsertableValues(List<AttributeValue> values, ManagedType<?> type, Object object) { for (Attribute<?, ?> attribute : type.getAttributes()) { if (isInsertable(attribute)) { Object value = EntityUtil.getValue(attribute, object); if (attribute.getPersistentAttributeType() == PersistentAttributeType.EMBEDDED) { SingularAttributeImpl<?, ?> singular = (SingularAttributeImpl<?, ?>) attribute; ManagedType<?> t = (ManagedType<?>) singular.getType(); addInsertableValues(values, t, value); continue; } GeneratedValue generated = ((AttributeImpl<?, ?>) attribute).getAnnotation(GeneratedValue.class); if (generated != null) { IdGenerator generator = metamodel.getGenerator(generated.generator()); Field field = (Field) attribute.getJavaMember(); // TODO: method value = generator.next(this); JdbcUtil.setPersistenceValue(field, object, value); } values.add(new AttributeValue(attribute, value)); } } return values; } private List<AttributeValue> getUpdatableValues(EntityType<?> type, Object entity) { return addUpdatableValues(new ArrayList<AttributeValue>(), type, entity); } private List<AttributeValue> addUpdatableValues(List<AttributeValue> values, ManagedType<?> type, Object object) { for (Attribute<?, ?> attribute : type.getAttributes()) { if (isUpdatable(attribute)) { Object value = EntityUtil.getValue(attribute, object); if (attribute.getPersistentAttributeType() == PersistentAttributeType.EMBEDDED) { SingularAttributeImpl<?, ?> singular = (SingularAttributeImpl<?, ?>) attribute; ManagedType<?> t = (ManagedType<?>) singular.getType(); addUpdatableValues(values, t, value); continue; } values.add(new AttributeValue(attribute, value)); } } return values; } private void appendSelectSection(JdbcSqlAppendVisitor visitor, List<Select> select) { visitor.append("SELECT "); for (Iterator<Select> i = select.iterator(); i.hasNext();) { i.next().accept(visitor); if (i.hasNext()) { visitor.append(","); } } } private void appendFromSection(JdbcSqlAppendVisitor visitor, EntityType<?> type) { visitor.append(" FROM ").append(naming.getQualifiedTableName(type.getJavaType())); } private void appendWhereSection(JdbcSqlAppendVisitor visitor, Conjunction conjunction) { if (conjunction.conditions.size() > 0) { visitor.append(" WHERE "); conjunction.accept(visitor); } } private void appendGroupBySection(JdbcSqlAppendVisitor visitor, List<Group> groups) { if (groups.size() > 0) { visitor.append(" GROUP BY "); for (Iterator<Group> i = groups.iterator(); i.hasNext();) { i.next().accept(visitor); if (i.hasNext()) { visitor.append(","); } } } } private void appendHavingSection(JdbcSqlAppendVisitor visitor, Conjunction conjunction) { if (conjunction.conditions.size() > 0) { visitor.append(" HAVING "); conjunction.accept(visitor); } } private void appendOrderBySection(JdbcSqlAppendVisitor visitor, List<Order> order) { if (order.size() > 0) { visitor.append(" ORDER BY "); for (Iterator<Order> i = order.iterator(); i.hasNext();) { i.next().accept(visitor); if (i.hasNext()) { visitor.append(","); } } } } private boolean isInsertable(Attribute<?, ?> attribute) { // TODO: Support for plural etc. SingularAttributeImpl<?, ?> singular = (SingularAttributeImpl<?, ?>) attribute; Column column = singular.getAnnotation(Column.class); if (column != null) { return column.insertable(); } return true; } private boolean isUpdatable(Attribute<?, ?> attribute) { // TODO: Support for plural etc. SingularAttributeImpl<?, ?> singular = (SingularAttributeImpl<?, ?>) attribute; if (singular.getAnnotation(Id.class) != null || singular.getAnnotation(EmbeddedId.class) != null) { return false; } Column column = singular.getAnnotation(Column.class); if (column != null) { return column.updatable(); } return true; } private static <T> T newInstance(Class<T> type) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Constructor<T> constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); T entity = constructor.newInstance(); return entity; } }
true
true
public <T> List<T> list(Query<T> query) { EntityType<T> type = metamodel.entity(query.type); StringBuilder sql = new StringBuilder(); List<Select> select = query.select; if (select == null) { select = new ArrayList<>(); for (Attribute<? super T, ?> a : type.getAttributes()) { select.add(new AttrSelect(a)); } } { JdbcSqlAppendVisitor visitor = new JdbcSqlAppendVisitor(sql); appendSelectSection(visitor, select); appendFromSection(visitor, type); appendWhereSection(visitor, query.where); appendGroupBySection(visitor, query.groups); appendHavingSection(visitor, query.having); appendOrderBySection(visitor, query.order); } if (query.offset != null) { sql.append(" OFFSET " + query.offset); } if (query.offset != null) { sql.append(" LIMIT " + query.fetch); } List<T> list = new ArrayList<>(); try { Connection con = acquireConnection(); try { PreparedStatement stmt = con.prepareStatement(sql.toString()); try { JdbcSetParameterVisitor visitor = new JdbcSetParameterVisitor(stmt); query.where.accept(visitor); for (Group g : query.groups) g.accept(visitor); query.having.accept(visitor); for (Order o : query.order) o.accept(visitor); ResultSet rset = stmt.executeQuery(); try { JdbcRowMapperVisitor<T> results = (query.select != null && select.size() == 1) ? new JdbcSingleValueMapperVisitor<>(rset, type.getJavaType()) : new JdbcRowMapperVisitor<>(rset, type.getJavaType()); while (rset.next()) { for (Select s : select) s.accept(results); // if (query.select != null && select.size() == 1) { // Select s = select.iterator().next(); // AttrSelect as = (AttrSelect) s; // @SuppressWarnings("unchecked") // A hack, Path<X> should fix type problems // T value = (T) EntityUtil.getValue(as.attribute, results.getEntity()); // list.add(value); // } else { list.add(results.getEntity()); // } results.reset(); } } finally { rset.close(); } } finally { stmt.close(); } } finally { releaseConnection(con); } } catch (SQLException e) { throw new PersistenceException(e); } return list; }
public <T> List<T> list(Query<T> query) { EntityType<T> type = metamodel.entity(query.type); StringBuilder sql = new StringBuilder(); List<Select> select = query.select; if (select == null) { select = new ArrayList<>(); for (Attribute<? super T, ?> a : type.getAttributes()) { select.add(new AttrSelect(a)); } } { JdbcSqlAppendVisitor visitor = new JdbcSqlAppendVisitor(sql); appendSelectSection(visitor, select); appendFromSection(visitor, type); appendWhereSection(visitor, query.where); appendGroupBySection(visitor, query.groups); appendHavingSection(visitor, query.having); appendOrderBySection(visitor, query.order); } if (query.offset != null) { sql.append(" OFFSET " + query.offset); } if (query.fetch != null) { sql.append(" LIMIT " + query.fetch); } List<T> list = new ArrayList<>(); try { Connection con = acquireConnection(); try { PreparedStatement stmt = con.prepareStatement(sql.toString()); try { JdbcSetParameterVisitor visitor = new JdbcSetParameterVisitor(stmt); query.where.accept(visitor); for (Group g : query.groups) g.accept(visitor); query.having.accept(visitor); for (Order o : query.order) o.accept(visitor); ResultSet rset = stmt.executeQuery(); try { JdbcRowMapperVisitor<T> results = (query.select != null && select.size() == 1) ? new JdbcSingleValueMapperVisitor<>(rset, type.getJavaType()) : new JdbcRowMapperVisitor<>(rset, type.getJavaType()); while (rset.next()) { for (Select s : select) s.accept(results); // if (query.select != null && select.size() == 1) { // Select s = select.iterator().next(); // AttrSelect as = (AttrSelect) s; // @SuppressWarnings("unchecked") // A hack, Path<X> should fix type problems // T value = (T) EntityUtil.getValue(as.attribute, results.getEntity()); // list.add(value); // } else { list.add(results.getEntity()); // } results.reset(); } } finally { rset.close(); } } finally { stmt.close(); } } finally { releaseConnection(con); } } catch (SQLException e) { throw new PersistenceException(e); } return list; }
diff --git a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java index 1e3656495..9d1ded99f 100644 --- a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java +++ b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java @@ -1,456 +1,456 @@ package org.apache.solr.cloud; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.net.MalformedURLException; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.request.AbstractUpdateRequest; import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.cloud.SafeStopThread; import org.apache.solr.common.cloud.ZkCoreNodeProps; import org.apache.solr.common.cloud.ZkNodeProps; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.CoreDescriptor; import org.apache.solr.core.RequestHandlers.LazyRequestHandlerWrapper; import org.apache.solr.core.SolrCore; import org.apache.solr.handler.ReplicationHandler; import org.apache.solr.request.LocalSolrQueryRequest; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrRequestHandler; import org.apache.solr.request.SolrRequestInfo; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.update.CommitUpdateCommand; import org.apache.solr.update.PeerSync; import org.apache.solr.update.UpdateLog; import org.apache.solr.update.UpdateLog.RecoveryInfo; import org.apache.solr.update.processor.DistributedUpdateProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RecoveryStrategy extends Thread implements SafeStopThread { private static final int MAX_RETRIES = 500; private static final int INTERRUPTED = MAX_RETRIES + 1; private static final int START_TIMEOUT = 100; private static final String REPLICATION_HANDLER = "/replication"; private static Logger log = LoggerFactory.getLogger(RecoveryStrategy.class); private volatile boolean close = false; private ZkController zkController; private String baseUrl; private String coreZkNodeName; private ZkStateReader zkStateReader; private volatile String coreName; private int retries; private boolean recoveringAfterStartup; private CoreContainer cc; public RecoveryStrategy(CoreContainer cc, String name) { this.cc = cc; this.coreName = name; setName("RecoveryThread"); zkController = cc.getZkController(); zkStateReader = zkController.getZkStateReader(); baseUrl = zkController.getBaseUrl(); coreZkNodeName = zkController.getNodeName() + "_" + coreName; } public void setRecoveringAfterStartup(boolean recoveringAfterStartup) { this.recoveringAfterStartup = recoveringAfterStartup; } // make sure any threads stop retrying public void close() { close = true; } private void recoveryFailed(final SolrCore core, final ZkController zkController, final String baseUrl, final String shardZkNodeName, final CoreDescriptor cd) { SolrException.log(log, "Recovery failed - I give up."); zkController.publishAsRecoveryFailed(baseUrl, cd, shardZkNodeName, core.getName()); close = true; } private void replicate(String nodeName, SolrCore core, ZkNodeProps leaderprops, String baseUrl) throws SolrServerException, IOException { String leaderBaseUrl = leaderprops.get(ZkStateReader.BASE_URL_PROP); ZkCoreNodeProps leaderCNodeProps = new ZkCoreNodeProps(leaderprops); String leaderUrl = leaderCNodeProps.getCoreUrl(); log.info("Attempting to replicate from " + leaderUrl); // if we are the leader, either we are trying to recover faster // then our ephemeral timed out or we are the only node if (!leaderBaseUrl.equals(baseUrl)) { // send commit commitOnLeader(leaderUrl); // use rep handler directly, so we can do this sync rather than async SolrRequestHandler handler = core.getRequestHandler(REPLICATION_HANDLER); if (handler instanceof LazyRequestHandlerWrapper) { handler = ((LazyRequestHandlerWrapper)handler).getWrappedHandler(); } ReplicationHandler replicationHandler = (ReplicationHandler) handler; if (replicationHandler == null) { throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "Skipping recovery, no " + REPLICATION_HANDLER + " handler found"); } ModifiableSolrParams solrParams = new ModifiableSolrParams(); solrParams.set(ReplicationHandler.MASTER_URL, leaderUrl + "replication"); if (close) retries = INTERRUPTED; boolean success = replicationHandler.doFetch(solrParams, true); // TODO: look into making sure force=true does not download files we already have if (!success) { throw new SolrException(ErrorCode.SERVER_ERROR, "Replication for recovery failed."); } // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() + " replicated " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits + " from " + leaderUrl + " gen:" + core.getDeletionPolicy().getLatestCommit().getGeneration() + " data:" + core.getDataDir()); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } } } private void commitOnLeader(String leaderUrl) throws MalformedURLException, SolrServerException, IOException { CommonsHttpSolrServer server = new CommonsHttpSolrServer(leaderUrl); server.setConnectionTimeout(30000); server.setSoTimeout(30000); UpdateRequest ureq = new UpdateRequest(); ureq.setParams(new ModifiableSolrParams()); ureq.getParams().set(DistributedUpdateProcessor.COMMIT_END_POINT, true); ureq.setAction(AbstractUpdateRequest.ACTION.COMMIT, false, true).process( server); server.commit(); server.shutdown(); } private void sendPrepRecoveryCmd(String leaderBaseUrl, String leaderCoreName) throws MalformedURLException, SolrServerException, IOException { CommonsHttpSolrServer server = new CommonsHttpSolrServer(leaderBaseUrl); server.setConnectionTimeout(45000); server.setSoTimeout(45000); WaitForState prepCmd = new WaitForState(); prepCmd.setCoreName(leaderCoreName); prepCmd.setNodeName(zkController.getNodeName()); prepCmd.setCoreNodeName(coreZkNodeName); prepCmd.setState(ZkStateReader.RECOVERING); prepCmd.setCheckLive(true); prepCmd.setPauseFor(6000); server.request(prepCmd); server.shutdown(); } @Override public void run() { SolrCore core = cc.getCore(coreName); if (core == null) { SolrException.log(log, "SolrCore not found - cannot recover:" + coreName); return; } // set request info for logging SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams()); SolrQueryResponse rsp = new SolrQueryResponse(); SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, rsp)); try { doRecovery(core); } finally { SolrRequestInfo.clearRequestInfo(); } } public void doRecovery(SolrCore core) { boolean replayed = false; - boolean succesfulRecovery = false; + boolean successfulRecovery = false; UpdateLog ulog; try { ulog = core.getUpdateHandler().getUpdateLog(); if (ulog == null) { SolrException.log(log, "No UpdateLog found - cannot recover"); recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); return; } } finally { core.close(); } List<Long> startingRecentVersions; UpdateLog.RecentUpdates startingRecentUpdates = ulog.getRecentUpdates(); try { startingRecentVersions = startingRecentUpdates.getVersions(ulog.numRecordsToKeep); } finally { startingRecentUpdates.close(); } List<Long> reallyStartingVersions = ulog.getStartingVersions(); if (reallyStartingVersions != null && recoveringAfterStartup) { int oldIdx = 0; // index of the start of the old list in the current list long firstStartingVersion = reallyStartingVersions.size() > 0 ? reallyStartingVersions.get(0) : 0; for (; oldIdx<startingRecentVersions.size(); oldIdx++) { if (startingRecentVersions.get(oldIdx) == firstStartingVersion) break; } if (oldIdx > 0) { log.info("####### Found new versions added after startup: num=" + oldIdx); } // TODO: only log at debug level in the future (or move to oldIdx > 0 block) log.info("###### startupVersions=" + reallyStartingVersions); log.info("###### currentVersions=" + startingRecentVersions); } if (recoveringAfterStartup) { // if we're recovering after startup (i.e. we have been down), then we need to know what the last versions were // when we went down. startingRecentVersions = reallyStartingVersions; } boolean firstTime = true; - while (!succesfulRecovery && !close && !isInterrupted()) { // don't use interruption or it will close channels though + while (!successfulRecovery && !close && !isInterrupted()) { // don't use interruption or it will close channels though core = cc.getCore(coreName); if (core == null) { SolrException.log(log, "SolrCore not found - cannot recover:" + coreName); return; } try { // first thing we just try to sync zkController.publish(core.getCoreDescriptor(), ZkStateReader.RECOVERING); CloudDescriptor cloudDesc = core.getCoreDescriptor() .getCloudDescriptor(); ZkNodeProps leaderprops = zkStateReader.getLeaderProps( cloudDesc.getCollectionName(), cloudDesc.getShardId()); String leaderBaseUrl = leaderprops.get(ZkStateReader.BASE_URL_PROP); String leaderCoreName = leaderprops.get(ZkStateReader.CORE_NAME_PROP); String leaderUrl = ZkCoreNodeProps.getCoreUrl(leaderBaseUrl, leaderCoreName); sendPrepRecoveryCmd(leaderBaseUrl, leaderCoreName); // first thing we just try to sync if (firstTime) { firstTime = false; // only try sync the first time through the loop log.info("Attempting to PeerSync from " + leaderUrl + " recoveringAfterStartup="+recoveringAfterStartup); // System.out.println("Attempting to PeerSync from " + leaderUrl // + " i am:" + zkController.getNodeName()); PeerSync peerSync = new PeerSync(core, Collections.singletonList(leaderUrl), ulog.numRecordsToKeep); peerSync.setStartingVersions(startingRecentVersions); boolean syncSuccess = peerSync.sync(); if (syncSuccess) { SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams()); core.getUpdateHandler().commit(new CommitUpdateCommand(req, false)); - log.info("Sync Recovery was succesful - registering as Active"); + log.info("Sync Recovery was successful - registering as Active"); // System.out - // .println("Sync Recovery was succesful - registering as Active " + // .println("Sync Recovery was successful - registering as Active " // + zkController.getNodeName()); // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = // core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() // + " synched " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } // sync success - register as active and return zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); - succesfulRecovery = true; + successfulRecovery = true; close = true; return; } log.info("Sync Recovery was not successful - trying replication"); } //System.out.println("Sync Recovery was not successful - trying replication"); log.info("Begin buffering updates"); ulog.bufferUpdates(); replayed = false; try { replicate(zkController.getNodeName(), core, leaderprops, leaderUrl); replay(ulog); replayed = true; - log.info("Recovery was succesful - registering as Active"); + log.info("Recovery was successful - registering as Active"); // if there are pending recovery requests, don't advert as active zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); close = true; - succesfulRecovery = true; + successfulRecovery = true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (!replayed) { try { ulog.dropBufferedUpdates(); } catch (Throwable t) { SolrException.log(log, "", t); } } } } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (core != null) { core.close(); } } - if (!succesfulRecovery) { + if (!successfulRecovery) { // lets pause for a moment and we need to try again... // TODO: we don't want to retry for some problems? // Or do a fall off retry... try { SolrException.log(log, "Recovery failed - trying again..."); retries++; if (retries >= MAX_RETRIES) { if (retries == INTERRUPTED) { } else { // TODO: for now, give up after X tries - should we do more? core = cc.getCore(coreName); try { recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); } finally { if (core != null) { core.close(); } } } break; } } catch (Exception e) { SolrException.log(log, "", e); } try { Thread.sleep(Math.min(START_TIMEOUT * retries, 60000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } } log.info("Finished recovery process"); } } private Future<RecoveryInfo> replay(UpdateLog ulog) throws InterruptedException, ExecutionException, TimeoutException { Future<RecoveryInfo> future = ulog.applyBufferedUpdates(); if (future == null) { // no replay needed\ log.info("No replay needed"); } else { log.info("Replaying buffered documents"); // wait for replay future.get(); } // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() + " replayed " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } return future; } public boolean isClosed() { return close; } }
false
true
public void doRecovery(SolrCore core) { boolean replayed = false; boolean succesfulRecovery = false; UpdateLog ulog; try { ulog = core.getUpdateHandler().getUpdateLog(); if (ulog == null) { SolrException.log(log, "No UpdateLog found - cannot recover"); recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); return; } } finally { core.close(); } List<Long> startingRecentVersions; UpdateLog.RecentUpdates startingRecentUpdates = ulog.getRecentUpdates(); try { startingRecentVersions = startingRecentUpdates.getVersions(ulog.numRecordsToKeep); } finally { startingRecentUpdates.close(); } List<Long> reallyStartingVersions = ulog.getStartingVersions(); if (reallyStartingVersions != null && recoveringAfterStartup) { int oldIdx = 0; // index of the start of the old list in the current list long firstStartingVersion = reallyStartingVersions.size() > 0 ? reallyStartingVersions.get(0) : 0; for (; oldIdx<startingRecentVersions.size(); oldIdx++) { if (startingRecentVersions.get(oldIdx) == firstStartingVersion) break; } if (oldIdx > 0) { log.info("####### Found new versions added after startup: num=" + oldIdx); } // TODO: only log at debug level in the future (or move to oldIdx > 0 block) log.info("###### startupVersions=" + reallyStartingVersions); log.info("###### currentVersions=" + startingRecentVersions); } if (recoveringAfterStartup) { // if we're recovering after startup (i.e. we have been down), then we need to know what the last versions were // when we went down. startingRecentVersions = reallyStartingVersions; } boolean firstTime = true; while (!succesfulRecovery && !close && !isInterrupted()) { // don't use interruption or it will close channels though core = cc.getCore(coreName); if (core == null) { SolrException.log(log, "SolrCore not found - cannot recover:" + coreName); return; } try { // first thing we just try to sync zkController.publish(core.getCoreDescriptor(), ZkStateReader.RECOVERING); CloudDescriptor cloudDesc = core.getCoreDescriptor() .getCloudDescriptor(); ZkNodeProps leaderprops = zkStateReader.getLeaderProps( cloudDesc.getCollectionName(), cloudDesc.getShardId()); String leaderBaseUrl = leaderprops.get(ZkStateReader.BASE_URL_PROP); String leaderCoreName = leaderprops.get(ZkStateReader.CORE_NAME_PROP); String leaderUrl = ZkCoreNodeProps.getCoreUrl(leaderBaseUrl, leaderCoreName); sendPrepRecoveryCmd(leaderBaseUrl, leaderCoreName); // first thing we just try to sync if (firstTime) { firstTime = false; // only try sync the first time through the loop log.info("Attempting to PeerSync from " + leaderUrl + " recoveringAfterStartup="+recoveringAfterStartup); // System.out.println("Attempting to PeerSync from " + leaderUrl // + " i am:" + zkController.getNodeName()); PeerSync peerSync = new PeerSync(core, Collections.singletonList(leaderUrl), ulog.numRecordsToKeep); peerSync.setStartingVersions(startingRecentVersions); boolean syncSuccess = peerSync.sync(); if (syncSuccess) { SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams()); core.getUpdateHandler().commit(new CommitUpdateCommand(req, false)); log.info("Sync Recovery was succesful - registering as Active"); // System.out // .println("Sync Recovery was succesful - registering as Active " // + zkController.getNodeName()); // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = // core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() // + " synched " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } // sync success - register as active and return zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); succesfulRecovery = true; close = true; return; } log.info("Sync Recovery was not successful - trying replication"); } //System.out.println("Sync Recovery was not successful - trying replication"); log.info("Begin buffering updates"); ulog.bufferUpdates(); replayed = false; try { replicate(zkController.getNodeName(), core, leaderprops, leaderUrl); replay(ulog); replayed = true; log.info("Recovery was succesful - registering as Active"); // if there are pending recovery requests, don't advert as active zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); close = true; succesfulRecovery = true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (!replayed) { try { ulog.dropBufferedUpdates(); } catch (Throwable t) { SolrException.log(log, "", t); } } } } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (core != null) { core.close(); } } if (!succesfulRecovery) { // lets pause for a moment and we need to try again... // TODO: we don't want to retry for some problems? // Or do a fall off retry... try { SolrException.log(log, "Recovery failed - trying again..."); retries++; if (retries >= MAX_RETRIES) { if (retries == INTERRUPTED) { } else { // TODO: for now, give up after X tries - should we do more? core = cc.getCore(coreName); try { recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); } finally { if (core != null) { core.close(); } } } break; } } catch (Exception e) { SolrException.log(log, "", e); } try { Thread.sleep(Math.min(START_TIMEOUT * retries, 60000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } } log.info("Finished recovery process"); } }
public void doRecovery(SolrCore core) { boolean replayed = false; boolean successfulRecovery = false; UpdateLog ulog; try { ulog = core.getUpdateHandler().getUpdateLog(); if (ulog == null) { SolrException.log(log, "No UpdateLog found - cannot recover"); recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); return; } } finally { core.close(); } List<Long> startingRecentVersions; UpdateLog.RecentUpdates startingRecentUpdates = ulog.getRecentUpdates(); try { startingRecentVersions = startingRecentUpdates.getVersions(ulog.numRecordsToKeep); } finally { startingRecentUpdates.close(); } List<Long> reallyStartingVersions = ulog.getStartingVersions(); if (reallyStartingVersions != null && recoveringAfterStartup) { int oldIdx = 0; // index of the start of the old list in the current list long firstStartingVersion = reallyStartingVersions.size() > 0 ? reallyStartingVersions.get(0) : 0; for (; oldIdx<startingRecentVersions.size(); oldIdx++) { if (startingRecentVersions.get(oldIdx) == firstStartingVersion) break; } if (oldIdx > 0) { log.info("####### Found new versions added after startup: num=" + oldIdx); } // TODO: only log at debug level in the future (or move to oldIdx > 0 block) log.info("###### startupVersions=" + reallyStartingVersions); log.info("###### currentVersions=" + startingRecentVersions); } if (recoveringAfterStartup) { // if we're recovering after startup (i.e. we have been down), then we need to know what the last versions were // when we went down. startingRecentVersions = reallyStartingVersions; } boolean firstTime = true; while (!successfulRecovery && !close && !isInterrupted()) { // don't use interruption or it will close channels though core = cc.getCore(coreName); if (core == null) { SolrException.log(log, "SolrCore not found - cannot recover:" + coreName); return; } try { // first thing we just try to sync zkController.publish(core.getCoreDescriptor(), ZkStateReader.RECOVERING); CloudDescriptor cloudDesc = core.getCoreDescriptor() .getCloudDescriptor(); ZkNodeProps leaderprops = zkStateReader.getLeaderProps( cloudDesc.getCollectionName(), cloudDesc.getShardId()); String leaderBaseUrl = leaderprops.get(ZkStateReader.BASE_URL_PROP); String leaderCoreName = leaderprops.get(ZkStateReader.CORE_NAME_PROP); String leaderUrl = ZkCoreNodeProps.getCoreUrl(leaderBaseUrl, leaderCoreName); sendPrepRecoveryCmd(leaderBaseUrl, leaderCoreName); // first thing we just try to sync if (firstTime) { firstTime = false; // only try sync the first time through the loop log.info("Attempting to PeerSync from " + leaderUrl + " recoveringAfterStartup="+recoveringAfterStartup); // System.out.println("Attempting to PeerSync from " + leaderUrl // + " i am:" + zkController.getNodeName()); PeerSync peerSync = new PeerSync(core, Collections.singletonList(leaderUrl), ulog.numRecordsToKeep); peerSync.setStartingVersions(startingRecentVersions); boolean syncSuccess = peerSync.sync(); if (syncSuccess) { SolrQueryRequest req = new LocalSolrQueryRequest(core, new ModifiableSolrParams()); core.getUpdateHandler().commit(new CommitUpdateCommand(req, false)); log.info("Sync Recovery was successful - registering as Active"); // System.out // .println("Sync Recovery was successful - registering as Active " // + zkController.getNodeName()); // solrcloud_debug // try { // RefCounted<SolrIndexSearcher> searchHolder = // core.getNewestSearcher(false); // SolrIndexSearcher searcher = searchHolder.get(); // try { // System.out.println(core.getCoreDescriptor().getCoreContainer().getZkController().getNodeName() // + " synched " // + searcher.search(new MatchAllDocsQuery(), 1).totalHits); // } finally { // searchHolder.decref(); // } // } catch (Exception e) { // // } // sync success - register as active and return zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); successfulRecovery = true; close = true; return; } log.info("Sync Recovery was not successful - trying replication"); } //System.out.println("Sync Recovery was not successful - trying replication"); log.info("Begin buffering updates"); ulog.bufferUpdates(); replayed = false; try { replicate(zkController.getNodeName(), core, leaderprops, leaderUrl); replay(ulog); replayed = true; log.info("Recovery was successful - registering as Active"); // if there are pending recovery requests, don't advert as active zkController.publishAsActive(baseUrl, core.getCoreDescriptor(), coreZkNodeName, coreName); close = true; successfulRecovery = true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (!replayed) { try { ulog.dropBufferedUpdates(); } catch (Throwable t) { SolrException.log(log, "", t); } } } } catch (Throwable t) { SolrException.log(log, "Error while trying to recover", t); } finally { if (core != null) { core.close(); } } if (!successfulRecovery) { // lets pause for a moment and we need to try again... // TODO: we don't want to retry for some problems? // Or do a fall off retry... try { SolrException.log(log, "Recovery failed - trying again..."); retries++; if (retries >= MAX_RETRIES) { if (retries == INTERRUPTED) { } else { // TODO: for now, give up after X tries - should we do more? core = cc.getCore(coreName); try { recoveryFailed(core, zkController, baseUrl, coreZkNodeName, core.getCoreDescriptor()); } finally { if (core != null) { core.close(); } } } break; } } catch (Exception e) { SolrException.log(log, "", e); } try { Thread.sleep(Math.min(START_TIMEOUT * retries, 60000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Recovery was interrupted", e); retries = INTERRUPTED; } } log.info("Finished recovery process"); } }
diff --git a/fap/app/verificacion/VerificacionUtils.java b/fap/app/verificacion/VerificacionUtils.java index 3503bf10..92907dd4 100644 --- a/fap/app/verificacion/VerificacionUtils.java +++ b/fap/app/verificacion/VerificacionUtils.java @@ -1,410 +1,410 @@ package verificacion; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import play.libs.F.Promise; import reports.Report; import services.FirmaService; import services.GestorDocumentalService; import services.aed.ProcedimientosService; import config.InjectorConfig; import controllers.fap.VerificacionFapController; import messages.Messages; import models.Documento; import models.SolicitudGenerica; import models.TableKeyValue; import models.TipoDocumento; import models.Tramite; import models.Verificacion; import models.VerificacionDocumento; import enumerado.fap.gen.EstadosDocumentoVerificacionEnum; import enumerado.fap.gen.EstadosVerificacionEnum; import es.gobcan.eadmon.procedimientos.ws.dominio.ObligatoriedadEnum; import es.gobcan.eadmon.procedimientos.ws.dominio.TipoDocumentoEnTramite; import es.gobcan.eadmon.verificacion.ws.dominio.EstadoDocumentoVerificacion; public class VerificacionUtils { /** * Devuelve la lista de documentos a verificar (presentes y no presentes) que no han sido verificados en forma de lista de VerificacionDocumentos. * * 1ª Verificación del trámite actual: * - Lista con todos los documentos aportados y no aportados. * 2ª o posteriores verificaciones de un trámite: * - Añadimos los nuevo documentos presentados con estado ="No verificado" * - Copiamos de la verificación anterior de ese trámite todos los documentos "No válido" * y "No presentado" con sus respectivos motivos y códigos de requerimiento que no se han * presentado ahora. * * @param listDoc Lista de Documentos (verificados y no verificados) * @return Lista de VerificaciónDocumentos (sólo los no verificados) */ public static List<VerificacionDocumento> getVerificacionDocumentosFromNewDocumentos (List<Documento> listDoc, String uriTramite, List<Verificacion> verificacionesBefore, Long idSolicitud) { Tramite tramite = (Tramite) Tramite.find("select t from Tramite t where t.uri=?", uriTramite).first(); List<VerificacionDocumento> list = new ArrayList<VerificacionDocumento>(); List<Documento> aux = new ArrayList<Documento>(); List<Documento> auxIterar = new ArrayList<Documento>(); aux.addAll(listDoc); auxIterar.addAll(listDoc); GestorDocumentalService gestorDocumental = InjectorConfig.getInjector().getInstance(GestorDocumentalService.class); /// Comprobamos si existenVerificaciones de este mismo trámite anteriormente Verificacion verificacionAnterior = null; if (verificacionesBefore != null && !verificacionesBefore.isEmpty()) { for (Verificacion auxVerificacion : verificacionesBefore) { if (auxVerificacion.uriTramite.equals(uriTramite)) { verificacionAnterior = auxVerificacion; } } } /// Si verificacionAnterior == null, NO tiene verificaciones anteriores en ese trámite List<TipoDocumentoEnTramite> listaTipos = new ArrayList<TipoDocumentoEnTramite>(); if (verificacionAnterior == null) { play.Logger.info("No existen verificaciones anteriores para la solicitud "+idSolicitud+" del trámite "+uriTramite); listaTipos = gestorDocumental.getTiposDocumentosAportadosCiudadano(tramite); // Documentos condicionados automaticos obligatorios de la aplicacion en cuestion List<String> docCondicionadosAutomaticosNoAportados=new ArrayList<String>(); try { docCondicionadosAutomaticosNoAportados = VerificacionFapController.invoke("getDocumentosNoAportadosCondicionadosAutomaticos", tramite.nombre, idSolicitud); } catch (Throwable e) { play.Logger.error("Fallo al recuperar la lista con los tipos de documentos condicionados automaticos: "+e); } for (TipoDocumentoEnTramite tipoDoc : listaTipos) { boolean tipoEncontrado = false; // Mejorar la implementación for (Documento doc: auxIterar) { if ((doc.tipo != null) && (doc.tipo.trim().equals(tipoDoc.getUri()))) { VerificacionDocumento vDoc = new VerificacionDocumento(doc); vDoc.existe = true; if (tipoDoc.getObligatoriedad() == ObligatoriedadEnum.CONDICIONADO_AUTOMATICO) { // Comprobar si se tenía que añadir o no if ((docCondicionadosAutomaticosNoAportados != null) && (docCondicionadosAutomaticosNoAportados.size() != 0) && docCondicionadosAutomaticosNoAportados.contains(ObligatoriedadDocumentosFap.eliminarVersionUri(tipoDoc.getUri()))) vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); else vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noProcede.name(); } else { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); } vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); //vDoc.etiquetaTipoDocumento if ((tipoEncontrado) && !vDoc.identificadorMultiple.equalsIgnoreCase("multiple")) { play.Logger.error("El tipo de documento <"+doc.tipo+"> ya había sido añadido en la misma verificacion y su cardinalidad es "+vDoc.identificadorMultiple); } vDoc.save(); list.add(vDoc); aux.remove(doc); tipoEncontrado = true; } } // Si el tipo de documento no fue encontrado en los que aporta if (!tipoEncontrado) { // Si es OBLIGATORIO if ((tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.OBLIGATORIO)) ||(tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.IMPRESCINDIBLE))) { VerificacionDocumento vDoc = new VerificacionDocumento(); vDoc.existe = false; vDoc.uriTipoDocumento = tipoDoc.getUri(); vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); vDoc.descripcion = TableKeyValue.getValue("tiposDocumentos", tipoDoc.getUri()); if (existsDocumentoVerificacionAnterior(EstadosDocumentoVerificacionEnum.noProcede, verificacionesBefore, tipoDoc.getUri(), tramite.uri) || existsDocumentoVerificacionAnterior(EstadosDocumentoVerificacionEnum.valido, verificacionesBefore, tipoDoc.getUri(), tramite.uri)) { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); } else { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noPresentado.name(); } vDoc.save(); list.add(vDoc); } else if (tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.CONDICIONADO_MANUAL)){ VerificacionDocumento vDoc = new VerificacionDocumento(); vDoc.existe = false; vDoc.uriTipoDocumento = tipoDoc.getUri(); vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); vDoc.descripcion = TableKeyValue.getValue("tiposDocumentos", tipoDoc.getUri()); vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noPresentado.name(); vDoc.save(); list.add(vDoc); } // Condicionado AUTOMATICO else if (tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.CONDICIONADO_AUTOMATICO)){ VerificacionDocumento vDoc = new VerificacionDocumento(); vDoc.existe = false; vDoc.uriTipoDocumento = tipoDoc.getUri(); vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); vDoc.descripcion = TableKeyValue.getValue("tiposDocumentos", tipoDoc.getUri()); // Si el tipo de Documento está en la lista de los tipos de documentos obligatorios condicionados automaticos que obtenemos de la propia aplicacion // Quitamos la uri del tipo de documento porque esta quitada en la lista de condicionados automaticos, por lo que se debe quitar para comparar if ((docCondicionadosAutomaticosNoAportados != null) && (docCondicionadosAutomaticosNoAportados.size() != 0) && docCondicionadosAutomaticosNoAportados.contains(ObligatoriedadDocumentosFap.eliminarVersionUri(tipoDoc.getUri()))){ vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noPresentado.name(); } else { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noProcede.name(); } vDoc.save(); list.add(vDoc); } } } // Recorro todos los documentos no pertenecientes al trámite actual pero que se han aportado for (Documento docAux: aux){ VerificacionDocumento vDoc = new VerificacionDocumento(docAux); vDoc.existe = true; vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noProcede.name(); vDoc.save(); list.add(vDoc); } } else { /// Tiene verificaciones anteriores de este trámite y está en verificacionAnterior play.Logger.info("Existe al menos una verificación anterior "+verificacionAnterior.id+" de la solicitud "+idSolicitud+" para trámite "+uriTramite); // Añadimos todos los documentos que se aportaron ahora for (Documento doc: listDoc) { VerificacionDocumento vDoc = new VerificacionDocumento(doc); vDoc.existe = true; vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); vDoc.save(); list.add(vDoc); } // De la verificación anterior copiamos los No Validos y los No Presentados que no // hayan sido añadidos ahora for (VerificacionDocumento docVerif : verificacionAnterior.documentos) { - if (docVerif.estadoDocumentoVerificacion.equals(EstadoDocumentoVerificacion.NO_PRESENTADO.name()) - || docVerif.estadoDocumentoVerificacion.equals(EstadoDocumentoVerificacion.NO_VALIDO.name())) { + if (docVerif.estadoDocumentoVerificacion.equals(EstadosDocumentoVerificacionEnum.noPresentado.name()) + || docVerif.estadoDocumentoVerificacion.equals(EstadosDocumentoVerificacionEnum.noValido.name())) { boolean findActual = false; for (Documento doc: listDoc) { if (ObligatoriedadDocumentosFap.eliminarVersionUri(docVerif.uriTipoDocumento).equals(ObligatoriedadDocumentosFap.eliminarVersionUri(doc.tipo))) { findActual = true; break; } } if (!findActual) { VerificacionDocumento newVerDoc = new VerificacionDocumento(docVerif); newVerDoc.save(); list.add(newVerDoc); } } } } return list; } /** * Indica si existe un documento con dicho tipo en las verificaciones anteriores de ese mismo trámite. * * @param listVerificacion Lista de verificaciones anteriores donde buscar. * @param uriTipo Tipo del documento. * @param uriTramite Uri del trámite sobre el que se busca. * * @return True Si existe el documento en verificaciones anteriores */ public static boolean existsDocumentoVerificacionAnterior (List<Verificacion> listVerificacion, String uriTipo, String uriTramite) { play.Logger.info("Buscamos el tipo de documento <"+uriTipo+"> en verificaciones anteriores del trámite <"+uriTramite+">"); for (Verificacion verif: listVerificacion) { if (verif.uriTramite.equals(uriTramite)) { for (VerificacionDocumento vDoc: verif.documentos) { if (vDoc.uriTipoDocumento.equals(uriTipo)) { if (vDoc.existe) { play.Logger.info("Existe -> "+vDoc.uriDocumento); return true; } } } } } play.Logger.info("NO existen documentos del tipo de documento "+uriTipo); return false; } /** * Indica si el documento fue verificado como "resultado" con dicho tipo en las verificaciones anteriores de ese mismo trámite. * * @param resultado Resultado de la verificacion anterior * @param listVerificacion Lista de verificaciones anteriores donde buscar. * @param uriTipo Tipo del documento. * @param uriTramite Uri del trámite sobre el que se busca. * * @return True Si existe el documento en verificaciones anteriores */ public static boolean existsDocumentoVerificacionAnterior (EstadosDocumentoVerificacionEnum resultado, List<Verificacion> listVerificacion, String uriTipo, String uriTramite) { play.Logger.info("Buscamos el tipo de documento <"+uriTipo+"> con resultado <"+resultado.name()+"> en verificaciones anteriores del trámite <"+uriTramite+">"); for (Verificacion verif: listVerificacion) { if ((verif.uriTramite != null) && (verif.uriTramite.equals(uriTramite))) { for (VerificacionDocumento vDoc: verif.documentos) { if (vDoc.uriTipoDocumento.equals(uriTipo)) { if (vDoc.existe && (vDoc.estadoDocumentoVerificacion.equals(resultado.name()))) { play.Logger.info("Existe -> "+vDoc.uriDocumento); return true; } } } } } play.Logger.info("NO existen documentos del tipo de documento "+uriTipo); return false; } /** * Indica si existe algun documento no verificado, en la verificacion actual * * @param verificacionActual La verificación que está en curso * * @return True Si existe un documento de la verificación actual que está No Verificado */ public static boolean existsDocumentoNoVerificado (Verificacion verificacionActual) { for (VerificacionDocumento vDoc: verificacionActual.documentos) { if (vDoc.estadoDocumentoVerificacion.equals(EstadosDocumentoVerificacionEnum.noVerificado.name())) { return true; } } return false; } /** * Indica si existen documentos nuevos aportados por el solicitante y que no estan incluidos en la verificacion actual, ni en anteriores * * @param verificacionActual La verificación que está en curso * * @return documentosNuevos Lista con los documentos nuevos que ha aportado el solicitante y no han sido incluidos en ninguna verificacion */ public static List<Documento> existDocumentosNuevos (Verificacion verificacionActual, Long idSolicitud) { List<Documento> documentosNuevos=null; List <Documento> documentosNuevosSinVerificacionActual = null; try { documentosNuevos = (List<Documento>)VerificacionFapController.invoke("getNuevosDocumentosVerificar", verificacionActual.id, idSolicitud); documentosNuevosSinVerificacionActual = (List<Documento>)VerificacionFapController.invoke("getNuevosDocumentosVerificar", verificacionActual.id, idSolicitud); } catch (Throwable e) { e.printStackTrace(); play.Logger.error("Error recuperando los documentos nuevos a verificar", e.getMessage()); } for (Documento doc: documentosNuevos){ for (VerificacionDocumento vDoc: verificacionActual.documentos){ if ((vDoc.uriDocumento != null) && (vDoc.uriDocumento.equals(doc.uri))){ documentosNuevosSinVerificacionActual.remove(doc); break; } } } return documentosNuevosSinVerificacionActual; } /** * Indica si existen documentos nuevos aportados por el solicitante y que no estan incluidos en la verificacion actual, ni en anteriores, ni en la verificacion de tipos actual * * @param verificacionActual La verificación que está en curso * @param verificaciones Las verificaciones anteriores ya finalizadas * @param documentosActuales La lista de documentos actuales que ha aportado el solicitante * * @return documentosNuevos Lista con los documentos nuevos que ha aportado el solicitante y no han sido incluidos en ninguna verificacion */ public static List<Documento> existDocumentosNuevosVerificacionTipos (Verificacion verificacionActual, List<Verificacion> verificaciones, List<Documento> documentosActuales, Long idSolicitud) { List <Documento> documentos = existDocumentosNuevos (verificacionActual, idSolicitud); List <Documento> documentosNuevos = existDocumentosNuevos (verificacionActual, idSolicitud); for (Documento vtdoc: verificacionActual.verificacionTiposDocumentos){ for (Documento doc: documentos){ if ((vtdoc.uri != null) && (doc.uri != null) && (vtdoc.uri.equals(doc.uri))){ documentosNuevos.remove(doc); break; } } } return documentosNuevos; } /** * Indica si todos los documentos de la verificacion estan correctamente (no procede o valido) * * @param verificacionActual La verificación que está en curso * * @return True Si todos los documentos estan correctamente (en estado no procede o valido) */ public static boolean documentosValidos (Verificacion verificacionActual) { for (VerificacionDocumento vDoc: verificacionActual.documentos){ if (!(vDoc.estadoDocumentoVerificacion.equals(EstadosDocumentoVerificacionEnum.valido.name())) && !((vDoc.estadoDocumentoVerificacion.equals(EstadosDocumentoVerificacionEnum.noProcede.name())))){ return false; } } return true; } /** * Indica si existe algun documento en la verificacion en estado No presentado o no valido * * @param verificacionActual La verificación que está en curso * * @return True Si algun documento esta en estado No presentado o no valido */ public static boolean documentosIncorrectos (Verificacion verificacionActual) { for (VerificacionDocumento vDoc: verificacionActual.documentos){ if ((vDoc.estadoDocumentoVerificacion.equals(EstadosDocumentoVerificacionEnum.noValido.name())) || ((vDoc.estadoDocumentoVerificacion.equals(EstadosDocumentoVerificacionEnum.noPresentado.name())))){ return true; } } return false; } // Función que a través del trámite sobre el que se está trabajando en la clase // Recupera los documentos aportados por el CIUDADANO y que sean CONDICIONADO_AUTOMATICO // Almacenandolos en la lista local de la clase para tal efecto public static List<String> ObtenerDocumentosAutomaticos(Tramite tramite){ List<String> lista = new ArrayList<String>(); for (TipoDocumento td : tramite.documentos) { if (td.aportadoPor.toUpperCase().equals("CIUDADANO")){ if(td.obligatoriedad.toUpperCase().equals("CONDICIONADO_AUTOMATICO")){ lista.add(eliminarVersionUri(td.uri)); } } } return lista; } // Para eliminar de la URI, la Versión, que no hará falta en el proceso de obtener la documentación obligatoria al trámite public static String eliminarVersionUri(String uri) { String PATTERN_VERSION_URI = "(.*)/v[0-9][0-9]$"; Pattern p = Pattern.compile(PATTERN_VERSION_URI); Matcher m = p.matcher(uri); if (m.find()) return m.group(1); return uri; } /** * Establece el campo verificado de los documentos a true * * @param vDocs VerificacionDocumentos verificados * @param docs Documentos donde deberá buscar para setear los anteriores */ public static void setVerificadoDocumentos (List<VerificacionDocumento> vDocs, List<Documento> docs) { for (VerificacionDocumento vDoc : vDocs) { for (Documento docu: docs) { if ((docu.uri != null) && (vDoc.uriDocumento != null) && (docu.uri.equals(vDoc.uriDocumento))){ docu.verificado=true; break; } } } } }
true
true
public static List<VerificacionDocumento> getVerificacionDocumentosFromNewDocumentos (List<Documento> listDoc, String uriTramite, List<Verificacion> verificacionesBefore, Long idSolicitud) { Tramite tramite = (Tramite) Tramite.find("select t from Tramite t where t.uri=?", uriTramite).first(); List<VerificacionDocumento> list = new ArrayList<VerificacionDocumento>(); List<Documento> aux = new ArrayList<Documento>(); List<Documento> auxIterar = new ArrayList<Documento>(); aux.addAll(listDoc); auxIterar.addAll(listDoc); GestorDocumentalService gestorDocumental = InjectorConfig.getInjector().getInstance(GestorDocumentalService.class); /// Comprobamos si existenVerificaciones de este mismo trámite anteriormente Verificacion verificacionAnterior = null; if (verificacionesBefore != null && !verificacionesBefore.isEmpty()) { for (Verificacion auxVerificacion : verificacionesBefore) { if (auxVerificacion.uriTramite.equals(uriTramite)) { verificacionAnterior = auxVerificacion; } } } /// Si verificacionAnterior == null, NO tiene verificaciones anteriores en ese trámite List<TipoDocumentoEnTramite> listaTipos = new ArrayList<TipoDocumentoEnTramite>(); if (verificacionAnterior == null) { play.Logger.info("No existen verificaciones anteriores para la solicitud "+idSolicitud+" del trámite "+uriTramite); listaTipos = gestorDocumental.getTiposDocumentosAportadosCiudadano(tramite); // Documentos condicionados automaticos obligatorios de la aplicacion en cuestion List<String> docCondicionadosAutomaticosNoAportados=new ArrayList<String>(); try { docCondicionadosAutomaticosNoAportados = VerificacionFapController.invoke("getDocumentosNoAportadosCondicionadosAutomaticos", tramite.nombre, idSolicitud); } catch (Throwable e) { play.Logger.error("Fallo al recuperar la lista con los tipos de documentos condicionados automaticos: "+e); } for (TipoDocumentoEnTramite tipoDoc : listaTipos) { boolean tipoEncontrado = false; // Mejorar la implementación for (Documento doc: auxIterar) { if ((doc.tipo != null) && (doc.tipo.trim().equals(tipoDoc.getUri()))) { VerificacionDocumento vDoc = new VerificacionDocumento(doc); vDoc.existe = true; if (tipoDoc.getObligatoriedad() == ObligatoriedadEnum.CONDICIONADO_AUTOMATICO) { // Comprobar si se tenía que añadir o no if ((docCondicionadosAutomaticosNoAportados != null) && (docCondicionadosAutomaticosNoAportados.size() != 0) && docCondicionadosAutomaticosNoAportados.contains(ObligatoriedadDocumentosFap.eliminarVersionUri(tipoDoc.getUri()))) vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); else vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noProcede.name(); } else { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); } vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); //vDoc.etiquetaTipoDocumento if ((tipoEncontrado) && !vDoc.identificadorMultiple.equalsIgnoreCase("multiple")) { play.Logger.error("El tipo de documento <"+doc.tipo+"> ya había sido añadido en la misma verificacion y su cardinalidad es "+vDoc.identificadorMultiple); } vDoc.save(); list.add(vDoc); aux.remove(doc); tipoEncontrado = true; } } // Si el tipo de documento no fue encontrado en los que aporta if (!tipoEncontrado) { // Si es OBLIGATORIO if ((tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.OBLIGATORIO)) ||(tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.IMPRESCINDIBLE))) { VerificacionDocumento vDoc = new VerificacionDocumento(); vDoc.existe = false; vDoc.uriTipoDocumento = tipoDoc.getUri(); vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); vDoc.descripcion = TableKeyValue.getValue("tiposDocumentos", tipoDoc.getUri()); if (existsDocumentoVerificacionAnterior(EstadosDocumentoVerificacionEnum.noProcede, verificacionesBefore, tipoDoc.getUri(), tramite.uri) || existsDocumentoVerificacionAnterior(EstadosDocumentoVerificacionEnum.valido, verificacionesBefore, tipoDoc.getUri(), tramite.uri)) { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); } else { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noPresentado.name(); } vDoc.save(); list.add(vDoc); } else if (tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.CONDICIONADO_MANUAL)){ VerificacionDocumento vDoc = new VerificacionDocumento(); vDoc.existe = false; vDoc.uriTipoDocumento = tipoDoc.getUri(); vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); vDoc.descripcion = TableKeyValue.getValue("tiposDocumentos", tipoDoc.getUri()); vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noPresentado.name(); vDoc.save(); list.add(vDoc); } // Condicionado AUTOMATICO else if (tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.CONDICIONADO_AUTOMATICO)){ VerificacionDocumento vDoc = new VerificacionDocumento(); vDoc.existe = false; vDoc.uriTipoDocumento = tipoDoc.getUri(); vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); vDoc.descripcion = TableKeyValue.getValue("tiposDocumentos", tipoDoc.getUri()); // Si el tipo de Documento está en la lista de los tipos de documentos obligatorios condicionados automaticos que obtenemos de la propia aplicacion // Quitamos la uri del tipo de documento porque esta quitada en la lista de condicionados automaticos, por lo que se debe quitar para comparar if ((docCondicionadosAutomaticosNoAportados != null) && (docCondicionadosAutomaticosNoAportados.size() != 0) && docCondicionadosAutomaticosNoAportados.contains(ObligatoriedadDocumentosFap.eliminarVersionUri(tipoDoc.getUri()))){ vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noPresentado.name(); } else { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noProcede.name(); } vDoc.save(); list.add(vDoc); } } } // Recorro todos los documentos no pertenecientes al trámite actual pero que se han aportado for (Documento docAux: aux){ VerificacionDocumento vDoc = new VerificacionDocumento(docAux); vDoc.existe = true; vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noProcede.name(); vDoc.save(); list.add(vDoc); } } else { /// Tiene verificaciones anteriores de este trámite y está en verificacionAnterior play.Logger.info("Existe al menos una verificación anterior "+verificacionAnterior.id+" de la solicitud "+idSolicitud+" para trámite "+uriTramite); // Añadimos todos los documentos que se aportaron ahora for (Documento doc: listDoc) { VerificacionDocumento vDoc = new VerificacionDocumento(doc); vDoc.existe = true; vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); vDoc.save(); list.add(vDoc); } // De la verificación anterior copiamos los No Validos y los No Presentados que no // hayan sido añadidos ahora for (VerificacionDocumento docVerif : verificacionAnterior.documentos) { if (docVerif.estadoDocumentoVerificacion.equals(EstadoDocumentoVerificacion.NO_PRESENTADO.name()) || docVerif.estadoDocumentoVerificacion.equals(EstadoDocumentoVerificacion.NO_VALIDO.name())) { boolean findActual = false; for (Documento doc: listDoc) { if (ObligatoriedadDocumentosFap.eliminarVersionUri(docVerif.uriTipoDocumento).equals(ObligatoriedadDocumentosFap.eliminarVersionUri(doc.tipo))) { findActual = true; break; } } if (!findActual) { VerificacionDocumento newVerDoc = new VerificacionDocumento(docVerif); newVerDoc.save(); list.add(newVerDoc); } } } } return list; }
public static List<VerificacionDocumento> getVerificacionDocumentosFromNewDocumentos (List<Documento> listDoc, String uriTramite, List<Verificacion> verificacionesBefore, Long idSolicitud) { Tramite tramite = (Tramite) Tramite.find("select t from Tramite t where t.uri=?", uriTramite).first(); List<VerificacionDocumento> list = new ArrayList<VerificacionDocumento>(); List<Documento> aux = new ArrayList<Documento>(); List<Documento> auxIterar = new ArrayList<Documento>(); aux.addAll(listDoc); auxIterar.addAll(listDoc); GestorDocumentalService gestorDocumental = InjectorConfig.getInjector().getInstance(GestorDocumentalService.class); /// Comprobamos si existenVerificaciones de este mismo trámite anteriormente Verificacion verificacionAnterior = null; if (verificacionesBefore != null && !verificacionesBefore.isEmpty()) { for (Verificacion auxVerificacion : verificacionesBefore) { if (auxVerificacion.uriTramite.equals(uriTramite)) { verificacionAnterior = auxVerificacion; } } } /// Si verificacionAnterior == null, NO tiene verificaciones anteriores en ese trámite List<TipoDocumentoEnTramite> listaTipos = new ArrayList<TipoDocumentoEnTramite>(); if (verificacionAnterior == null) { play.Logger.info("No existen verificaciones anteriores para la solicitud "+idSolicitud+" del trámite "+uriTramite); listaTipos = gestorDocumental.getTiposDocumentosAportadosCiudadano(tramite); // Documentos condicionados automaticos obligatorios de la aplicacion en cuestion List<String> docCondicionadosAutomaticosNoAportados=new ArrayList<String>(); try { docCondicionadosAutomaticosNoAportados = VerificacionFapController.invoke("getDocumentosNoAportadosCondicionadosAutomaticos", tramite.nombre, idSolicitud); } catch (Throwable e) { play.Logger.error("Fallo al recuperar la lista con los tipos de documentos condicionados automaticos: "+e); } for (TipoDocumentoEnTramite tipoDoc : listaTipos) { boolean tipoEncontrado = false; // Mejorar la implementación for (Documento doc: auxIterar) { if ((doc.tipo != null) && (doc.tipo.trim().equals(tipoDoc.getUri()))) { VerificacionDocumento vDoc = new VerificacionDocumento(doc); vDoc.existe = true; if (tipoDoc.getObligatoriedad() == ObligatoriedadEnum.CONDICIONADO_AUTOMATICO) { // Comprobar si se tenía que añadir o no if ((docCondicionadosAutomaticosNoAportados != null) && (docCondicionadosAutomaticosNoAportados.size() != 0) && docCondicionadosAutomaticosNoAportados.contains(ObligatoriedadDocumentosFap.eliminarVersionUri(tipoDoc.getUri()))) vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); else vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noProcede.name(); } else { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); } vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); //vDoc.etiquetaTipoDocumento if ((tipoEncontrado) && !vDoc.identificadorMultiple.equalsIgnoreCase("multiple")) { play.Logger.error("El tipo de documento <"+doc.tipo+"> ya había sido añadido en la misma verificacion y su cardinalidad es "+vDoc.identificadorMultiple); } vDoc.save(); list.add(vDoc); aux.remove(doc); tipoEncontrado = true; } } // Si el tipo de documento no fue encontrado en los que aporta if (!tipoEncontrado) { // Si es OBLIGATORIO if ((tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.OBLIGATORIO)) ||(tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.IMPRESCINDIBLE))) { VerificacionDocumento vDoc = new VerificacionDocumento(); vDoc.existe = false; vDoc.uriTipoDocumento = tipoDoc.getUri(); vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); vDoc.descripcion = TableKeyValue.getValue("tiposDocumentos", tipoDoc.getUri()); if (existsDocumentoVerificacionAnterior(EstadosDocumentoVerificacionEnum.noProcede, verificacionesBefore, tipoDoc.getUri(), tramite.uri) || existsDocumentoVerificacionAnterior(EstadosDocumentoVerificacionEnum.valido, verificacionesBefore, tipoDoc.getUri(), tramite.uri)) { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); } else { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noPresentado.name(); } vDoc.save(); list.add(vDoc); } else if (tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.CONDICIONADO_MANUAL)){ VerificacionDocumento vDoc = new VerificacionDocumento(); vDoc.existe = false; vDoc.uriTipoDocumento = tipoDoc.getUri(); vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); vDoc.descripcion = TableKeyValue.getValue("tiposDocumentos", tipoDoc.getUri()); vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noPresentado.name(); vDoc.save(); list.add(vDoc); } // Condicionado AUTOMATICO else if (tipoDoc.getObligatoriedad().equals(ObligatoriedadEnum.CONDICIONADO_AUTOMATICO)){ VerificacionDocumento vDoc = new VerificacionDocumento(); vDoc.existe = false; vDoc.uriTipoDocumento = tipoDoc.getUri(); vDoc.identificadorMultiple = tipoDoc.getCardinalidad().name(); vDoc.descripcion = TableKeyValue.getValue("tiposDocumentos", tipoDoc.getUri()); // Si el tipo de Documento está en la lista de los tipos de documentos obligatorios condicionados automaticos que obtenemos de la propia aplicacion // Quitamos la uri del tipo de documento porque esta quitada en la lista de condicionados automaticos, por lo que se debe quitar para comparar if ((docCondicionadosAutomaticosNoAportados != null) && (docCondicionadosAutomaticosNoAportados.size() != 0) && docCondicionadosAutomaticosNoAportados.contains(ObligatoriedadDocumentosFap.eliminarVersionUri(tipoDoc.getUri()))){ vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noPresentado.name(); } else { vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noProcede.name(); } vDoc.save(); list.add(vDoc); } } } // Recorro todos los documentos no pertenecientes al trámite actual pero que se han aportado for (Documento docAux: aux){ VerificacionDocumento vDoc = new VerificacionDocumento(docAux); vDoc.existe = true; vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noProcede.name(); vDoc.save(); list.add(vDoc); } } else { /// Tiene verificaciones anteriores de este trámite y está en verificacionAnterior play.Logger.info("Existe al menos una verificación anterior "+verificacionAnterior.id+" de la solicitud "+idSolicitud+" para trámite "+uriTramite); // Añadimos todos los documentos que se aportaron ahora for (Documento doc: listDoc) { VerificacionDocumento vDoc = new VerificacionDocumento(doc); vDoc.existe = true; vDoc.estadoDocumentoVerificacion = EstadosDocumentoVerificacionEnum.noVerificado.name(); vDoc.save(); list.add(vDoc); } // De la verificación anterior copiamos los No Validos y los No Presentados que no // hayan sido añadidos ahora for (VerificacionDocumento docVerif : verificacionAnterior.documentos) { if (docVerif.estadoDocumentoVerificacion.equals(EstadosDocumentoVerificacionEnum.noPresentado.name()) || docVerif.estadoDocumentoVerificacion.equals(EstadosDocumentoVerificacionEnum.noValido.name())) { boolean findActual = false; for (Documento doc: listDoc) { if (ObligatoriedadDocumentosFap.eliminarVersionUri(docVerif.uriTipoDocumento).equals(ObligatoriedadDocumentosFap.eliminarVersionUri(doc.tipo))) { findActual = true; break; } } if (!findActual) { VerificacionDocumento newVerDoc = new VerificacionDocumento(docVerif); newVerDoc.save(); list.add(newVerDoc); } } } } return list; }
diff --git a/src/main/java/com/conventnunnery/plugins/mythicdrops/objects/parents/MythicTome.java b/src/main/java/com/conventnunnery/plugins/mythicdrops/objects/parents/MythicTome.java index d51fcd25..fbaa38eb 100644 --- a/src/main/java/com/conventnunnery/plugins/mythicdrops/objects/parents/MythicTome.java +++ b/src/main/java/com/conventnunnery/plugins/mythicdrops/objects/parents/MythicTome.java @@ -1,39 +1,46 @@ package com.conventnunnery.plugins.mythicdrops.objects.parents; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.MaterialData; import java.util.Arrays; public class MythicTome extends MythicItemStack { public MythicTome(TomeType tomeType, String title, String author, String[] lore, String[] pages) { super(tomeType.toMaterialData()); ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(getType()); - BookMeta bookMeta = (BookMeta) itemMeta; - bookMeta.setTitle(title); - bookMeta.setAuthor(author); - bookMeta.setLore(Arrays.asList(lore)); - bookMeta.setPages(pages); - setItemMeta(bookMeta); + if (itemMeta instanceof BookMeta) { + BookMeta bookMeta = (BookMeta) itemMeta; + bookMeta.setTitle(title); + bookMeta.setAuthor(author); + bookMeta.setLore(Arrays.asList(lore)); + bookMeta.setPages(pages); + setItemMeta(bookMeta); + } + else { + itemMeta.setDisplayName(title); + itemMeta.setLore(Arrays.asList(lore)); + setItemMeta(itemMeta); + } } public enum TomeType { WRITTEN_BOOK(new MaterialData(Material.WRITTEN_BOOK, (byte) 0)), BOOK(new MaterialData(Material.BOOK, (byte) 0)), BOOK_AND_QUILL(new MaterialData(Material.BOOK_AND_QUILL, (byte) 0)), ENCHANTED_BOOK(new MaterialData(Material.ENCHANTED_BOOK, (byte) 0)); private final MaterialData materialData; private TomeType(MaterialData matData) { this.materialData = matData; } public MaterialData toMaterialData() { return materialData; } } }
true
true
public MythicTome(TomeType tomeType, String title, String author, String[] lore, String[] pages) { super(tomeType.toMaterialData()); ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(getType()); BookMeta bookMeta = (BookMeta) itemMeta; bookMeta.setTitle(title); bookMeta.setAuthor(author); bookMeta.setLore(Arrays.asList(lore)); bookMeta.setPages(pages); setItemMeta(bookMeta); }
public MythicTome(TomeType tomeType, String title, String author, String[] lore, String[] pages) { super(tomeType.toMaterialData()); ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(getType()); if (itemMeta instanceof BookMeta) { BookMeta bookMeta = (BookMeta) itemMeta; bookMeta.setTitle(title); bookMeta.setAuthor(author); bookMeta.setLore(Arrays.asList(lore)); bookMeta.setPages(pages); setItemMeta(bookMeta); } else { itemMeta.setDisplayName(title); itemMeta.setLore(Arrays.asList(lore)); setItemMeta(itemMeta); } }
diff --git a/ratpack-core/src/main/java/org/ratpackframework/file/internal/FileStaticAssetRequestHandler.java b/ratpack-core/src/main/java/org/ratpackframework/file/internal/FileStaticAssetRequestHandler.java index dfe01af02..c400dc469 100644 --- a/ratpack-core/src/main/java/org/ratpackframework/file/internal/FileStaticAssetRequestHandler.java +++ b/ratpack-core/src/main/java/org/ratpackframework/file/internal/FileStaticAssetRequestHandler.java @@ -1,85 +1,85 @@ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ratpackframework.file.internal; import io.netty.handler.codec.http.HttpHeaders; import org.ratpackframework.file.FileSystemBinding; import org.ratpackframework.file.MimeTypes; import org.ratpackframework.http.Request; import org.ratpackframework.http.Response; import org.ratpackframework.routing.Exchange; import org.ratpackframework.routing.Handler; import java.io.File; import java.util.Date; import static io.netty.handler.codec.http.HttpHeaders.Names.IF_MODIFIED_SINCE; import static io.netty.handler.codec.http.HttpResponseStatus.*; public class FileStaticAssetRequestHandler implements Handler { public void handle(Exchange exchange) { Request request = exchange.getRequest(); Response response = exchange.getResponse(); if (!request.getMethod().isGet()) { response.status(METHOD_NOT_ALLOWED.code(), METHOD_NOT_ALLOWED.reasonPhrase()).send(); return; } FileSystemBinding fileSystemBinding = exchange.get(FileSystemBinding.class); File targetFile = fileSystemBinding.getFile(); if (targetFile.isHidden() || !targetFile.exists()) { exchange.next(); return; } if (!targetFile.isFile()) { response.status(FORBIDDEN.code(), FORBIDDEN.reasonPhrase()).send(); return; } long lastModifiedTime = targetFile.lastModified(); if (lastModifiedTime < 1) { exchange.next(); return; } Date ifModifiedSinceHeader = request.getDateHeader(IF_MODIFIED_SINCE); if (ifModifiedSinceHeader != null) { long ifModifiedSinceSecs = ifModifiedSinceHeader.getTime() / 1000; long lastModifiedSecs = lastModifiedTime / 1000; if (lastModifiedSecs == ifModifiedSinceSecs) { - response.status(NOT_MODIFIED.code(), NOT_MODIFIED.reasonPhrase()); + response.status(NOT_MODIFIED.code(), NOT_MODIFIED.reasonPhrase()).send(); return; } } final String ifNoneMatch = request.getHeader(HttpHeaders.Names.IF_NONE_MATCH); if (ifNoneMatch != null && ifNoneMatch.trim().equals("*")) { response.status(NOT_MODIFIED.code(), NOT_MODIFIED.reasonPhrase()).send(); return; } String contentType = exchange.get(MimeTypes.class).getContentType(targetFile); response.sendFile(contentType, targetFile); } }
true
true
public void handle(Exchange exchange) { Request request = exchange.getRequest(); Response response = exchange.getResponse(); if (!request.getMethod().isGet()) { response.status(METHOD_NOT_ALLOWED.code(), METHOD_NOT_ALLOWED.reasonPhrase()).send(); return; } FileSystemBinding fileSystemBinding = exchange.get(FileSystemBinding.class); File targetFile = fileSystemBinding.getFile(); if (targetFile.isHidden() || !targetFile.exists()) { exchange.next(); return; } if (!targetFile.isFile()) { response.status(FORBIDDEN.code(), FORBIDDEN.reasonPhrase()).send(); return; } long lastModifiedTime = targetFile.lastModified(); if (lastModifiedTime < 1) { exchange.next(); return; } Date ifModifiedSinceHeader = request.getDateHeader(IF_MODIFIED_SINCE); if (ifModifiedSinceHeader != null) { long ifModifiedSinceSecs = ifModifiedSinceHeader.getTime() / 1000; long lastModifiedSecs = lastModifiedTime / 1000; if (lastModifiedSecs == ifModifiedSinceSecs) { response.status(NOT_MODIFIED.code(), NOT_MODIFIED.reasonPhrase()); return; } } final String ifNoneMatch = request.getHeader(HttpHeaders.Names.IF_NONE_MATCH); if (ifNoneMatch != null && ifNoneMatch.trim().equals("*")) { response.status(NOT_MODIFIED.code(), NOT_MODIFIED.reasonPhrase()).send(); return; } String contentType = exchange.get(MimeTypes.class).getContentType(targetFile); response.sendFile(contentType, targetFile); }
public void handle(Exchange exchange) { Request request = exchange.getRequest(); Response response = exchange.getResponse(); if (!request.getMethod().isGet()) { response.status(METHOD_NOT_ALLOWED.code(), METHOD_NOT_ALLOWED.reasonPhrase()).send(); return; } FileSystemBinding fileSystemBinding = exchange.get(FileSystemBinding.class); File targetFile = fileSystemBinding.getFile(); if (targetFile.isHidden() || !targetFile.exists()) { exchange.next(); return; } if (!targetFile.isFile()) { response.status(FORBIDDEN.code(), FORBIDDEN.reasonPhrase()).send(); return; } long lastModifiedTime = targetFile.lastModified(); if (lastModifiedTime < 1) { exchange.next(); return; } Date ifModifiedSinceHeader = request.getDateHeader(IF_MODIFIED_SINCE); if (ifModifiedSinceHeader != null) { long ifModifiedSinceSecs = ifModifiedSinceHeader.getTime() / 1000; long lastModifiedSecs = lastModifiedTime / 1000; if (lastModifiedSecs == ifModifiedSinceSecs) { response.status(NOT_MODIFIED.code(), NOT_MODIFIED.reasonPhrase()).send(); return; } } final String ifNoneMatch = request.getHeader(HttpHeaders.Names.IF_NONE_MATCH); if (ifNoneMatch != null && ifNoneMatch.trim().equals("*")) { response.status(NOT_MODIFIED.code(), NOT_MODIFIED.reasonPhrase()).send(); return; } String contentType = exchange.get(MimeTypes.class).getContentType(targetFile); response.sendFile(contentType, targetFile); }
diff --git a/src/test/java/com/jmcejuela/bio/jenia/MainTest.java b/src/test/java/com/jmcejuela/bio/jenia/MainTest.java index 25ecb4b..199810f 100644 --- a/src/test/java/com/jmcejuela/bio/jenia/MainTest.java +++ b/src/test/java/com/jmcejuela/bio/jenia/MainTest.java @@ -1,49 +1,49 @@ package com.jmcejuela.bio.jenia; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import org.junit.Test; import com.jmcejuela.bio.jenia.util.Util; public class MainTest { @Test public void testNothingCrashes() throws IOException, InterruptedException { System.setIn(Util.resourceStream("/genia-nt.in")); File tmpOut = File.createTempFile("test-genia-nt", ".out"); System.out.println("tmp out file: " + tmpOut.getAbsolutePath()); System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(tmpOut)))); Main.main(new String[] { "-nt" }); System.err.println("Done. Now comparing the output files, line by line"); BufferedReader expectOutput = new BufferedReader(new InputStreamReader(Util.resourceStream("/genia-nt.out"))); BufferedReader actualOutput = new BufferedReader(new FileReader(tmpOut)); String expectLine = null; String actualLine = null; int n = 1; while (((expectLine = expectOutput.readLine()) != null) && ((actualLine = actualOutput.readLine()) != null)) { assertEquals("The lines are the same at line " + n, expectLine, actualLine); n++; } // "Both file must have the exact number of lines", assertEquals(null, expectLine); - assertEquals(null, actualLine); + assertEquals(null, actualOutput.readLine()); // note, the last line of actual was not read yet expectOutput.close(); actualOutput.close(); } }
true
true
public void testNothingCrashes() throws IOException, InterruptedException { System.setIn(Util.resourceStream("/genia-nt.in")); File tmpOut = File.createTempFile("test-genia-nt", ".out"); System.out.println("tmp out file: " + tmpOut.getAbsolutePath()); System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(tmpOut)))); Main.main(new String[] { "-nt" }); System.err.println("Done. Now comparing the output files, line by line"); BufferedReader expectOutput = new BufferedReader(new InputStreamReader(Util.resourceStream("/genia-nt.out"))); BufferedReader actualOutput = new BufferedReader(new FileReader(tmpOut)); String expectLine = null; String actualLine = null; int n = 1; while (((expectLine = expectOutput.readLine()) != null) && ((actualLine = actualOutput.readLine()) != null)) { assertEquals("The lines are the same at line " + n, expectLine, actualLine); n++; } // "Both file must have the exact number of lines", assertEquals(null, expectLine); assertEquals(null, actualLine); expectOutput.close(); actualOutput.close(); }
public void testNothingCrashes() throws IOException, InterruptedException { System.setIn(Util.resourceStream("/genia-nt.in")); File tmpOut = File.createTempFile("test-genia-nt", ".out"); System.out.println("tmp out file: " + tmpOut.getAbsolutePath()); System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(tmpOut)))); Main.main(new String[] { "-nt" }); System.err.println("Done. Now comparing the output files, line by line"); BufferedReader expectOutput = new BufferedReader(new InputStreamReader(Util.resourceStream("/genia-nt.out"))); BufferedReader actualOutput = new BufferedReader(new FileReader(tmpOut)); String expectLine = null; String actualLine = null; int n = 1; while (((expectLine = expectOutput.readLine()) != null) && ((actualLine = actualOutput.readLine()) != null)) { assertEquals("The lines are the same at line " + n, expectLine, actualLine); n++; } // "Both file must have the exact number of lines", assertEquals(null, expectLine); assertEquals(null, actualOutput.readLine()); // note, the last line of actual was not read yet expectOutput.close(); actualOutput.close(); }
diff --git a/java/src/test/com/dgrid/test/helpers/SQSHelperTestCase.java b/java/src/test/com/dgrid/test/helpers/SQSHelperTestCase.java index 15a5cd4..4389530 100644 --- a/java/src/test/com/dgrid/test/helpers/SQSHelperTestCase.java +++ b/java/src/test/com/dgrid/test/helpers/SQSHelperTestCase.java @@ -1,38 +1,38 @@ package com.dgrid.test.helpers; import com.dgrid.helpers.SQSHelper; import com.dgrid.test.BaseTestCase; import com.xerox.amazonws.sqs2.Message; public class SQSHelperTestCase extends BaseTestCase { public void testSQSHelper() throws Exception { String queueName = String.format( "1234567890-abcdefghijklm-test-queue-%1$d", System .currentTimeMillis()); String msgBody = "Hello, world"; SQSHelper sqs = (SQSHelper) super.getBean(SQSHelper.NAME); // create a queue? sqs.getMessageQueue(queueName); String msgid = sqs.send(queueName, msgBody); assertNotNull(msgid); // sleep for a bit - Thread.sleep(1000); + Thread.sleep(3000); // check queue size int queueSize = sqs.getQueueSize(queueName); assertEquals(queueSize, 1); // receive Message msg = sqs.receive(queueName); try { assertEquals(msg.getMessageBody(), msgBody); } finally { // delete the message sqs.delete(queueName, msg); // delete the queue sqs.deleteMessageQueue(queueName); } } }
true
true
public void testSQSHelper() throws Exception { String queueName = String.format( "1234567890-abcdefghijklm-test-queue-%1$d", System .currentTimeMillis()); String msgBody = "Hello, world"; SQSHelper sqs = (SQSHelper) super.getBean(SQSHelper.NAME); // create a queue? sqs.getMessageQueue(queueName); String msgid = sqs.send(queueName, msgBody); assertNotNull(msgid); // sleep for a bit Thread.sleep(1000); // check queue size int queueSize = sqs.getQueueSize(queueName); assertEquals(queueSize, 1); // receive Message msg = sqs.receive(queueName); try { assertEquals(msg.getMessageBody(), msgBody); } finally { // delete the message sqs.delete(queueName, msg); // delete the queue sqs.deleteMessageQueue(queueName); } }
public void testSQSHelper() throws Exception { String queueName = String.format( "1234567890-abcdefghijklm-test-queue-%1$d", System .currentTimeMillis()); String msgBody = "Hello, world"; SQSHelper sqs = (SQSHelper) super.getBean(SQSHelper.NAME); // create a queue? sqs.getMessageQueue(queueName); String msgid = sqs.send(queueName, msgBody); assertNotNull(msgid); // sleep for a bit Thread.sleep(3000); // check queue size int queueSize = sqs.getQueueSize(queueName); assertEquals(queueSize, 1); // receive Message msg = sqs.receive(queueName); try { assertEquals(msg.getMessageBody(), msgBody); } finally { // delete the message sqs.delete(queueName, msg); // delete the queue sqs.deleteMessageQueue(queueName); } }
diff --git a/src/main/ed/net/lb/GridMapping.java b/src/main/ed/net/lb/GridMapping.java index 501463076..8eb37fae9 100644 --- a/src/main/ed/net/lb/GridMapping.java +++ b/src/main/ed/net/lb/GridMapping.java @@ -1,170 +1,170 @@ // GridMapping.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.net.lb; import java.io.*; import java.net.*; import java.util.*; import ed.js.*; import ed.db.*; import ed.log.*; import ed.net.*; import ed.net.httpserver.*; import ed.cloud.*; import static ed.appserver.AppContextHolder.*; public class GridMapping extends MappingBase { public static class Factory implements MappingFactory { Factory(){ _cloud = Cloud.getInstanceIfOnGrid(); _logger = Logger.getLogger( "lb.gridmapping" ); _cacheFile = new File( "logs/gridmapcache" ); } public Mapping getMapping(){ try { GridMapping gm = new GridMapping( _cloud ); _prev = gm; writeToCache( gm ); return gm; } catch ( RuntimeException e ){ _logger.error( "couldn't load new grid config" , e ); if ( _prev != null ){ _logger.info( "using previously loaded config" ); return _prev; } if ( _cacheFile.exists() ){ _logger.info( "trying old cache from disk [" + _cacheFile + "]" ); try { return new TextMapping( _cacheFile ); } catch ( IOException ioe ){ _logger.error( "couldn't read old cache file [" + _cacheFile + "]" , ioe ); } } throw e; } } public long refreshRate(){ return 1000 * 30; } void writeToCache( GridMapping mapping ){ String s = mapping.toFileConfig(); int hash = s.hashCode(); if ( hash == _prevHash ) return; _prevHash = hash; try { byte[] data = s.getBytes( "utf8" ); FileOutputStream out = new FileOutputStream( _cacheFile ); out.write( data ); out.close(); } catch ( IOException ioe ){ _logger.error( "couldn't write gcache file" , ioe ); } } final Cloud _cloud; final Logger _logger; final File _cacheFile; private GridMapping _prev; private int _prevHash = 0; } GridMapping( Cloud c ){ super( "GridMapping" ); _cloud = c; if ( _cloud == null ) throw new RuntimeException( "can't have a GridMapping when not running on a grid!" ); DBBase db = (DBBase)_cloud.getScope().get("db"); for ( Iterator<JSObject> i = db.getCollection( "sites" ).find(); i.hasNext(); ){ final JSObject site = i.next(); final String name = site.get("name").toString().toLowerCase(); if ( site.get( "environments" ) == null ) continue; for ( Object eo : ((JSArray)site.get( "environments" ) ) ){ final JSObject e = (JSObject)eo; final String env = e.get( "name" ).toString().toLowerCase(); final String pool = e.get( "pool" ).toString().toLowerCase(); addSiteMapping( name , env , pool ); if ( e.get( "aliases" ) instanceof List ) for ( Object a : (List)(e.get( "aliases" )) ) - addSiteAlias( name , a.toString().toLowerCase() , pool ); + addSiteAlias( name , a.toString().toLowerCase() , env ); } } String defaultPool = null; for ( Iterator<JSObject> i = db.getCollection( "pools" ).find(); i.hasNext(); ){ final JSObject pool = i.next(); final String name = pool.get( "name" ).toString().toLowerCase(); for ( Object mo : ((JSArray)pool.get( "machines" ) ) ){ String m = mo.toString().toLowerCase(); addAddressToPool( name , m ); } if ( name.startsWith( "prod" ) ){ if ( defaultPool == null || name.compareTo( defaultPool ) > 0 ) defaultPool = name; } } setDefaultPool( defaultPool ); Iterator<JSObject> i = db.getCollection( "blocked_ips" ).find(); if ( i != null ) while ( i.hasNext() ) blockIp( i.next().get( "ip" ).toString() ); i = db.getCollection( "blocked_urls" ).find(); if ( i != null ) while ( i.hasNext() ) blockUrl( i.next().get( "url" ).toString() ); } final Cloud _cloud; public static void main( String args[] ){ System.out.println( (new Factory()).getMapping() ); } }
true
true
GridMapping( Cloud c ){ super( "GridMapping" ); _cloud = c; if ( _cloud == null ) throw new RuntimeException( "can't have a GridMapping when not running on a grid!" ); DBBase db = (DBBase)_cloud.getScope().get("db"); for ( Iterator<JSObject> i = db.getCollection( "sites" ).find(); i.hasNext(); ){ final JSObject site = i.next(); final String name = site.get("name").toString().toLowerCase(); if ( site.get( "environments" ) == null ) continue; for ( Object eo : ((JSArray)site.get( "environments" ) ) ){ final JSObject e = (JSObject)eo; final String env = e.get( "name" ).toString().toLowerCase(); final String pool = e.get( "pool" ).toString().toLowerCase(); addSiteMapping( name , env , pool ); if ( e.get( "aliases" ) instanceof List ) for ( Object a : (List)(e.get( "aliases" )) ) addSiteAlias( name , a.toString().toLowerCase() , pool ); } } String defaultPool = null; for ( Iterator<JSObject> i = db.getCollection( "pools" ).find(); i.hasNext(); ){ final JSObject pool = i.next(); final String name = pool.get( "name" ).toString().toLowerCase(); for ( Object mo : ((JSArray)pool.get( "machines" ) ) ){ String m = mo.toString().toLowerCase(); addAddressToPool( name , m ); } if ( name.startsWith( "prod" ) ){ if ( defaultPool == null || name.compareTo( defaultPool ) > 0 ) defaultPool = name; } } setDefaultPool( defaultPool ); Iterator<JSObject> i = db.getCollection( "blocked_ips" ).find(); if ( i != null ) while ( i.hasNext() ) blockIp( i.next().get( "ip" ).toString() ); i = db.getCollection( "blocked_urls" ).find(); if ( i != null ) while ( i.hasNext() ) blockUrl( i.next().get( "url" ).toString() ); }
GridMapping( Cloud c ){ super( "GridMapping" ); _cloud = c; if ( _cloud == null ) throw new RuntimeException( "can't have a GridMapping when not running on a grid!" ); DBBase db = (DBBase)_cloud.getScope().get("db"); for ( Iterator<JSObject> i = db.getCollection( "sites" ).find(); i.hasNext(); ){ final JSObject site = i.next(); final String name = site.get("name").toString().toLowerCase(); if ( site.get( "environments" ) == null ) continue; for ( Object eo : ((JSArray)site.get( "environments" ) ) ){ final JSObject e = (JSObject)eo; final String env = e.get( "name" ).toString().toLowerCase(); final String pool = e.get( "pool" ).toString().toLowerCase(); addSiteMapping( name , env , pool ); if ( e.get( "aliases" ) instanceof List ) for ( Object a : (List)(e.get( "aliases" )) ) addSiteAlias( name , a.toString().toLowerCase() , env ); } } String defaultPool = null; for ( Iterator<JSObject> i = db.getCollection( "pools" ).find(); i.hasNext(); ){ final JSObject pool = i.next(); final String name = pool.get( "name" ).toString().toLowerCase(); for ( Object mo : ((JSArray)pool.get( "machines" ) ) ){ String m = mo.toString().toLowerCase(); addAddressToPool( name , m ); } if ( name.startsWith( "prod" ) ){ if ( defaultPool == null || name.compareTo( defaultPool ) > 0 ) defaultPool = name; } } setDefaultPool( defaultPool ); Iterator<JSObject> i = db.getCollection( "blocked_ips" ).find(); if ( i != null ) while ( i.hasNext() ) blockIp( i.next().get( "ip" ).toString() ); i = db.getCollection( "blocked_urls" ).find(); if ( i != null ) while ( i.hasNext() ) blockUrl( i.next().get( "url" ).toString() ); }