diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/com/pokebros/android/pokemononline/ChatActivity.java b/src/com/pokebros/android/pokemononline/ChatActivity.java index 839d9b0f..2ec44717 100644 --- a/src/com/pokebros/android/pokemononline/ChatActivity.java +++ b/src/com/pokebros/android/pokemononline/ChatActivity.java @@ -1,888 +1,887 @@ package com.pokebros.android.pokemononline; import java.util.Enumeration; import java.util.LinkedList; import java.util.ListIterator; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.NotificationManager; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.IBinder; import android.text.Html; import android.text.InputType; import android.text.SpannableStringBuilder; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnKeyListener; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.pokebros.android.pokemononline.battle.ChallengeEnums.ChallengeDesc; import com.pokebros.android.pokemononline.battle.ChallengeEnums.Clauses; import com.pokebros.android.pokemononline.battle.ChallengeEnums.Mode; import com.pokebros.android.pokemononline.player.PlayerInfo; import com.pokebros.android.pokemononline.player.PlayerInfo.TierStanding; import com.pokebros.android.pokemononline.poke.UniqueID; import com.pokebros.android.utilities.StringUtilities; import com.pokebros.android.utilities.TwoViewsArrayAdapter; import de.marcreichelt.android.ChatRealViewSwitcher; public class ChatActivity extends Activity { static final String TAG = "ChatActivity"; private enum ChatDialog { Challenge, AskForPass, ConfirmDisconnect, FindBattle, TierSelection, PlayerInfo, ChallengeMode } public final static int SWIPE_TIME_THRESHOLD = 100; private enum ChatContext { ChallengePlayer, ViewPlayerInfo, JoinChannel, LeaveChannel, WatchBattle; } private PlayerListAdapter playerAdapter = null; private ChannelListAdapter channelAdapter = null; private MessageListAdapter messageAdapter = null; public ProgressDialog progressDialog; private ChatListView players; private ListView channels; private NetworkService netServ = null; private ListView chatView; private EditText chatInput; private ChatRealViewSwitcher chatViewSwitcher; private String packName = "com.pokebros.android.pokemononline"; private PlayerInfo lastClickedPlayer; private Channel lastClickedChannel; private boolean loading = true; private SharedPreferences prefs; class TierAlertDialog extends AlertDialog { public Tier parentTier = null; public ListView dialogListView = null; protected TierAlertDialog(Context context, Tier t) { super(context); parentTier = t; dialogListView = makeTierListView(); setTitle("Tier Selection"); setView(dialogListView); setIcon(0); // Don't want an icon } @Override public void onBackPressed() { if(parentTier.parentTier == null) { // this is the top level dismiss(); } else { dialogListView.setAdapter(new ArrayAdapter<Tier>(ChatActivity.this, R.layout.tier_list_item, parentTier.parentTier.subTiers)); parentTier = parentTier.parentTier; } } ListView makeTierListView() { ListView lv = new ListView(ChatActivity.this); lv.setAdapter(new ArrayAdapter<Tier>(ChatActivity.this, R.layout.tier_list_item, parentTier.subTiers)); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Tier self = parentTier.subTiers.get((int)id); if(self.subTiers.size() > 0) { parentTier = self; ((ListView)parent).setAdapter(new ArrayAdapter<Tier>(ChatActivity.this, R.layout.tier_list_item, parentTier.subTiers)); } else { Baos b = new Baos(); b.putString(self.name); netServ.socket.sendMessage(b, Command.TierSelection); Toast.makeText(ChatActivity.this, "Tier Selected: " + self.name, Toast.LENGTH_SHORT).show(); dismiss(); } } }); return lv; } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { System.out.println("CREATED CHAT ACTIVITY"); if (loading) { progressDialog = ProgressDialog.show(ChatActivity.this, "","Loading. Please wait...", true); progressDialog.setCancelable(true); progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { disconnect(); } }); } super.onCreate(savedInstanceState); setContentView(R.layout.chat); prefs = getPreferences(MODE_PRIVATE); chatView = (ListView) findViewById(R.id.chatView); chatViewSwitcher = (ChatRealViewSwitcher)findViewById(R.id.chatPokeSwitcher); chatViewSwitcher.setCurrentScreen(1); //Player List Stuff** players = (ChatListView)findViewById(R.id.playerlisting); playerAdapter = new PlayerListAdapter(ChatActivity.this, 0); registerForContextMenu(players); //Channel List Stuff** channels = (ListView)findViewById(R.id.channellisting); channelAdapter = new ChannelListAdapter(this, 0); registerForContextMenu(channels); channels.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Channel clicked = channelAdapter.getItem(position); if(netServ != null && netServ.joinedChannels.contains(clicked)) { // XXX remove is implemented as O(N) we could do it O(1) if we really had to netServ.joinedChannels.remove(clicked); netServ.joinedChannels.addFirst(clicked); populateUI(true); } } }); bindService(new Intent(ChatActivity.this, NetworkService.class), connection, Context.BIND_AUTO_CREATE); chatInput = (EditText) findViewById(R.id.chatInput); // Hide the soft-keyboard when the activity is created chatInput.setInputType(InputType.TYPE_NULL); chatInput.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { chatInput.setInputType(InputType.TYPE_CLASS_TEXT); chatInput.onTouchEvent(event); return true; } }); chatInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button // and the socket is connected if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER) && netServ != null && netServ.socket != null && netServ.socket.isConnected()) { // Perform action on key press Baos b = new Baos(); b.write(1); //channel message b.write(0); //no html b.putInt(currentChannel().id); b.putString(chatInput.getText().toString()); netServ.socket.sendMessage(b, Command.SendMessage); chatInput.getText().clear(); return true; } return false; } }); } @Override public void onResume() { super.onResume(); chatViewSwitcher.setCurrentScreen(1); if (netServ != null && !netServ.hasBattle()) netServ.showNotification(ChatActivity.class, "Chat"); else if (netServ != null && netServ.hasBattle() && netServ.battle.gotEnd) netServ.battleActivity.endBattle(); checkChallenges(); checkAskForPass(); checkFailedConnection(); } private ServiceConnection connection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { netServ = ((NetworkService.LocalBinder)service).getService(); if (!netServ.hasBattle()) netServ.showNotification(ChatActivity.class, "Chat"); updateTitle(); netServ.chatActivity = ChatActivity.this; if (netServ.joinedChannels.peek() != null && !netServ.joinedChannels.isEmpty()) { populateUI(false); if (progressDialog.isShowing()) progressDialog.dismiss(); loading = false; } checkChallenges(); checkAskForPass(); checkFailedConnection(); } public void onServiceDisconnected(ComponentName className) { netServ.chatActivity = null; netServ = null; } }; void updateTitle() { runOnUiThread(new Runnable() { public void run() { ChatActivity.this.setTitle(netServ.serverName); } }); } /** * Gives the current channel * @return the current channel as a {@link Channel} object */ public Channel currentChannel() { /* Maybe later instead of this hack, use onSavedInstanceState properly ? */ return netServ.joinedChannels.peek(); } public void populateUI(boolean clear) { Channel currentChannel = netServ.joinedChannels.peek(); if (currentChannel != null) { // Populate the player list if (clear) { playerAdapter = new PlayerListAdapter(ChatActivity.this, 0); channelAdapter = new ChannelListAdapter(ChatActivity.this, 0); } messageAdapter = new MessageListAdapter(currentChannel, ChatActivity.this); Enumeration<PlayerInfo> e = netServ.joinedChannels.peek().players.elements(); playerAdapter.setNotifyOnChange(false); while(e.hasMoreElements()) { playerAdapter.add(e.nextElement()); } playerAdapter.sortByNick(); playerAdapter.setNotifyOnChange(true); // Populate the Channel list Enumeration<Channel> c = netServ.channels.elements(); channelAdapter.setNotifyOnChange(false); while(c.hasMoreElements()) channelAdapter.addChannel(c.nextElement()); channelAdapter.sortByName(); channelAdapter.setNotifyOnChange(true); // Load scrollback runOnUiThread(new Runnable() { public void run() { players.setAdapter(playerAdapter); channels.setAdapter(channelAdapter); chatView.setAdapter(messageAdapter); playerAdapter.notifyDataSetChanged(); channelAdapter.notifyDataSetChanged(); messageAdapter.notifyDataSetChanged(); chatView.setSelection(messageAdapter.getCount() - 1); chatViewSwitcher.invalidate(); } }); } } public synchronized void updateChat() { if (messageAdapter == null) return; final int delta = messageAdapter.channel.lastSeen - messageAdapter.lastSeen; if (delta <= 0) return; Runnable update = new Runnable() { public void run() { LinkedList<SpannableStringBuilder> msgList = messageAdapter.channel.messageList; int top = messageAdapter.channel.messageList.size() - delta; ListIterator<SpannableStringBuilder> it = msgList.listIterator(top < Channel.HIST_LIMIT ? top : Channel.HIST_LIMIT); while (it.hasNext()) { SpannableStringBuilder next = it.next(); messageAdapter.add(next); messageAdapter.lastSeen++; } messageAdapter.notifyDataSetChanged(); if (chatView.getLastVisiblePosition() + delta == top || !ChatActivity.this.hasWindowFocus()) { chatView.setSelection(messageAdapter.getCount() - 1); } chatViewSwitcher.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { public void onGlobalLayout() { chatViewSwitcher.getViewTreeObserver().removeGlobalOnLayoutListener(this); int heightDiff = chatViewSwitcher.getRootView().getHeight() - chatViewSwitcher.getHeight(); if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard... chatView.setSelection(messageAdapter.getCount() - 1); } } }); synchronized(this) { this.notify(); } } }; synchronized(update) { runOnUiThread(update); try { update.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public void notifyChallenge() { runOnUiThread(new Runnable() { public void run() { checkChallenges(); } } ); } private void checkChallenges() { if (netServ != null) { IncomingChallenge challenge = netServ.challenges.peek(); if (challenge != null) { ChatActivity.this.showDialog(ChatDialog.Challenge.ordinal()); ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(IncomingChallenge.note); } } } public void notifyAskForPass() { runOnUiThread(new Runnable() { public void run() { checkAskForPass(); } } ); } private void checkAskForPass() { if (netServ != null && netServ.askedForPass) showDialog(ChatDialog.AskForPass.ordinal()); } public void notifyFailedConnection() { disconnect(); } private void checkFailedConnection() { if(netServ != null && netServ.failedConnect) { disconnect(); } } @Override protected Dialog onCreateDialog(final int id) { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); switch (ChatDialog.values()[id]) { case Challenge: { if (netServ == null) { - removeDialog(id); - dismissDialog(id); + return null; } final IncomingChallenge challenge = netServ.challenges.poll(); View challengedLayout = inflater.inflate(R.layout.player_info_dialog, (LinearLayout)findViewById(R.id.player_info_dialog)); PlayerInfo opp = netServ.players.get(challenge.opponent); ImageView[] oppPokeIcons = new ImageView[6]; TextView oppInfo, oppTeam, oppName, oppTier, oppRating; builder.setView(challengedLayout) .setCancelable(false) .setNegativeButton(this.getString(R.string.decline), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Decline challenge if (netServ.socket.isConnected()) netServ.socket.sendMessage( constructChallenge(ChallengeDesc.Refused.ordinal(), challenge.opponent, challenge.clauses, challenge.mode), Command.ChallengeStuff); removeDialog(id); checkChallenges(); } }) .setPositiveButton(this.getString(R.string.accept), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Accept challenge if (netServ.socket.isConnected()) netServ.socket.sendMessage( constructChallenge(ChallengeDesc.Accepted.ordinal(), challenge.opponent, challenge.clauses, challenge.mode), Command.ChallengeStuff); // Without removeDialog() the dialog is reused and can only // be modified in onPrepareDialog(). This dialog changes // so much that I doubt it's worth the code to deal with // onPrepareDialog() but we should use it if we have complex // dialogs that only need to change a little removeDialog(id); checkChallenges(); } }); final AlertDialog oppInfoDialog = builder.create(); for(int i = 0; i < 6; i++){ oppPokeIcons[i] = (ImageView)challengedLayout.findViewById(getResources().getIdentifier("player_info_poke" + (i+1), "id", packName)); //oppPokeIcons[i].setImageDrawable(getIcon(opp.pokes[i])); } oppInfo = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info", "id", packName)); oppInfo.setText(Html.fromHtml("<b>Info: </b>" + StringUtilities.escapeHtml(opp.info()))); oppTeam = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_team", "id", packName)); oppTeam.setText(opp.nick() + "'s team:"); oppName = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_name", "id", packName)); oppName.setText(this.getString(R.string.accept_challenge) + " " + opp.nick() + "?"); oppName.setTextSize(18); oppTier = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_tier", "id", packName)); //oppTier.setText(Html.fromHtml("<b>Tier: </b>" + NetworkService.escapeHtml(opp.tier))); oppRating = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_rating", "id", packName)); //oppRating.setText(Html.fromHtml("<b>Rating: </b>" + NetworkService.escapeHtml(new Short(opp.rating).toString()))); return oppInfoDialog; } case AskForPass: { //View layout = inflater.inflate(R.layout.ask_for_pass, null); final EditText passField = new EditText(this); passField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); //passField.setTransformationMethod(PasswordTransformationMethod.getInstance()); builder.setMessage("Please enter your password " + netServ.mePlayer.nick() + ".") .setCancelable(true) .setView(passField) .setPositiveButton("Done", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (netServ != null) { netServ.sendPass(passField.getText().toString()); } removeDialog(id); } }) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { removeDialog(id); disconnect(); } }); final AlertDialog dialog = builder.create(); passField.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }); return dialog; } case ConfirmDisconnect: { builder.setMessage("Really disconnect?") .setCancelable(true) .setPositiveButton("Disconnect", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { disconnect(); } }) .setNegativeButton("Cancel", null); return builder.create(); } case FindBattle: { final EditText range = new EditText(this); range.append("" + (prefs.contains("range") ? prefs.getInt("range", 0) : "")); range.setInputType(InputType.TYPE_CLASS_NUMBER); range.setHint("Range"); builder.setTitle(R.string.find_a_battle) .setMultiChoiceItems(new CharSequence[]{"Force Rated", "Force Same Tier", "Only within range"}, new boolean[]{prefs.getBoolean("findOption0", false), prefs.getBoolean("findOption1", false), prefs.getBoolean("findOption2", false)}, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { prefs.edit().putBoolean("findOption" + which, isChecked).commit(); } }) .setView(range) .setPositiveButton("Find", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (netServ != null && netServ.socket.isConnected()) { netServ.findingBattle = true; try { prefs.edit().putInt("range", Integer.valueOf(range.getText().toString())).commit(); } catch (NumberFormatException e) { prefs.edit().remove("range").commit(); } netServ.socket.sendMessage( constructFindBattle(prefs.getBoolean("findOption0", false), prefs.getBoolean("findOption1", false), prefs.getBoolean("findOption2", false), prefs.getInt("range", 200), (byte) 0), Command.FindBattle); } } }); return builder.create(); } case TierSelection: { if (netServ == null) { return null; } return new TierAlertDialog(this, netServ.superTier); } case PlayerInfo: { View layout = inflater.inflate(R.layout.player_info_dialog, (LinearLayout)findViewById(R.id.player_info_dialog)); ImageView[] pPokeIcons = new ImageView[6]; TextView pInfo, pName; ListView ratings; builder.setView(layout) .setNegativeButton("Back", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { removeDialog(id); } }) .setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog) { removeDialog(id); } }) .setPositiveButton("Challenge", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { showDialog(ChatDialog.ChallengeMode.ordinal()); removeDialog(id); }}); final AlertDialog pInfoDialog = builder.create(); for(int i = 0; i < 6; i++){ pPokeIcons[i] = (ImageView)layout.findViewById(getResources().getIdentifier("player_info_poke" + (i+1), "id", packName)); //pPokeIcons[i].setImageDrawable(getIcon(lastClickedPlayer.pokes[i])); } pInfo = (TextView)layout.findViewById(R.id.player_info); pInfo.setText(Html.fromHtml("<b>Info: </b>" + StringUtilities.escapeHtml(lastClickedPlayer.info()))); pName = (TextView)layout.findViewById(R.id.player_info_name); pName.setText(lastClickedPlayer.nick()); ratings = (ListView)layout.findViewById(R.id.player_info_tiers); ratings.setAdapter(new TwoViewsArrayAdapter<TierStanding>(this, android.R.layout.simple_list_item_2, android.R.id.text1, android.R.id.text2, lastClickedPlayer.tierStandings, PlayerInfo.tierGetter)); return pInfoDialog; } case ChallengeMode: { final Clauses[] clauses = Clauses.values(); final int numClauses = clauses.length; final String[] clauseNames = new String[numClauses]; final boolean[] checked = new boolean[numClauses]; for (int i=0; i < numClauses; i++) { clauseNames[i] = clauses[i].toString(); checked[i] = prefs.getBoolean("challengeOption" + i, false); } builder.setMultiChoiceItems(clauseNames, checked, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { prefs.edit().putBoolean("challengeOption" + which, isChecked).commit(); } }) .setPositiveButton("Challenge", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { int clauses = 0; for (int i = 0; i < numClauses; i++) clauses |= (prefs.getBoolean("challengeOption" + i, false) ? Clauses.values()[i].mask() : 0); if (netServ != null && netServ.socket != null && netServ.socket.isConnected()) netServ.socket.sendMessage(constructChallenge(ChallengeDesc.Sent.ordinal(), lastClickedPlayer.id, clauses, Mode.Singles.ordinal()), Command.ChallengeStuff); removeDialog(id); } }) .setNegativeButton("Back", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { removeDialog(id); } }) .setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog) { removeDialog(id); } }) .setTitle("Select clauses"); return builder.create(); } default: { return new Dialog(this); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.chatoptions, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem findbattle = menu.findItem(R.id.findbattle); if (netServ != null && netServ.findingBattle) { findbattle.setTitle("Cancel Find Battle"); } else if(netServ != null && !netServ.hasBattle()) { findbattle.setTitle(R.string.find_a_battle); } else if(netServ != null && netServ.hasBattle()) { findbattle.setTitle(R.string.tobattlescreen); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.chat_disconnect: showDialog(ChatDialog.ConfirmDisconnect.ordinal()); break; case R.id.findbattle: if (netServ.socket.isConnected()) { if (netServ.findingBattle && !netServ.hasBattle()) { netServ.findingBattle = false; netServ.socket.sendMessage( constructChallenge(ChallengeDesc.Cancelled.ordinal(), 0, Clauses.SleepClause.mask(), Mode.Singles.ordinal()), Command.ChallengeStuff); } else if(!netServ.findingBattle && netServ.hasBattle()) { Intent in = new Intent(this, BattleActivity.class); in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(in); break; } else { showDialog(ChatDialog.FindBattle.ordinal()); } } break; case R.id.preferences: //TODO: Make actual preferences menu // Launch Preference activity //Toast.makeText(ChatActivity.this, "Preferences not Implemented Yet", // Toast.LENGTH_SHORT).show(); showDialog(ChatDialog.TierSelection.ordinal()); break; } return true; } public void makeToast(final String s, final String length) { if (length == "long") { runOnUiThread(new Runnable() { public void run() { Toast.makeText(ChatActivity.this, s, Toast.LENGTH_LONG).show(); } }); } else if(length == "short") { runOnUiThread(new Runnable() { public void run() { Toast.makeText(ChatActivity.this, s, Toast.LENGTH_SHORT).show(); } }); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo aMenuInfo = (AdapterView.AdapterContextMenuInfo) menuInfo; switch(v.getId()){ case R.id.playerlisting: lastClickedPlayer = playerAdapter.getItem(aMenuInfo.position); String pName = lastClickedPlayer.nick(); menu.setHeaderTitle(pName); menu.add(Menu.NONE, ChatContext.ChallengePlayer.ordinal(), 0, "Challenge " + pName); menu.add(Menu.NONE, ChatContext.ViewPlayerInfo.ordinal(), 0, "View Player Info"); if (netServ != null) { for (Integer battleid : lastClickedPlayer.battles) { menu.add(Menu.NONE, ChatContext.WatchBattle.ordinal(), 0, "Watch battle against " + netServ.playerName(netServ.battle(battleid).opponent(lastClickedPlayer.id))) .setIntent(new Intent().putExtra("battle", battleid)); } } break; case R.id.channellisting: lastClickedChannel = channelAdapter.getItem(aMenuInfo.position); String cName = lastClickedChannel.name; menu.setHeaderTitle(cName); if (netServ.joinedChannels.contains(lastClickedChannel)) menu.add(Menu.NONE, ChatContext.LeaveChannel.ordinal(), 0, "Leave " + cName); else menu.add(Menu.NONE, ChatContext.JoinChannel.ordinal(), 0, "Join " + cName); break; } } @Override public boolean onContextItemSelected(MenuItem item) { switch(ChatContext.values()[item.getItemId()]){ case ChallengePlayer: showDialog(ChatDialog.ChallengeMode.ordinal()); break; case ViewPlayerInfo: showDialog(ChatDialog.PlayerInfo.ordinal()); break; case WatchBattle: int battleid = item.getIntent().getIntExtra("battleid", 0); if (battleid != 0) { /* watch battle */ } break; case JoinChannel: Baos join = new Baos(); join.putString(lastClickedChannel.name); if (netServ != null && netServ.socket != null && netServ.socket.isConnected()) netServ.socket.sendMessage(join, Command.JoinChannel); break; case LeaveChannel: Baos leave = new Baos(); leave.putInt(lastClickedChannel.id); if (netServ != null && netServ.socket != null && netServ.socket.isConnected()) netServ.socket.sendMessage(leave, Command.LeaveChannel); break; } return true; } private void disconnect() { if (netServ != null) netServ.disconnect(); if (progressDialog != null) progressDialog.dismiss(); Intent intent = new Intent(this, RegistryActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("sticky", true); if(netServ == null || netServ.socket == null) intent.putExtra("failedConnect", true); startActivity(intent); ChatActivity.this.finish(); } private Baos constructChallenge(int desc, int opp, int clauses, int mode) { Baos challenge = new Baos(); challenge.write(desc); challenge.putInt(opp); challenge.putInt(clauses); challenge.write(mode); return challenge; } private Baos constructFindBattle(boolean forceRated, boolean forceSameTier, boolean onlyInRange, int i, byte mode) { Baos find = new Baos(); int flags = 0; flags |= (forceRated ? 1:0); flags |= (forceSameTier ? 2:0); flags |= (onlyInRange ? 4:0); find.putInt(flags); find.putShort((short)i); find.write(mode); return find; } public void removePlayer(final PlayerInfo pi){ synchronized(players) { if (players.isPressed()) { try { players.wait(); } catch (InterruptedException e) {} } } runOnUiThread(new Runnable() { public void run() { synchronized(playerAdapter) { playerAdapter.remove(pi); } } }); } public void addPlayer(final PlayerInfo pi) { synchronized(players) { if (players.isPressed()) { try { players.wait(); } catch (InterruptedException e) {} } } runOnUiThread(new Runnable() { public void run() { synchronized(playerAdapter) { playerAdapter.add(pi); } } }); } public void updatePlayer(final PlayerInfo pi) { runOnUiThread(new Runnable() { public void run() { synchronized (playerAdapter) { playerAdapter.notifyDataSetChanged(); } } }); } public void removeChannel(final Channel ch){ runOnUiThread(new Runnable() { public void run() { channelAdapter.removeChannel(ch); } }); } public void addChannel(final Channel ch) { runOnUiThread(new Runnable() { public void run() { channelAdapter.addChannel(ch); } }); } private Drawable getIcon(UniqueID uid) { Resources resources = getResources(); int resID = resources.getIdentifier("pi" + uid.pokeNum + (uid.subNum == 0 ? "" : "_" + uid.subNum) + "_icon", "drawable", packName); if (resID == 0) resID = resources.getIdentifier("pi" + uid.pokeNum + "_icon", "drawable", packName); return resources.getDrawable(resID); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); chatViewSwitcher.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { public void onGlobalLayout() { chatViewSwitcher.getViewTreeObserver().removeGlobalOnLayoutListener(this); chatViewSwitcher.setCurrentScreen(1); if (messageAdapter != null) chatView.setSelection(messageAdapter.getCount() - 1); } }); } @Override public void onDestroy() { unbindService(connection); super.onDestroy(); } }
true
true
protected Dialog onCreateDialog(final int id) { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); switch (ChatDialog.values()[id]) { case Challenge: { if (netServ == null) { removeDialog(id); dismissDialog(id); } final IncomingChallenge challenge = netServ.challenges.poll(); View challengedLayout = inflater.inflate(R.layout.player_info_dialog, (LinearLayout)findViewById(R.id.player_info_dialog)); PlayerInfo opp = netServ.players.get(challenge.opponent); ImageView[] oppPokeIcons = new ImageView[6]; TextView oppInfo, oppTeam, oppName, oppTier, oppRating; builder.setView(challengedLayout) .setCancelable(false) .setNegativeButton(this.getString(R.string.decline), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Decline challenge if (netServ.socket.isConnected()) netServ.socket.sendMessage( constructChallenge(ChallengeDesc.Refused.ordinal(), challenge.opponent, challenge.clauses, challenge.mode), Command.ChallengeStuff); removeDialog(id); checkChallenges(); } }) .setPositiveButton(this.getString(R.string.accept), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Accept challenge if (netServ.socket.isConnected()) netServ.socket.sendMessage( constructChallenge(ChallengeDesc.Accepted.ordinal(), challenge.opponent, challenge.clauses, challenge.mode), Command.ChallengeStuff); // Without removeDialog() the dialog is reused and can only // be modified in onPrepareDialog(). This dialog changes // so much that I doubt it's worth the code to deal with // onPrepareDialog() but we should use it if we have complex // dialogs that only need to change a little removeDialog(id); checkChallenges(); } }); final AlertDialog oppInfoDialog = builder.create(); for(int i = 0; i < 6; i++){ oppPokeIcons[i] = (ImageView)challengedLayout.findViewById(getResources().getIdentifier("player_info_poke" + (i+1), "id", packName)); //oppPokeIcons[i].setImageDrawable(getIcon(opp.pokes[i])); } oppInfo = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info", "id", packName)); oppInfo.setText(Html.fromHtml("<b>Info: </b>" + StringUtilities.escapeHtml(opp.info()))); oppTeam = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_team", "id", packName)); oppTeam.setText(opp.nick() + "'s team:"); oppName = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_name", "id", packName)); oppName.setText(this.getString(R.string.accept_challenge) + " " + opp.nick() + "?"); oppName.setTextSize(18); oppTier = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_tier", "id", packName)); //oppTier.setText(Html.fromHtml("<b>Tier: </b>" + NetworkService.escapeHtml(opp.tier))); oppRating = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_rating", "id", packName)); //oppRating.setText(Html.fromHtml("<b>Rating: </b>" + NetworkService.escapeHtml(new Short(opp.rating).toString()))); return oppInfoDialog; } case AskForPass: { //View layout = inflater.inflate(R.layout.ask_for_pass, null); final EditText passField = new EditText(this); passField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); //passField.setTransformationMethod(PasswordTransformationMethod.getInstance()); builder.setMessage("Please enter your password " + netServ.mePlayer.nick() + ".") .setCancelable(true) .setView(passField) .setPositiveButton("Done", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (netServ != null) { netServ.sendPass(passField.getText().toString()); } removeDialog(id); } }) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { removeDialog(id); disconnect(); } }); final AlertDialog dialog = builder.create(); passField.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }); return dialog; } case ConfirmDisconnect: { builder.setMessage("Really disconnect?") .setCancelable(true) .setPositiveButton("Disconnect", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { disconnect(); } }) .setNegativeButton("Cancel", null); return builder.create(); } case FindBattle: { final EditText range = new EditText(this); range.append("" + (prefs.contains("range") ? prefs.getInt("range", 0) : "")); range.setInputType(InputType.TYPE_CLASS_NUMBER); range.setHint("Range"); builder.setTitle(R.string.find_a_battle) .setMultiChoiceItems(new CharSequence[]{"Force Rated", "Force Same Tier", "Only within range"}, new boolean[]{prefs.getBoolean("findOption0", false), prefs.getBoolean("findOption1", false), prefs.getBoolean("findOption2", false)}, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { prefs.edit().putBoolean("findOption" + which, isChecked).commit(); } }) .setView(range) .setPositiveButton("Find", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (netServ != null && netServ.socket.isConnected()) { netServ.findingBattle = true; try { prefs.edit().putInt("range", Integer.valueOf(range.getText().toString())).commit(); } catch (NumberFormatException e) { prefs.edit().remove("range").commit(); } netServ.socket.sendMessage( constructFindBattle(prefs.getBoolean("findOption0", false), prefs.getBoolean("findOption1", false), prefs.getBoolean("findOption2", false), prefs.getInt("range", 200), (byte) 0), Command.FindBattle); } } }); return builder.create(); } case TierSelection: { if (netServ == null) { return null; } return new TierAlertDialog(this, netServ.superTier); } case PlayerInfo: { View layout = inflater.inflate(R.layout.player_info_dialog, (LinearLayout)findViewById(R.id.player_info_dialog)); ImageView[] pPokeIcons = new ImageView[6]; TextView pInfo, pName; ListView ratings; builder.setView(layout) .setNegativeButton("Back", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { removeDialog(id); } }) .setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog) { removeDialog(id); } }) .setPositiveButton("Challenge", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { showDialog(ChatDialog.ChallengeMode.ordinal()); removeDialog(id); }}); final AlertDialog pInfoDialog = builder.create(); for(int i = 0; i < 6; i++){ pPokeIcons[i] = (ImageView)layout.findViewById(getResources().getIdentifier("player_info_poke" + (i+1), "id", packName)); //pPokeIcons[i].setImageDrawable(getIcon(lastClickedPlayer.pokes[i])); } pInfo = (TextView)layout.findViewById(R.id.player_info); pInfo.setText(Html.fromHtml("<b>Info: </b>" + StringUtilities.escapeHtml(lastClickedPlayer.info()))); pName = (TextView)layout.findViewById(R.id.player_info_name); pName.setText(lastClickedPlayer.nick()); ratings = (ListView)layout.findViewById(R.id.player_info_tiers); ratings.setAdapter(new TwoViewsArrayAdapter<TierStanding>(this, android.R.layout.simple_list_item_2, android.R.id.text1, android.R.id.text2, lastClickedPlayer.tierStandings, PlayerInfo.tierGetter)); return pInfoDialog; } case ChallengeMode: { final Clauses[] clauses = Clauses.values(); final int numClauses = clauses.length; final String[] clauseNames = new String[numClauses]; final boolean[] checked = new boolean[numClauses]; for (int i=0; i < numClauses; i++) { clauseNames[i] = clauses[i].toString(); checked[i] = prefs.getBoolean("challengeOption" + i, false); } builder.setMultiChoiceItems(clauseNames, checked, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { prefs.edit().putBoolean("challengeOption" + which, isChecked).commit(); } }) .setPositiveButton("Challenge", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { int clauses = 0; for (int i = 0; i < numClauses; i++) clauses |= (prefs.getBoolean("challengeOption" + i, false) ? Clauses.values()[i].mask() : 0); if (netServ != null && netServ.socket != null && netServ.socket.isConnected()) netServ.socket.sendMessage(constructChallenge(ChallengeDesc.Sent.ordinal(), lastClickedPlayer.id, clauses, Mode.Singles.ordinal()), Command.ChallengeStuff); removeDialog(id); } }) .setNegativeButton("Back", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { removeDialog(id); } }) .setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog) { removeDialog(id); } }) .setTitle("Select clauses"); return builder.create(); } default: { return new Dialog(this); } } }
protected Dialog onCreateDialog(final int id) { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); switch (ChatDialog.values()[id]) { case Challenge: { if (netServ == null) { return null; } final IncomingChallenge challenge = netServ.challenges.poll(); View challengedLayout = inflater.inflate(R.layout.player_info_dialog, (LinearLayout)findViewById(R.id.player_info_dialog)); PlayerInfo opp = netServ.players.get(challenge.opponent); ImageView[] oppPokeIcons = new ImageView[6]; TextView oppInfo, oppTeam, oppName, oppTier, oppRating; builder.setView(challengedLayout) .setCancelable(false) .setNegativeButton(this.getString(R.string.decline), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Decline challenge if (netServ.socket.isConnected()) netServ.socket.sendMessage( constructChallenge(ChallengeDesc.Refused.ordinal(), challenge.opponent, challenge.clauses, challenge.mode), Command.ChallengeStuff); removeDialog(id); checkChallenges(); } }) .setPositiveButton(this.getString(R.string.accept), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Accept challenge if (netServ.socket.isConnected()) netServ.socket.sendMessage( constructChallenge(ChallengeDesc.Accepted.ordinal(), challenge.opponent, challenge.clauses, challenge.mode), Command.ChallengeStuff); // Without removeDialog() the dialog is reused and can only // be modified in onPrepareDialog(). This dialog changes // so much that I doubt it's worth the code to deal with // onPrepareDialog() but we should use it if we have complex // dialogs that only need to change a little removeDialog(id); checkChallenges(); } }); final AlertDialog oppInfoDialog = builder.create(); for(int i = 0; i < 6; i++){ oppPokeIcons[i] = (ImageView)challengedLayout.findViewById(getResources().getIdentifier("player_info_poke" + (i+1), "id", packName)); //oppPokeIcons[i].setImageDrawable(getIcon(opp.pokes[i])); } oppInfo = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info", "id", packName)); oppInfo.setText(Html.fromHtml("<b>Info: </b>" + StringUtilities.escapeHtml(opp.info()))); oppTeam = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_team", "id", packName)); oppTeam.setText(opp.nick() + "'s team:"); oppName = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_name", "id", packName)); oppName.setText(this.getString(R.string.accept_challenge) + " " + opp.nick() + "?"); oppName.setTextSize(18); oppTier = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_tier", "id", packName)); //oppTier.setText(Html.fromHtml("<b>Tier: </b>" + NetworkService.escapeHtml(opp.tier))); oppRating = (TextView)challengedLayout.findViewById(getResources().getIdentifier("player_info_rating", "id", packName)); //oppRating.setText(Html.fromHtml("<b>Rating: </b>" + NetworkService.escapeHtml(new Short(opp.rating).toString()))); return oppInfoDialog; } case AskForPass: { //View layout = inflater.inflate(R.layout.ask_for_pass, null); final EditText passField = new EditText(this); passField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); //passField.setTransformationMethod(PasswordTransformationMethod.getInstance()); builder.setMessage("Please enter your password " + netServ.mePlayer.nick() + ".") .setCancelable(true) .setView(passField) .setPositiveButton("Done", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (netServ != null) { netServ.sendPass(passField.getText().toString()); } removeDialog(id); } }) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { removeDialog(id); disconnect(); } }); final AlertDialog dialog = builder.create(); passField.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }); return dialog; } case ConfirmDisconnect: { builder.setMessage("Really disconnect?") .setCancelable(true) .setPositiveButton("Disconnect", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { disconnect(); } }) .setNegativeButton("Cancel", null); return builder.create(); } case FindBattle: { final EditText range = new EditText(this); range.append("" + (prefs.contains("range") ? prefs.getInt("range", 0) : "")); range.setInputType(InputType.TYPE_CLASS_NUMBER); range.setHint("Range"); builder.setTitle(R.string.find_a_battle) .setMultiChoiceItems(new CharSequence[]{"Force Rated", "Force Same Tier", "Only within range"}, new boolean[]{prefs.getBoolean("findOption0", false), prefs.getBoolean("findOption1", false), prefs.getBoolean("findOption2", false)}, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { prefs.edit().putBoolean("findOption" + which, isChecked).commit(); } }) .setView(range) .setPositiveButton("Find", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (netServ != null && netServ.socket.isConnected()) { netServ.findingBattle = true; try { prefs.edit().putInt("range", Integer.valueOf(range.getText().toString())).commit(); } catch (NumberFormatException e) { prefs.edit().remove("range").commit(); } netServ.socket.sendMessage( constructFindBattle(prefs.getBoolean("findOption0", false), prefs.getBoolean("findOption1", false), prefs.getBoolean("findOption2", false), prefs.getInt("range", 200), (byte) 0), Command.FindBattle); } } }); return builder.create(); } case TierSelection: { if (netServ == null) { return null; } return new TierAlertDialog(this, netServ.superTier); } case PlayerInfo: { View layout = inflater.inflate(R.layout.player_info_dialog, (LinearLayout)findViewById(R.id.player_info_dialog)); ImageView[] pPokeIcons = new ImageView[6]; TextView pInfo, pName; ListView ratings; builder.setView(layout) .setNegativeButton("Back", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { removeDialog(id); } }) .setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog) { removeDialog(id); } }) .setPositiveButton("Challenge", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { showDialog(ChatDialog.ChallengeMode.ordinal()); removeDialog(id); }}); final AlertDialog pInfoDialog = builder.create(); for(int i = 0; i < 6; i++){ pPokeIcons[i] = (ImageView)layout.findViewById(getResources().getIdentifier("player_info_poke" + (i+1), "id", packName)); //pPokeIcons[i].setImageDrawable(getIcon(lastClickedPlayer.pokes[i])); } pInfo = (TextView)layout.findViewById(R.id.player_info); pInfo.setText(Html.fromHtml("<b>Info: </b>" + StringUtilities.escapeHtml(lastClickedPlayer.info()))); pName = (TextView)layout.findViewById(R.id.player_info_name); pName.setText(lastClickedPlayer.nick()); ratings = (ListView)layout.findViewById(R.id.player_info_tiers); ratings.setAdapter(new TwoViewsArrayAdapter<TierStanding>(this, android.R.layout.simple_list_item_2, android.R.id.text1, android.R.id.text2, lastClickedPlayer.tierStandings, PlayerInfo.tierGetter)); return pInfoDialog; } case ChallengeMode: { final Clauses[] clauses = Clauses.values(); final int numClauses = clauses.length; final String[] clauseNames = new String[numClauses]; final boolean[] checked = new boolean[numClauses]; for (int i=0; i < numClauses; i++) { clauseNames[i] = clauses[i].toString(); checked[i] = prefs.getBoolean("challengeOption" + i, false); } builder.setMultiChoiceItems(clauseNames, checked, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { prefs.edit().putBoolean("challengeOption" + which, isChecked).commit(); } }) .setPositiveButton("Challenge", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { int clauses = 0; for (int i = 0; i < numClauses; i++) clauses |= (prefs.getBoolean("challengeOption" + i, false) ? Clauses.values()[i].mask() : 0); if (netServ != null && netServ.socket != null && netServ.socket.isConnected()) netServ.socket.sendMessage(constructChallenge(ChallengeDesc.Sent.ordinal(), lastClickedPlayer.id, clauses, Mode.Singles.ordinal()), Command.ChallengeStuff); removeDialog(id); } }) .setNegativeButton("Back", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { removeDialog(id); } }) .setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog) { removeDialog(id); } }) .setTitle("Select clauses"); return builder.create(); } default: { return new Dialog(this); } } }
diff --git a/src-pos/com/openbravo/pos/ticket/FindTicketsRenderer.java b/src-pos/com/openbravo/pos/ticket/FindTicketsRenderer.java index ce26211..33d3732 100644 --- a/src-pos/com/openbravo/pos/ticket/FindTicketsRenderer.java +++ b/src-pos/com/openbravo/pos/ticket/FindTicketsRenderer.java @@ -1,47 +1,47 @@ // Openbravo POS is a point of sales application designed for touch screens. // Copyright (C) 2008 Openbravo, S.L. // http://sourceforge.net/projects/openbravopos // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth floor, Boston, MA 02110-1301 USA package com.openbravo.pos.ticket; import java.awt.Component; import javax.swing.DefaultListCellRenderer; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JList; /** * * @author Mikel Irurita */ public class FindTicketsRenderer extends DefaultListCellRenderer { private Icon icoticket; /** Creates a new instance of ProductRenderer */ public FindTicketsRenderer() { icoticket = new ImageIcon(getClass().getClassLoader().getResource("com/openbravo/images/mime.png")); } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, null, index, isSelected, cellHasFocus); - setText("<html><table>" + value.toString() +"</html></table>"); + setText("<html><table>" + value.toString() +"</table></html>"); setIcon(icoticket); return this; } }
true
true
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, null, index, isSelected, cellHasFocus); setText("<html><table>" + value.toString() +"</html></table>"); setIcon(icoticket); return this; }
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, null, index, isSelected, cellHasFocus); setText("<html><table>" + value.toString() +"</table></html>"); setIcon(icoticket); return this; }
diff --git a/xwiki-commons-core/xwiki-commons-environment/xwiki-commons-environment-standard/src/test/java/org/xwiki/environment/internal/StandardEnvironmentTest.java b/xwiki-commons-core/xwiki-commons-environment/xwiki-commons-environment-standard/src/test/java/org/xwiki/environment/internal/StandardEnvironmentTest.java index f567eb29a..09d588258 100644 --- a/xwiki-commons-core/xwiki-commons-environment/xwiki-commons-environment-standard/src/test/java/org/xwiki/environment/internal/StandardEnvironmentTest.java +++ b/xwiki-commons-core/xwiki-commons-environment/xwiki-commons-environment-standard/src/test/java/org/xwiki/environment/internal/StandardEnvironmentTest.java @@ -1,209 +1,209 @@ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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.xwiki.environment.internal; import java.io.File; import java.net.URL; import javax.inject.Provider; import org.apache.commons.io.FileUtils; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.integration.junit4.JMock; import org.junit.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.xwiki.component.embed.EmbeddableComponentManager; import org.xwiki.component.util.ReflectionUtils; import org.xwiki.environment.Environment; import org.xwiki.store.UnexpectedException; /** * Unit tests for {@link StandardEnvironment}. * * @version $Id$ * @since 3.5M1 */ @RunWith(JMock.class) public class StandardEnvironmentTest { private static final File TMPDIR = new File(System.getProperty("java.io.tmpdir"), "xwiki-temp"); private StandardEnvironment environment; private Mockery mockery = new JUnit4Mockery(); public Mockery getMockery() { return this.mockery; } @Before public void setUp() throws Exception { EmbeddableComponentManager ecm = new EmbeddableComponentManager(); ecm.initialize(getClass().getClassLoader()); this.environment = (StandardEnvironment) ecm.getInstance(Environment.class); ReflectionUtils.setFieldValue(this.environment, "isTesting", true); if (TMPDIR.exists()) { FileUtils.forceDelete(TMPDIR); } } @After public void tearDown() throws Exception { if (TMPDIR.exists()) { FileUtils.forceDelete(TMPDIR); } } @Test public void testGetResourceWhenResourceDirNotSet() { Assert.assertNull(this.environment.getResource("doesntexist")); } @Test public void testGetResourceOk() { // Make sure our resource really exists on the file system... // TODO: find a better way... File resourceFile = new File("target/testGetResourceOk"); resourceFile.mkdirs(); this.environment.setResourceDirectory(new File("target")); URL resource = this.environment.getResource("testGetResourceOk"); Assert.assertNotNull(resource); } @Test public void testGetResourceWhenResourceDirNotSetButResourceAvailableInDefaultClassLoader() { URL resource = this.environment.getResource("test"); Assert.assertNotNull(resource); } @Test public void testGetResourceWhenResourceDirSetButResourceAvailableInDefaultClassLoader() { this.environment.setResourceDirectory(new File("/resource")); URL resource = this.environment.getResource("test"); Assert.assertNotNull(resource); } @Test public void testGetPermanentDirectory() { File permanentDirectory = new File("/permanent"); this.environment.setPermanentDirectory(permanentDirectory); Assert.assertEquals(permanentDirectory, this.environment.getPermanentDirectory()); } @Test public void testGetPermanentDirectoryWhenNotSet() { // Also verify that we log a warning! final Logger logger = getMockery().mock(Logger.class); getMockery().checking(new Expectations() {{ oneOf(logger).warn("No permanent directory configured. Using a temporary directory [{}]", System.getProperty("java.io.tmpdir")); }}); ReflectionUtils.setFieldValue(this.environment, "logger", logger); Assert.assertEquals(new File(System.getProperty("java.io.tmpdir")), this.environment.getPermanentDirectory()); } @Test public void testGetTemporaryDirectory() { File tmpDir = new File("tmpdir"); this.environment.setTemporaryDirectory(tmpDir); Assert.assertEquals(tmpDir, this.environment.getTemporaryDirectory()); } @Test public void testGetTemporaryDirectoryWhenNotSet() { Assert.assertEquals(TMPDIR, this.environment.getTemporaryDirectory()); } @Test(expected = UnexpectedException.class) public void testGetTemporaryDirectoryWhenNotADirectory() throws Exception { FileUtils.write(TMPDIR, "test"); final String[] params = new String[] { "temporary", TMPDIR.getAbsolutePath(), "not a directory" }; final Logger logger = getMockery().mock(Logger.class); getMockery().checking(new Expectations() {{ oneOf(logger).error("Configured {} directory [{}] is {}.", params); }}); ReflectionUtils.setFieldValue(this.environment, "logger", logger); this.environment.getTemporaryDirectory(); } @Test public void testGetTemporaryDirectoryFailOver() throws Exception { FileUtils.forceMkdir(TMPDIR); final File txtFile = new File(TMPDIR, "test.txt"); FileUtils.write(txtFile, "test"); final Provider<EnvironmentConfiguration> prov = new Provider<EnvironmentConfiguration>() { public EnvironmentConfiguration get() { return new EnvironmentConfiguration() { public String getPermanentDirectoryPath() { return txtFile.getAbsolutePath(); } }; } }; ReflectionUtils.setFieldValue(this.environment, "configurationProvider", prov); final Logger logger = getMockery().mock(Logger.class); getMockery().checking(new Expectations() {{ allowing(logger).error(with(any(String.class)), with(any(String[].class))); // Getting the tmp dir causes the permenant dir to be checked. oneOf(logger).warn("Falling back on [{}] for {} directory.", - TMPDIR.getParentFile().getAbsolutePath(), + System.getProperty("java.io.tmpdir"), "permanent"); }}); ReflectionUtils.setFieldValue(this.environment, "logger", logger); Assert.assertEquals(TMPDIR, this.environment.getTemporaryDirectory()); // Check that the directory was cleared. Assert.assertEquals(0, TMPDIR.listFiles().length); } }
true
true
public void testGetTemporaryDirectoryFailOver() throws Exception { FileUtils.forceMkdir(TMPDIR); final File txtFile = new File(TMPDIR, "test.txt"); FileUtils.write(txtFile, "test"); final Provider<EnvironmentConfiguration> prov = new Provider<EnvironmentConfiguration>() { public EnvironmentConfiguration get() { return new EnvironmentConfiguration() { public String getPermanentDirectoryPath() { return txtFile.getAbsolutePath(); } }; } }; ReflectionUtils.setFieldValue(this.environment, "configurationProvider", prov); final Logger logger = getMockery().mock(Logger.class); getMockery().checking(new Expectations() {{ allowing(logger).error(with(any(String.class)), with(any(String[].class))); // Getting the tmp dir causes the permenant dir to be checked. oneOf(logger).warn("Falling back on [{}] for {} directory.", TMPDIR.getParentFile().getAbsolutePath(), "permanent"); }}); ReflectionUtils.setFieldValue(this.environment, "logger", logger); Assert.assertEquals(TMPDIR, this.environment.getTemporaryDirectory()); // Check that the directory was cleared. Assert.assertEquals(0, TMPDIR.listFiles().length); }
public void testGetTemporaryDirectoryFailOver() throws Exception { FileUtils.forceMkdir(TMPDIR); final File txtFile = new File(TMPDIR, "test.txt"); FileUtils.write(txtFile, "test"); final Provider<EnvironmentConfiguration> prov = new Provider<EnvironmentConfiguration>() { public EnvironmentConfiguration get() { return new EnvironmentConfiguration() { public String getPermanentDirectoryPath() { return txtFile.getAbsolutePath(); } }; } }; ReflectionUtils.setFieldValue(this.environment, "configurationProvider", prov); final Logger logger = getMockery().mock(Logger.class); getMockery().checking(new Expectations() {{ allowing(logger).error(with(any(String.class)), with(any(String[].class))); // Getting the tmp dir causes the permenant dir to be checked. oneOf(logger).warn("Falling back on [{}] for {} directory.", System.getProperty("java.io.tmpdir"), "permanent"); }}); ReflectionUtils.setFieldValue(this.environment, "logger", logger); Assert.assertEquals(TMPDIR, this.environment.getTemporaryDirectory()); // Check that the directory was cleared. Assert.assertEquals(0, TMPDIR.listFiles().length); }
diff --git a/XPathTestRunner/src/test/java/org/omg/bpmn/miwg/xpath/XPathTest.java b/XPathTestRunner/src/test/java/org/omg/bpmn/miwg/xpath/XPathTest.java index 4968adea..f3c5f6da 100644 --- a/XPathTestRunner/src/test/java/org/omg/bpmn/miwg/xpath/XPathTest.java +++ b/XPathTestRunner/src/test/java/org/omg/bpmn/miwg/xpath/XPathTest.java @@ -1,158 +1,158 @@ /** * The MIT License (MIT) * Copyright (c) 2013 OMG BPMN Model Interchange Working Group * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.omg.bpmn.miwg.xpath; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import org.omg.bpmn.miwg.xpathTestRunner.base.TestInfo; import org.omg.bpmn.miwg.xpathTestRunner.base.TestOutput; import org.omg.bpmn.miwg.xpathTestRunner.tests.B_1_0_Test; import org.omg.bpmn.miwg.xpathTestRunner.tests.B_2_0_Test; import org.omg.bpmn.miwg.xpathTestRunner.tests.ValidatorTest; /** * * @author Tim Stephenson * */ public class XPathTest { private static final String S = File.separator; private static final String RESOURCE_BASE_DIR = ".." + S + ".." + S + "bpmn-miwg-test-suite" + S; private static final String A_DIR = "A - Fixed Digrams with Variations of Attributes"; private static final String B_DIR = "B - Validate that tool covers conformance class set"; private static final String RPT_DIR = "target" + S + "surefire-reports"; private static File baseDir; private static File testADir; private static File testBDir; private static List<String> tools; @BeforeClass public static void setUp() throws Exception { baseDir = new File(RESOURCE_BASE_DIR); System.out.println("Looking for MIWG resources in: " + baseDir.getAbsolutePath()); testADir = new File(baseDir, A_DIR); assertTrue("Dir does not exist at " + testADir.getAbsolutePath() + ", please ensure you have checked out the MIWG resources.", testADir.exists()); testBDir = new File(baseDir, B_DIR); assertTrue("Dir does not exist at " + testBDir.getAbsolutePath() + ", please ensure you have checked out the MIWG resources.", testBDir.exists()); tools = new ArrayList<String>(); for (String dir : testADir.list()) { if (!dir.equals("Reference") && !dir.startsWith(".")) { tools.add(dir); } } new File(RPT_DIR).mkdirs(); } @Test public void testSchemaValid() { doTest(new ValidatorTest(), "B.1.0"); doTest(new ValidatorTest(), "B.2.0"); } @Test public void testB10() { doTest(new B_1_0_Test(), "B.1.0"); } @Test public void testB20() { doTest(new B_2_0_Test(), "B.2.0"); } private void doTest(org.omg.bpmn.miwg.xpathTestRunner.testBase.Test test, String baseFileName) { for (String tool : tools) { TestInfo info = new TestInfo(baseDir.getAbsolutePath() - + testBDir.getName(), tool, baseFileName + + testBDir.getName() + S, tool, baseFileName + "-roundtrip.bpmn"); TestOutput out = null; try { out = new TestOutput(test, info, RPT_DIR); out.println("Running Tests for " + test.getName() + ":"); int numOK = 0; int numIssue = 0; if (test.isApplicable(info.getFile().getName())) { out.println("> TEST " + test.getName()); try { test.init(out); test.execute(info.getFile().getAbsolutePath()); } catch (FileNotFoundException e) { // Most likely this is because this tool has not // provided a test file out.println(e.getMessage()); } catch (Exception e) { out.println("Exception during test execution of " + test.getName()); e.printStackTrace(); fail(e.getMessage()); } catch (Throwable e) { e.printStackTrace(); fail(e.getMessage()); } out.println(); out.println(" TEST " + test.getName() + " results:"); out.println(" * OK : " + test.ResultsOK()); out.println(" * ISSUES: " + test.ResultsIssue()); out.println(); numOK += test.ResultsOK(); numIssue += test.ResultsIssue(); } else { fail("File to test is not applicable: " + info.getFile().getName()); } } catch (IOException e) { fail(e.getMessage()); } finally { out.close(); } } } }
true
true
private void doTest(org.omg.bpmn.miwg.xpathTestRunner.testBase.Test test, String baseFileName) { for (String tool : tools) { TestInfo info = new TestInfo(baseDir.getAbsolutePath() + testBDir.getName(), tool, baseFileName + "-roundtrip.bpmn"); TestOutput out = null; try { out = new TestOutput(test, info, RPT_DIR); out.println("Running Tests for " + test.getName() + ":"); int numOK = 0; int numIssue = 0; if (test.isApplicable(info.getFile().getName())) { out.println("> TEST " + test.getName()); try { test.init(out); test.execute(info.getFile().getAbsolutePath()); } catch (FileNotFoundException e) { // Most likely this is because this tool has not // provided a test file out.println(e.getMessage()); } catch (Exception e) { out.println("Exception during test execution of " + test.getName()); e.printStackTrace(); fail(e.getMessage()); } catch (Throwable e) { e.printStackTrace(); fail(e.getMessage()); } out.println(); out.println(" TEST " + test.getName() + " results:"); out.println(" * OK : " + test.ResultsOK()); out.println(" * ISSUES: " + test.ResultsIssue()); out.println(); numOK += test.ResultsOK(); numIssue += test.ResultsIssue(); } else { fail("File to test is not applicable: " + info.getFile().getName()); } } catch (IOException e) { fail(e.getMessage()); } finally { out.close(); } } }
private void doTest(org.omg.bpmn.miwg.xpathTestRunner.testBase.Test test, String baseFileName) { for (String tool : tools) { TestInfo info = new TestInfo(baseDir.getAbsolutePath() + testBDir.getName() + S, tool, baseFileName + "-roundtrip.bpmn"); TestOutput out = null; try { out = new TestOutput(test, info, RPT_DIR); out.println("Running Tests for " + test.getName() + ":"); int numOK = 0; int numIssue = 0; if (test.isApplicable(info.getFile().getName())) { out.println("> TEST " + test.getName()); try { test.init(out); test.execute(info.getFile().getAbsolutePath()); } catch (FileNotFoundException e) { // Most likely this is because this tool has not // provided a test file out.println(e.getMessage()); } catch (Exception e) { out.println("Exception during test execution of " + test.getName()); e.printStackTrace(); fail(e.getMessage()); } catch (Throwable e) { e.printStackTrace(); fail(e.getMessage()); } out.println(); out.println(" TEST " + test.getName() + " results:"); out.println(" * OK : " + test.ResultsOK()); out.println(" * ISSUES: " + test.ResultsIssue()); out.println(); numOK += test.ResultsOK(); numIssue += test.ResultsIssue(); } else { fail("File to test is not applicable: " + info.getFile().getName()); } } catch (IOException e) { fail(e.getMessage()); } finally { out.close(); } } }
diff --git a/splat/src/main/uk/ac/starlink/splat/iface/SpecTransferHandler.java b/splat/src/main/uk/ac/starlink/splat/iface/SpecTransferHandler.java index f16e84c0a..e92ee8c5a 100644 --- a/splat/src/main/uk/ac/starlink/splat/iface/SpecTransferHandler.java +++ b/splat/src/main/uk/ac/starlink/splat/iface/SpecTransferHandler.java @@ -1,355 +1,355 @@ /* * Copyright (C) 2003 Central Laboratory of the Research Councils * * History: * 19-MAR-2003 (Peter W. Draper): * Original version. */ package uk.ac.starlink.splat.iface; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.net.URL; import javax.xml.transform.stream.StreamSource; import javax.swing.TransferHandler; import javax.swing.JComponent; import javax.swing.JList; import uk.ac.starlink.splat.data.NDXSpecDataImpl; import uk.ac.starlink.splat.data.SpecData; import uk.ac.starlink.splat.data.SpecDataFactory; import uk.ac.starlink.splat.plot.PlotControl; import uk.ac.starlink.splat.util.SplatException; import uk.ac.starlink.table.StarTable; import uk.ac.starlink.table.StarTableFactory; /** * A TransferHandler for dragging and dropping SpecData instances. * In SPLAT these are between any JLists showing the global list (i.e. * using a SpecListModel) and a PlotControl. Drop events outside of * SPLAT may be encodings of various types that need to be converted * into SpecData instances (Treeview is the primary source of these * and should be checked for the various types). * <p> * Notes that this all works between different JVMs as Transferables * containing serialized objects. * * @author Peter W. Draper * @version $Id$ */ public class SpecTransferHandler extends TransferHandler { /** * The global list of spectra and plots. */ protected GlobalSpecPlotList globalList = GlobalSpecPlotList.getInstance(); /** * Spectra factory */ protected SpecDataFactory specFactory = SpecDataFactory.getInstance(); /** * Table factory. */ protected StarTableFactory tableFactory = new StarTableFactory(); /** * Various flavors we can import, doesn't include the * tables. These are provided by the table factory. */ public static final DataFlavor flavors[] = { // Define a flavor for transfering spectra. new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=uk.ac.starlink.splat.iface.SpecTransferHandler", "Local SpecData" ), // Flavors we can accept from Treeview. new DataFlavor( "application/xml;class=java.io.InputStream", "NDX stream" ), new DataFlavor( DataFlavor.javaSerializedObjectMimeType + ";class=java.net.URL", "URL" ) /*XXX Don't want one of these yet. new DataFlavor( "application/fits;class=java.io.InputStream", "FITS stream" ),*/ }; public boolean canImport( JComponent comp, DataFlavor flavor[] ) { if ( checkImportComponent( comp ) ) { for ( int i = 0, n = flavor.length; i < n; i++ ) { for ( int j = 0, m = flavors.length; j < m; j++ ) { if ( flavor[i].equals( flavors[j] ) ) { return true; } } } } // Check tables. return tableFactory.canImport( flavor ); } protected boolean checkImportComponent( JComponent comp ) { if ( comp instanceof PlotControl ) { return true; } // The List can import too. return checkExportComponent( comp ); } protected boolean checkExportComponent( JComponent comp ) { // Valid signature is a JList backed by a SpecListModel. if ( comp instanceof JList ) { JList list = (JList) comp; if ( list.getModel() instanceof SpecListModel ) { return true; } } return false; } public int getSourceActions( JComponent c ) { return TransferHandler.COPY; } // At the start of a drag event take a copy of the SpecData // objects that are selected in the JList. These are then stored // in a SpecTransferable object which will be presented to any // targets. public Transferable createTransferable( JComponent comp ) { if ( checkExportComponent( comp ) ) { JList list = (JList) comp; final int[] indices = list.getSelectedIndices(); if ( indices.length > 0 ) { SpecListModel model = (SpecListModel) list.getModel(); ArrayList spectra = new ArrayList( indices.length ); for ( int i = 0; i < indices.length; i++ ) { spectra.add( model.getSpectrum( indices[i] ) ); } return new SpecTransferable( spectra, flavors ); } } return null; } // Drop event, if the target is a PlotControl object, then get it // to display any of the spectra that it is not already // displaying. If the Transferable is from a external application // with known mimetype then create a spectrum and display and add // it to the global list. public boolean importData( JComponent comp, Transferable t ) { if ( checkImportComponent( comp ) ) { DataFlavor[] importFlavors = t.getTransferDataFlavors(); // Tables first, there are more of these that look just // like URLS/FITS streams etc. XXXX Need to able to // distinguish these as some table classes are greedy and // will open any FITS file (with a table somewhere). if ( tableFactory.canImport( importFlavors ) ) { try { StarTable table = tableFactory.makeStarTable( t ); if ( table != null ) { return importTable( comp, table ); } } catch (Exception e) { // Do nothing. } } for ( int j = 0; j < importFlavors.length; j++ ) { if ( flavors[0].match( importFlavors[j] ) ) { return importSpecData( comp, t ); } if ( flavors[1].match( importFlavors[j] ) ) { return importNDXStream( comp, t ); } if ( flavors[2].match( importFlavors[j] ) ) { return importURL( comp, t ); } //if ( flavors[3].match( importFlavors[j] ) ) { // return importFITSStream( comp, t ); //} } } return false; } protected boolean importSpecData( JComponent comp, Transferable t ) { try { ArrayList spectra = (ArrayList) t.getTransferData( flavors[0] ); int added = 0; // Add any unknowns to the global list (needed in both // cases). These will be imports from other instances of // SPLAT! for ( int i = 0; i < spectra.size(); i++ ) { SpecData spec = (SpecData) spectra.get( i ); if ( globalList.getSpectrumIndex( spec ) == -1 ) { globalList.add( spec ); added++; } } // If importing to a PlotControl also arrange to display // any currently undisplayed spectra. if ( comp instanceof PlotControl ) { added = 0; PlotControl plot = (PlotControl) comp; for ( int i = 0; i < spectra.size(); i++ ) { SpecData spec = (SpecData) spectra.get( i ); if ( ! plot.isDisplayed( spec ) ) { try { globalList.addSpectrum( plot, spec ); added++; } catch (SplatException e) { - // Not a good time to do anything. + // Not a good time to do anything. Which is bad... e.printStackTrace(); } } } } return ( added > 0 ); } catch ( UnsupportedFlavorException ignored ) { ignored.printStackTrace(); } catch ( IOException ignored ) { ignored.printStackTrace(); } return false; } protected boolean importNDXStream( JComponent comp, Transferable t ) { boolean added = false; InputStream inputStream = null; try { inputStream = (InputStream) t.getTransferData( flavors[1] ); StreamSource streamSource = new StreamSource( inputStream ); NDXSpecDataImpl impl = new NDXSpecDataImpl( streamSource ); SpecData spectrum = new SpecData( impl ); displaySpectrum( comp, spectrum ); added = true; } catch (Exception e) { e.printStackTrace(); } try { inputStream.close(); } catch (Exception e) { // Do nothing. } return added; } protected boolean importFITSStream( JComponent comp, Transferable t ) { // NDX as FITS stream? System.out.println( "No Support for FITS streams" ); return false; } protected boolean importURL( JComponent comp, Transferable t ) { boolean added = false; try { URL url = (URL) t.getTransferData( flavors[2] ); NDXSpecDataImpl impl = new NDXSpecDataImpl( url ); SpecData spectrum = new SpecData( impl ); displaySpectrum( comp, spectrum ); added = true; } catch (Exception e) { e.printStackTrace(); } return added; } protected boolean importTable( JComponent comp, StarTable table ) { boolean added = false; try { SpecData spectrum = specFactory.get( table ); displaySpectrum( comp, spectrum ); added = true; } catch (Exception e) { e.printStackTrace(); } return added; } protected void displaySpectrum( JComponent comp, SpecData spectrum ) { globalList.add( spectrum ); if ( comp instanceof PlotControl ) { PlotControl plot = (PlotControl) comp; if ( ! plot.isDisplayed( spectrum ) ) { try { globalList.addSpectrum( plot, spectrum ); } catch (Exception e) { // Ignore. } } } } // Inner class that implements Transferable. This is the object // that stores the information generated when the drag event // happens (this stores the list of spectra to be transferred and // our flavor signature for SpecData). protected class SpecTransferable implements Transferable { protected ArrayList spectra; protected DataFlavor[] flavors; public SpecTransferable( ArrayList spectra, DataFlavor[] flavors ) { this.spectra = spectra; this.flavors = flavors; } public Object getTransferData( DataFlavor flavor) { if ( isDataFlavorSupported( flavor ) ) { return spectra; } return null; } public DataFlavor[] getTransferDataFlavors() { return flavors; } public boolean isDataFlavorSupported( DataFlavor flavor ) { // Note we only support SpecData internally. return flavor.equals( flavors[0] ); } } }
true
true
protected boolean importSpecData( JComponent comp, Transferable t ) { try { ArrayList spectra = (ArrayList) t.getTransferData( flavors[0] ); int added = 0; // Add any unknowns to the global list (needed in both // cases). These will be imports from other instances of // SPLAT! for ( int i = 0; i < spectra.size(); i++ ) { SpecData spec = (SpecData) spectra.get( i ); if ( globalList.getSpectrumIndex( spec ) == -1 ) { globalList.add( spec ); added++; } } // If importing to a PlotControl also arrange to display // any currently undisplayed spectra. if ( comp instanceof PlotControl ) { added = 0; PlotControl plot = (PlotControl) comp; for ( int i = 0; i < spectra.size(); i++ ) { SpecData spec = (SpecData) spectra.get( i ); if ( ! plot.isDisplayed( spec ) ) { try { globalList.addSpectrum( plot, spec ); added++; } catch (SplatException e) { // Not a good time to do anything. e.printStackTrace(); } } } } return ( added > 0 ); } catch ( UnsupportedFlavorException ignored ) { ignored.printStackTrace(); } catch ( IOException ignored ) { ignored.printStackTrace(); } return false; }
protected boolean importSpecData( JComponent comp, Transferable t ) { try { ArrayList spectra = (ArrayList) t.getTransferData( flavors[0] ); int added = 0; // Add any unknowns to the global list (needed in both // cases). These will be imports from other instances of // SPLAT! for ( int i = 0; i < spectra.size(); i++ ) { SpecData spec = (SpecData) spectra.get( i ); if ( globalList.getSpectrumIndex( spec ) == -1 ) { globalList.add( spec ); added++; } } // If importing to a PlotControl also arrange to display // any currently undisplayed spectra. if ( comp instanceof PlotControl ) { added = 0; PlotControl plot = (PlotControl) comp; for ( int i = 0; i < spectra.size(); i++ ) { SpecData spec = (SpecData) spectra.get( i ); if ( ! plot.isDisplayed( spec ) ) { try { globalList.addSpectrum( plot, spec ); added++; } catch (SplatException e) { // Not a good time to do anything. Which is bad... e.printStackTrace(); } } } } return ( added > 0 ); } catch ( UnsupportedFlavorException ignored ) { ignored.printStackTrace(); } catch ( IOException ignored ) { ignored.printStackTrace(); } return false; }
diff --git a/src/main/java/me/iffa/bananaspace/wgen/populators/SpaceAsteroidPopulator.java b/src/main/java/me/iffa/bananaspace/wgen/populators/SpaceAsteroidPopulator.java index 78f84f1..aca4375 100644 --- a/src/main/java/me/iffa/bananaspace/wgen/populators/SpaceAsteroidPopulator.java +++ b/src/main/java/me/iffa/bananaspace/wgen/populators/SpaceAsteroidPopulator.java @@ -1,69 +1,69 @@ // Package Declaration package me.iffa.bananaspace.wgen.populators; // Java Imports import java.util.Random; // BananaSpace Imports import me.iffa.bananaspace.api.SpaceConfigHandler; // Bukkit Imports import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.generator.BlockPopulator; /** * SpaceAsteroidPopulator * * @author Markus 'Notch' Persson * @author iffa * @author Nightgunner5 */ public class SpaceAsteroidPopulator extends BlockPopulator { // Variables private static final BlockFace[] faces = {BlockFace.DOWN, BlockFace.EAST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.UP, BlockFace.WEST}; /** * Populates a world with asteroids. * * @param world World * @param random Random * @param source Source chunk */ @Override public void populate(World world, Random random, Chunk source) { for (int i = 0; i < 2; i++) { int x = random.nextInt(16); int y = random.nextInt(128); int z = random.nextInt(16); Block block = source.getBlock(x, y, z); if (block.getTypeId() != 0) { return; } - if (random.nextInt(200) <= SpaceConfigHandler.getAsteroidChance(world)) { + if (random.nextInt(200) <= SpaceConfigHandler.getStoneChance(world)) { block.setTypeId(1); for (int j = 0; j < 1500; j++) { Block current = block.getRelative(random.nextInt(8) - random.nextInt(8), random.nextInt(12), random.nextInt(8) - random.nextInt(8)); if (current.getTypeId() != 0) { continue; } int count = 0; for (BlockFace face : faces) { if (current.getRelative(face).getTypeId() == 1) { count++; } } if (count == 1) { current.setTypeId(1); } } } } } }
true
true
public void populate(World world, Random random, Chunk source) { for (int i = 0; i < 2; i++) { int x = random.nextInt(16); int y = random.nextInt(128); int z = random.nextInt(16); Block block = source.getBlock(x, y, z); if (block.getTypeId() != 0) { return; } if (random.nextInt(200) <= SpaceConfigHandler.getAsteroidChance(world)) { block.setTypeId(1); for (int j = 0; j < 1500; j++) { Block current = block.getRelative(random.nextInt(8) - random.nextInt(8), random.nextInt(12), random.nextInt(8) - random.nextInt(8)); if (current.getTypeId() != 0) { continue; } int count = 0; for (BlockFace face : faces) { if (current.getRelative(face).getTypeId() == 1) { count++; } } if (count == 1) { current.setTypeId(1); } } } } }
public void populate(World world, Random random, Chunk source) { for (int i = 0; i < 2; i++) { int x = random.nextInt(16); int y = random.nextInt(128); int z = random.nextInt(16); Block block = source.getBlock(x, y, z); if (block.getTypeId() != 0) { return; } if (random.nextInt(200) <= SpaceConfigHandler.getStoneChance(world)) { block.setTypeId(1); for (int j = 0; j < 1500; j++) { Block current = block.getRelative(random.nextInt(8) - random.nextInt(8), random.nextInt(12), random.nextInt(8) - random.nextInt(8)); if (current.getTypeId() != 0) { continue; } int count = 0; for (BlockFace face : faces) { if (current.getRelative(face).getTypeId() == 1) { count++; } } if (count == 1) { current.setTypeId(1); } } } } }
diff --git a/LWALLPAPER/src/com/kaist/crescendowallpaper/MyAvata3.java b/LWALLPAPER/src/com/kaist/crescendowallpaper/MyAvata3.java index c47d53c..afc623c 100644 --- a/LWALLPAPER/src/com/kaist/crescendowallpaper/MyAvata3.java +++ b/LWALLPAPER/src/com/kaist/crescendowallpaper/MyAvata3.java @@ -1,488 +1,488 @@ package com.kaist.crescendowallpaper; import java.io.File; import java.util.ArrayList; import java.util.Random; import android.app.WallpaperManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.util.Log; import android.view.MotionEvent; public class MyAvata3 { private static final int MAX_COUNT = 60; private static final int MIN_COUNT = 10; private static final int BODY_SX = 150; private static final int BODY_SY = 170; private static final int HEAD_SY = 110; private static final int HEAD_SX = 120; private static final int HEAD_SXOFFSET = (BODY_SX - HEAD_SY) / 2; private static final int INDICATOR_SY = 20; private static final int WORDBALLON_WIDTH = 150; private static final int MAX_LINENUMBER = 10; private final int MODE_STAY = 0; private final int MODE_WALK = 1; private final int MODE_MIN = MODE_STAY; private final int MODE_MAX = MODE_WALK; private static final Random rand = new Random(); private static final long DOUBLE_TAP_INTV = 600; private static final int MODE_STAY_COUNT = 600; public int startX, startY; // ���� ��ǥ private int countX; private int countY; private int directX = 1; private int directY = 1; private int STAY_COUNT = 0; private int headIndex = 0; private int bodyIndex = 0; private ArrayList<Bitmap> headImgs = new ArrayList<Bitmap>(); private ArrayList<Bitmap> stayBodyImgs = new ArrayList<Bitmap>(); private ArrayList<Bitmap> walkBodyImgs = new ArrayList<Bitmap>(); private boolean isStickyMode; private int waitToStickyMode; private long lastTapEventTime; private boolean isNeedDrawDirecty; private Context mContext; private boolean isShowBalloon = true; private Paint paint; private ArrayList<String> words = new ArrayList<String>(); private int lineHeight; private int movingMode = MODE_WALK; private Rect rect = new Rect(); private long fpsStartTime; private int frameCnt; private float timeElapsed; public static final String AVATA_FILNENAME = "myAvata.png"; public MyAvata3(Context context, Context appContext, int type, String name, boolean isMe, int progress) { startX = rand.nextInt(StarWallpaper.Width - BODY_SX); startY = rand.nextInt(StarWallpaper.Height - (HEAD_SY + BODY_SY)); // headImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), // R.drawable.man_shop), HEAD_SX, HEAD_SY, true)); // headImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), // R.drawable.man_shop_press), HEAD_SX, HEAD_SY, true)); appContext.getFileStreamPath(AVATA_FILNENAME); File file; if (isMe) file = appContext.getFileStreamPath(AVATA_FILNENAME); else file = appContext.getFileStreamPath(AVATA_FILNENAME); if (file.exists() == false || isMe == false) headImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.man_shop), HEAD_SX, HEAD_SY, true)); else { Bitmap bit = BitmapFactory.decodeFile(file.getPath().toString()); if (bit == null) headImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.man_shop), HEAD_SX, HEAD_SY, true)); else headImgs.add(Bitmap.createScaledBitmap(bit, HEAD_SX, HEAD_SY, true)); } if (isMe == true) { if (progress < 50) { stayBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.stay_fat1), BODY_SX, BODY_SY, true)); stayBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.stay_fat2), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.walk_fat1), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.walk_fat2), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.walk_fat3), BODY_SX, BODY_SY, true)); } else { stayBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1), BODY_SX, BODY_SY, true)); stayBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( - context.getResources(), R.drawable.stay_thin1), BODY_SX, BODY_SY, + context.getResources(), R.drawable.stay_thin2), BODY_SX, BODY_SY, true)); walkBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin1), BODY_SX, BODY_SY, true)); walkBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin2), BODY_SX, BODY_SY, true)); walkBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin3), BODY_SX, BODY_SY, true)); } } else { if (progress < 50) { stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_fat1_friend), BODY_SX, BODY_SY, true)); stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_fat2_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_fat1_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_fat2_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_fat3_friend), BODY_SX, BODY_SY, true)); } else { stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1_friend), BODY_SX, BODY_SY, true)); stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin1_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin2_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin3_friend), BODY_SX, BODY_SY, true)); } } mContext = context; paint = new Paint(); // paint.setColor(Color.YELLOW); paint.setStyle(Style.FILL); paint.setTextSize(30); /* * test TODO remove this code. */ setText(name); fpsStartTime = System.currentTimeMillis(); } public void moveBySelf() { if (isNeedDrawDirecty) { isNeedDrawDirecty = false; return; } if (countX == 0) { countX = rand.nextInt(MAX_COUNT - MIN_COUNT) + MIN_COUNT; directX = rand.nextBoolean() == true ? 1 : -1; headIndex++; bodyIndex++; } if (countY == 0) { countY = rand.nextInt(MAX_COUNT - MIN_COUNT) + MIN_COUNT; directY = rand.nextBoolean() == true ? 1 : -1; headIndex++; bodyIndex++; } if (startX < 0 || startX > StarWallpaper.Width - BODY_SX) /* * it's * dangerous, * don't cross * the line */ { directX *= -1; countX = MAX_COUNT; /* I'll give you the POWER to escape */ } if (startY < INDICATOR_SY || startY > StarWallpaper.Height - (HEAD_SY + BODY_SY + 20)) { directY *= -1; countY = MAX_COUNT; } countX--; countY--; if (movingMode == MODE_WALK) { startX += directX; startY += directY; } else if (movingMode == MODE_STAY) { } STAY_COUNT++; if (STAY_COUNT > MODE_STAY_COUNT) { STAY_COUNT = rand.nextInt(MODE_STAY_COUNT - 10) + 10; ; movingMode++; } } private Bitmap getHeadBitmap() { if (headIndex >= headImgs.size()) headIndex = 0; return headImgs.get(headIndex); } private Bitmap getBodyBitmap() { if (movingMode > MODE_MAX) movingMode = MODE_MIN; if (movingMode == MODE_STAY) { if (bodyIndex >= stayBodyImgs.size()) bodyIndex = 0; return stayBodyImgs.get(bodyIndex); } else if (movingMode == MODE_WALK) { if (bodyIndex >= walkBodyImgs.size()) bodyIndex = 0; return walkBodyImgs.get(bodyIndex); } return null; } public void setPosition(int x, int y) { startX = x; startY = y; isNeedDrawDirecty = true; } private void setText(String text) { breakText(paint, text, WORDBALLON_WIDTH); Rect bounds = new Rect(); if (words.size() > 1 && words.get(0) != null) { paint.getTextBounds(words.get(0), 0, words.get(0).length(), bounds); lineHeight = bounds.height() + 5; } } public void draw(Canvas canvas) { canvas.drawBitmap(getBodyBitmap(), startX, startY + HEAD_SY, null); long fpsEndTime = System.currentTimeMillis(); float timeDelta = (fpsEndTime - fpsStartTime) * 0.001f; // Frame ���� ���� frameCnt++; timeElapsed += timeDelta; // FPS�� ���ؼ� �α׷� ǥ�� if (timeElapsed >= 1.0f) { float fps = (float)(frameCnt / timeElapsed); Log.d("fps", "fps : " + fps); frameCnt = 0; timeElapsed = 0.0f; } // Frame ���� �ð� �ٽ� ���� fpsStartTime = System.currentTimeMillis(); if (isShowBalloon) { rect.set(startX + HEAD_SXOFFSET + HEAD_SX, startY + HEAD_SY - 10 - lineHeight, startX + HEAD_SXOFFSET + HEAD_SX + WORDBALLON_WIDTH + 3, startY + HEAD_SY + lineHeight * words.size() - 10); // canvas.drawRoundRect(rect, 1, 1, paint); paint.setColor(Color.YELLOW); paint.setStyle(Style.FILL); canvas.drawRect(rect, paint); // canvas.drawPaint(paint); paint.setColor(Color.BLACK); for (int i = 0; i < words.size(); i++) { canvas.drawText(words.get(i), startX + HEAD_SXOFFSET + HEAD_SX + 5, startY + HEAD_SY + (i * lineHeight) - 7, paint); } } canvas.drawBitmap(getHeadBitmap(), startX + HEAD_SXOFFSET, startY + 80 /* overlap */, null); } public boolean onTouch(MotionEvent event) { // TODO Auto-generated method stub // v.dispatchTouchEvent(event); // v. // head.dispatchTouchEvent(event); // Log.d("MyTag", "onTouch : " + event.getAction()+" x= "+ // event.getX()+"y= "+ event.getY()); if (event.getAction() == MotionEvent.ACTION_MOVE) /* * to catch drag * gesture */ { if (isStickyMode == true || waitToStickyMode > 0) { isStickyMode = true; setPosition((int)event.getX() - 80, (int)event.getY() - 120); return true; } else { isStickyMode = false; return false; } } if (isMyPosition(event)) /* I want to know the event */ { if (event.getAction() == MotionEvent.ACTION_DOWN) waitToStickyMode = 1; else waitToStickyMode = 0; return true; } else { waitToStickyMode = 0; isStickyMode = false; } return false; } private boolean isMyPosition(MotionEvent event) { int x = (int)event.getX(); int y = (int)event.getY(); if (x > startX && x < startX + BODY_SX) if (y > startY && y < startY + HEAD_SY + BODY_SY) return true; return false; } private boolean isMyPosition(int x, int y) { if (x > startX && x < startX + BODY_SX) if (y > startY && y < startY + HEAD_SY + BODY_SY) return true; return false; } private void wowDoubleTap() { // Intent intent = new Intent(); // intent.setAction("android.intent.action.callcrescendo"); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | // Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); // // mContext.startActivity(intent ); Intent intent = mContext.getPackageManager().getLaunchIntentForPackage( "com.kaist.crescendo"); intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); mContext.startActivity(intent); } /* to get the user's double tap event */ public boolean onCommand(String action, int x, int y, int z, long tapTime) { if (action.equals(WallpaperManager.COMMAND_TAP.toString()) && isMyPosition(x, y)) { isStickyMode = false; if (tapTime - lastTapEventTime < DOUBLE_TAP_INTV) wowDoubleTap(); lastTapEventTime = tapTime; } return false; } /** * �ٹٲ� * * @param textPaint TextView�� Paint ��ü * @param strText ���ڿ� * @param breakWidth �ٹٲ� �ϰ� ���� width�� ���� * @return */ public int breakText(Paint textPaint, String strText, int breakWidth) { // StringBuilder sb = new StringBuilder(); int endValue = 0; int totalLine = 0; do { endValue = textPaint.breakText(strText, true, breakWidth, null); if (endValue > 0) { words.add(strText.substring(0, endValue)); // sb.append(strText.substring(0, endValue)).append("\n"); strText = strText.substring(endValue); } totalLine++; } while (endValue > 0 && totalLine < MAX_LINENUMBER); // sb.toString().substring(0, sb.length()-1); // ������ "\n"�� ���� return totalLine; } }
true
true
public MyAvata3(Context context, Context appContext, int type, String name, boolean isMe, int progress) { startX = rand.nextInt(StarWallpaper.Width - BODY_SX); startY = rand.nextInt(StarWallpaper.Height - (HEAD_SY + BODY_SY)); // headImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), // R.drawable.man_shop), HEAD_SX, HEAD_SY, true)); // headImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), // R.drawable.man_shop_press), HEAD_SX, HEAD_SY, true)); appContext.getFileStreamPath(AVATA_FILNENAME); File file; if (isMe) file = appContext.getFileStreamPath(AVATA_FILNENAME); else file = appContext.getFileStreamPath(AVATA_FILNENAME); if (file.exists() == false || isMe == false) headImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.man_shop), HEAD_SX, HEAD_SY, true)); else { Bitmap bit = BitmapFactory.decodeFile(file.getPath().toString()); if (bit == null) headImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.man_shop), HEAD_SX, HEAD_SY, true)); else headImgs.add(Bitmap.createScaledBitmap(bit, HEAD_SX, HEAD_SY, true)); } if (isMe == true) { if (progress < 50) { stayBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.stay_fat1), BODY_SX, BODY_SY, true)); stayBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.stay_fat2), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.walk_fat1), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.walk_fat2), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.walk_fat3), BODY_SX, BODY_SY, true)); } else { stayBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1), BODY_SX, BODY_SY, true)); stayBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1), BODY_SX, BODY_SY, true)); walkBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin1), BODY_SX, BODY_SY, true)); walkBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin2), BODY_SX, BODY_SY, true)); walkBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin3), BODY_SX, BODY_SY, true)); } } else { if (progress < 50) { stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_fat1_friend), BODY_SX, BODY_SY, true)); stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_fat2_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_fat1_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_fat2_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_fat3_friend), BODY_SX, BODY_SY, true)); } else { stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1_friend), BODY_SX, BODY_SY, true)); stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin1_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin2_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin3_friend), BODY_SX, BODY_SY, true)); } } mContext = context; paint = new Paint(); // paint.setColor(Color.YELLOW); paint.setStyle(Style.FILL); paint.setTextSize(30); /* * test TODO remove this code. */ setText(name); fpsStartTime = System.currentTimeMillis(); }
public MyAvata3(Context context, Context appContext, int type, String name, boolean isMe, int progress) { startX = rand.nextInt(StarWallpaper.Width - BODY_SX); startY = rand.nextInt(StarWallpaper.Height - (HEAD_SY + BODY_SY)); // headImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), // R.drawable.man_shop), HEAD_SX, HEAD_SY, true)); // headImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), // R.drawable.man_shop_press), HEAD_SX, HEAD_SY, true)); appContext.getFileStreamPath(AVATA_FILNENAME); File file; if (isMe) file = appContext.getFileStreamPath(AVATA_FILNENAME); else file = appContext.getFileStreamPath(AVATA_FILNENAME); if (file.exists() == false || isMe == false) headImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.man_shop), HEAD_SX, HEAD_SY, true)); else { Bitmap bit = BitmapFactory.decodeFile(file.getPath().toString()); if (bit == null) headImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.man_shop), HEAD_SX, HEAD_SY, true)); else headImgs.add(Bitmap.createScaledBitmap(bit, HEAD_SX, HEAD_SY, true)); } if (isMe == true) { if (progress < 50) { stayBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.stay_fat1), BODY_SX, BODY_SY, true)); stayBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.stay_fat2), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.walk_fat1), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.walk_fat2), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap( BitmapFactory.decodeResource(context.getResources(), R.drawable.walk_fat3), BODY_SX, BODY_SY, true)); } else { stayBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1), BODY_SX, BODY_SY, true)); stayBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin2), BODY_SX, BODY_SY, true)); walkBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin1), BODY_SX, BODY_SY, true)); walkBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin2), BODY_SX, BODY_SY, true)); walkBodyImgs .add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin3), BODY_SX, BODY_SY, true)); } } else { if (progress < 50) { stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_fat1_friend), BODY_SX, BODY_SY, true)); stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_fat2_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_fat1_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_fat2_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_fat3_friend), BODY_SX, BODY_SY, true)); } else { stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1_friend), BODY_SX, BODY_SY, true)); stayBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.stay_thin1_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin1_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin2_friend), BODY_SX, BODY_SY, true)); walkBodyImgs.add(Bitmap.createScaledBitmap(BitmapFactory.decodeResource( context.getResources(), R.drawable.walk_thin3_friend), BODY_SX, BODY_SY, true)); } } mContext = context; paint = new Paint(); // paint.setColor(Color.YELLOW); paint.setStyle(Style.FILL); paint.setTextSize(30); /* * test TODO remove this code. */ setText(name); fpsStartTime = System.currentTimeMillis(); }
diff --git a/collatex/src/main/java/eu/interedition/collatex/dekker/TranspositionDetector.java b/collatex/src/main/java/eu/interedition/collatex/dekker/TranspositionDetector.java index cf632d5d..001edc07 100644 --- a/collatex/src/main/java/eu/interedition/collatex/dekker/TranspositionDetector.java +++ b/collatex/src/main/java/eu/interedition/collatex/dekker/TranspositionDetector.java @@ -1,73 +1,73 @@ /** * CollateX - a Java library for collating textual sources, for example, to * produce an apparatus. * * Copyright (C) 2010-2012 ESF COST Action "Interedition". * * 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 eu.interedition.collatex.dekker; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import eu.interedition.collatex.graph.VariantGraph; import eu.interedition.collatex.graph.VariantGraphVertex; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TranspositionDetector { private static final Logger LOG = LoggerFactory.getLogger(TranspositionDetector.class); public List<List<Match>> detect(List<List<Match>> phraseMatches, VariantGraph base) { //rank the variant graph base.rank(); // gather matched ranks into a list ordered by their natural order final List<Integer> ranks = Lists.newArrayList(); for (List<Match> phraseMatch : phraseMatches) { ranks.add(phraseMatch.get(0).vertex.getRank()); } Collections.sort(ranks); // detect transpositions final List<List<Match>> transpositions = Lists.newArrayList(); int previousRank = 0; - Tuple previous = new Tuple(0, 0); + Tuple<Integer> previous = new Tuple<Integer>(0, 0); for (List<Match> phraseMatch : phraseMatches) { VariantGraphVertex baseToken = phraseMatch.get(0).vertex; int rank = baseToken.getRank(); int expectedRank = ranks.get(previousRank); - Tuple current = new Tuple(expectedRank, rank); + Tuple<Integer> current = new Tuple<Integer>(expectedRank, rank); if (expectedRank != rank && !isMirrored(previous, current)) { transpositions.add(phraseMatch); } previousRank ++; previous = current; } if (LOG.isTraceEnabled()) { for (List<Match> transposition : transpositions) { LOG.trace("Detected transposition: {}", Iterables.toString(transposition)); } } return transpositions; } private boolean isMirrored(Tuple previousTuple, Tuple tuple) { return previousTuple.left.equals(tuple.right) && previousTuple.right.equals(tuple.left); } }
false
true
public List<List<Match>> detect(List<List<Match>> phraseMatches, VariantGraph base) { //rank the variant graph base.rank(); // gather matched ranks into a list ordered by their natural order final List<Integer> ranks = Lists.newArrayList(); for (List<Match> phraseMatch : phraseMatches) { ranks.add(phraseMatch.get(0).vertex.getRank()); } Collections.sort(ranks); // detect transpositions final List<List<Match>> transpositions = Lists.newArrayList(); int previousRank = 0; Tuple previous = new Tuple(0, 0); for (List<Match> phraseMatch : phraseMatches) { VariantGraphVertex baseToken = phraseMatch.get(0).vertex; int rank = baseToken.getRank(); int expectedRank = ranks.get(previousRank); Tuple current = new Tuple(expectedRank, rank); if (expectedRank != rank && !isMirrored(previous, current)) { transpositions.add(phraseMatch); } previousRank ++; previous = current; } if (LOG.isTraceEnabled()) { for (List<Match> transposition : transpositions) { LOG.trace("Detected transposition: {}", Iterables.toString(transposition)); } } return transpositions; }
public List<List<Match>> detect(List<List<Match>> phraseMatches, VariantGraph base) { //rank the variant graph base.rank(); // gather matched ranks into a list ordered by their natural order final List<Integer> ranks = Lists.newArrayList(); for (List<Match> phraseMatch : phraseMatches) { ranks.add(phraseMatch.get(0).vertex.getRank()); } Collections.sort(ranks); // detect transpositions final List<List<Match>> transpositions = Lists.newArrayList(); int previousRank = 0; Tuple<Integer> previous = new Tuple<Integer>(0, 0); for (List<Match> phraseMatch : phraseMatches) { VariantGraphVertex baseToken = phraseMatch.get(0).vertex; int rank = baseToken.getRank(); int expectedRank = ranks.get(previousRank); Tuple<Integer> current = new Tuple<Integer>(expectedRank, rank); if (expectedRank != rank && !isMirrored(previous, current)) { transpositions.add(phraseMatch); } previousRank ++; previous = current; } if (LOG.isTraceEnabled()) { for (List<Match> transposition : transpositions) { LOG.trace("Detected transposition: {}", Iterables.toString(transposition)); } } return transpositions; }
diff --git a/components/bio-formats/src/loci/formats/in/FV1000Reader.java b/components/bio-formats/src/loci/formats/in/FV1000Reader.java index 64a1839f1..3d85db7c1 100644 --- a/components/bio-formats/src/loci/formats/in/FV1000Reader.java +++ b/components/bio-formats/src/loci/formats/in/FV1000Reader.java @@ -1,1431 +1,1441 @@ // // FV1000Reader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import loci.common.ByteArrayHandle; import loci.common.DataTools; import loci.common.DateTools; import loci.common.IniList; import loci.common.IniParser; import loci.common.IniTable; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.services.POIService; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.TiffParser; import ome.xml.model.primitives.PositiveInteger; /** * FV1000Reader is the file format reader for Fluoview FV 1000 OIB and * Fluoview FV 1000 OIF files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/FV1000Reader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/FV1000Reader.java">SVN</a></dd></dl> * * @author Melissa Linkert melissa at glencoesoftware.com */ public class FV1000Reader extends FormatReader { // -- Constants -- public static final String FV1000_MAGIC_STRING_1 = "FileInformation"; public static final String FV1000_MAGIC_STRING_2 = "Acquisition Parameters"; public static final String[] OIB_SUFFIX = {"oib"}; public static final String[] OIF_SUFFIX = {"oif"}; public static final String[] FV1000_SUFFIXES = {"oib", "oif"}; public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final int NUM_DIMENSIONS = 9; /** ROI types. */ private static final int POINT = 2; private static final int LINE = 3; private static final int POLYLINE = 4; private static final int RECTANGLE = 5; private static final int CIRCLE = 6; private static final int ELLIPSE = 7; private static final int POLYGON = 8; private static final int FREE_SHAPE = 9; private static final int FREE_LINE = 10; private static final int GRID = 11; private static final int ARROW = 12; private static final int COLOR_BAR = 13; private static final int SCALE = 15; private static final String ROTATION = "rotate(%d %f %f)"; // -- Fields -- private IniParser parser = new IniParser(); /** Names of every TIFF file to open. */ private Vector<String> tiffs; /** Name of thumbnail file. */ private String thumbId; /** Helper reader for thumbnail. */ private BMPReader thumbReader; /** Used file list. */ private Vector<String> usedFiles; /** Flag indicating this is an OIB dataset. */ private boolean isOIB; /** File mappings for OIB file. */ private Hashtable<String, String> oibMapping; private String[] code, size; private Double[] pixelSize; private int imageDepth; private Vector<String> previewNames; private String pixelSizeX, pixelSizeY; private Vector<String> illuminations; private Vector<Integer> wavelengths; private String pinholeSize; private String magnification, lensNA, objectiveName, workingDistance; private String creationDate; private Vector<ChannelData> channels; private Vector<String> lutNames = new Vector<String>(); private Hashtable<Integer, String> filenames = new Hashtable<Integer, String>(); private Hashtable<Integer, String> roiFilenames = new Hashtable<Integer, String>(); private POIService poi; private short[][][] lut; private int lastChannel; private double pixelSizeZ = 1, pixelSizeT = 1; private String ptyStart = null, ptyEnd = null, ptyPattern = null, line = null; // -- Constructor -- /** Constructs a new FV1000 reader. */ public FV1000Reader() { super("Olympus FV1000", new String[] {"oib", "oif", "pty", "lut"}); domains = new String[] {FormatTools.LM_DOMAIN}; hasCompanionFiles = true; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return checkSuffix(id, OIB_SUFFIX); } /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { if (checkSuffix(name, FV1000_SUFFIXES)) return true; if (!open) return false; // not allowed to touch the file system try { Location oif = new Location(findOIFFile(name)); return oif.exists() && !oif.isDirectory() && checkSuffix(oif.getAbsolutePath(), "oif"); } catch (IndexOutOfBoundsException e) { } catch (NullPointerException e) { } catch (FormatException e) { } return false; } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 1024; if (!FormatTools.validStream(stream, blockLen, false)) return false; String s = DataTools.stripString(stream.readString(blockLen)); return s.indexOf(FV1000_MAGIC_STRING_1) >= 0 || s.indexOf(FV1000_MAGIC_STRING_2) >= 0; } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { String name = id.toLowerCase(); if (checkSuffix(name, FV1000_SUFFIXES)) { return FormatTools.CANNOT_GROUP; } return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() { FormatTools.assertId(currentId, true, 1); return lut == null ? null : lut[lastChannel]; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); int file = no; int image = 0; String filename = null; if (series == 0) { file = no / (getImageCount() / tiffs.size()); image = no % (getImageCount() / tiffs.size()); if (file < tiffs.size()) filename = tiffs.get(file); } else { file = no / (getImageCount() / previewNames.size()); image = no % (getImageCount() / previewNames.size()); if (file < previewNames.size()) { filename = previewNames.get(file); } } int[] coords = getZCTCoords(image); lastChannel = coords[1]; if (filename == null) return buf; RandomAccessInputStream plane = getFile(filename); TiffParser tp = new TiffParser(plane); IFDList ifds = tp.getIFDs(); if (image >= ifds.size()) return buf; IFD ifd = ifds.get(image); if (getSizeY() != ifd.getImageLength()) { tp.getSamples(ifd, buf, x, getIndex(coords[0], 0, coords[2]), w, 1); } else tp.getSamples(ifd, buf, x, y, w, h); plane.close(); plane = null; return buf; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (isOIB) { return noPixels ? null : new String[] {currentId}; } Vector<String> files = new Vector<String>(); if (usedFiles != null) { for (String file : usedFiles) { String f = file.toLowerCase(); if (!f.endsWith(".tif") && !f.endsWith(".tiff") && !f.endsWith(".bmp")) { files.add(file); } } } if (!noPixels) { if (getSeries() == 0 && tiffs != null) { files.addAll(tiffs); } else if (getSeries() == 1 && previewNames != null) { files.addAll(previewNames); } } return files.toArray(new String[0]); } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (thumbReader != null) thumbReader.close(fileOnly); if (!fileOnly) { tiffs = usedFiles = null; filenames = new Hashtable<Integer, String>(); roiFilenames = new Hashtable<Integer, String>(); thumbReader = null; thumbId = null; isOIB = false; previewNames = null; if (poi != null) poi.close(); poi = null; lastChannel = 0; wavelengths = null; illuminations = null; oibMapping = null; code = size = null; pixelSize = null; imageDepth = 0; pixelSizeX = pixelSizeY = null; pinholeSize = null; magnification = lensNA = objectiveName = workingDistance = null; creationDate = null; lut = null; channels = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); parser.setCommentDelimiter(null); isOIB = checkSuffix(id, OIB_SUFFIX); if (isOIB) { try { ServiceFactory factory = new ServiceFactory(); poi = factory.getInstance(POIService.class); } catch (DependencyException de) { throw new FormatException("POI library not found", de); } poi.initialize(Location.getMappedId(id)); } // mappedOIF is used to distinguish between datasets that are being read // directly (e.g. using ImageJ or showinf), and datasets that are being // imported through omebf. In the latter case, the necessary directory // structure is not preserved (only relative file names are stored in // OMEIS), so we will need to use slightly different logic to build the // list of associated files. boolean mappedOIF = !isOIB && !new File(id).getAbsoluteFile().exists(); wavelengths = new Vector<Integer>(); illuminations = new Vector<String>(); channels = new Vector<ChannelData>(); String oifName = null; if (isOIB) { oifName = mapOIBFiles(); } else { // make sure we have the OIF file, not a TIFF if (!checkSuffix(id, OIF_SUFFIX)) { currentId = findOIFFile(id); initFile(currentId); } oifName = currentId; } String oifPath = new Location(oifName).getAbsoluteFile().getAbsolutePath(); String path = (isOIB || !oifPath.endsWith(oifName) || mappedOIF) ? "" : oifPath.substring(0, oifPath.lastIndexOf(File.separator) + 1); try { getFile(oifName); } catch (IOException e) { oifName = oifName.replaceAll(".oif", ".OIF"); } // parse key/value pairs from the OIF file code = new String[NUM_DIMENSIONS]; size = new String[NUM_DIMENSIONS]; pixelSize = new Double[NUM_DIMENSIONS]; previewNames = new Vector<String>(); boolean laserEnabled = true; IniList f = getIniFile(oifName); IniTable saveInfo = f.getTable("ProfileSaveInfo"); String[] saveKeys = saveInfo.keySet().toArray(new String[saveInfo.size()]); for (String key : saveKeys) { String value = saveInfo.get(key).toString(); value = sanitizeValue(value).trim(); if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } filenames.put(new Integer(key.substring(11)), value); } else if (key.startsWith("RoiFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } try { roiFilenames.put(new Integer(key.substring(11)), value); } catch (NumberFormatException e) { } } else if (key.equals("PtyFileNameS")) ptyStart = value; else if (key.equals("PtyFileNameE")) ptyEnd = value; else if (key.equals("PtyFileNameT2")) ptyPattern = value; else if (key.indexOf("Thumb") != -1) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } if (thumbId == null) thumbId = value.trim(); } else if (key.startsWith("LutFileName")) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } lutNames.add(path + value); } else if (isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } previewNames.add(path + value.trim()); } } if (filenames.size() == 0) addPtyFiles(); for (int i=0; i<NUM_DIMENSIONS; i++) { IniTable commonParams = f.getTable("Axis " + i + " Parameters Common"); code[i] = commonParams.get("AxisCode"); size[i] = commonParams.get("MaxSize"); double end = Double.parseDouble(commonParams.get("EndPosition")); double start = Double.parseDouble(commonParams.get("StartPosition")); pixelSize[i] = end - start; } IniTable referenceParams = f.getTable("Reference Image Parameter"); imageDepth = Integer.parseInt(referenceParams.get("ImageDepth")); pixelSizeX = referenceParams.get("WidthConvertValue"); pixelSizeY = referenceParams.get("HeightConvertValue"); int index = 0; IniTable laser = f.getTable("Laser " + index + " Parameters"); while (laser != null) { laserEnabled = laser.get("Laser Enable").equals("1"); if (laserEnabled) { wavelengths.add(new Integer(laser.get("LaserWavelength"))); } creationDate = laser.get("ImageCaputreDate"); if (creationDate == null) { creationDate = laser.get("ImageCaptureDate"); } index++; laser = f.getTable("Laser " + index + " Parameters"); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { index = 1; IniTable guiChannel = f.getTable("GUI Channel " + index + " Parameters"); while (guiChannel != null) { ChannelData channel = new ChannelData(); channel.gain = new Double(guiChannel.get("AnalogPMTGain")); channel.voltage = new Double(guiChannel.get("AnalogPMTVoltage")); channel.barrierFilter = guiChannel.get("BF Name"); channel.active = Integer.parseInt(guiChannel.get("CH Activate")) != 0; channel.name = guiChannel.get("CH Name"); channel.dyeName = guiChannel.get("DyeName"); channel.emissionFilter = guiChannel.get("EmissionDM Name"); channel.emWave = new Integer(guiChannel.get("EmissionWavelength")); channel.excitationFilter = guiChannel.get("ExcitationDM Name"); channel.exWave = new Integer(guiChannel.get("ExcitationWavelength")); channels.add(channel); index++; guiChannel = f.getTable("GUI Channel " + index + " Parameters"); } index = 1; IniTable channel = f.getTable("Channel " + index + " Parameters"); while (channel != null) { String illumination = channel.get("LightType"); if (illumination != null) illumination = illumination.toLowerCase(); if (illumination == null) { // Ignored } else if (illumination.indexOf("fluorescence") != -1) { illumination = "Epifluorescence"; } else if (illumination.indexOf("transmitted") != -1) { illumination = "Transmitted"; } else illumination = null; illuminations.add(illumination); index++; channel = f.getTable("Channel " + index + " Parameters"); } for (IniTable table : f) { String tableName = table.get(IniTable.HEADER_KEY); String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { addGlobalMeta(tableName + " " + key, table.get(key)); } } } LOGGER.info("Initializing helper readers"); // populate core metadata for preview series if (previewNames.size() > 0) { Vector<String> v = new Vector<String>(); for (int i=0; i<previewNames.size(); i++) { String ss = previewNames.get(i); ss = replaceExtension(ss, "pty", "tif"); if (ss.endsWith(".tif")) v.add(ss); } previewNames = v; if (previewNames.size() > 0) { core = new CoreMetadata[2]; core[0] = new CoreMetadata(); core[1] = new CoreMetadata(); IFDList ifds = null; for (String previewName : previewNames) { RandomAccessInputStream preview = getFile(previewName); TiffParser tp = new TiffParser(preview); ifds = tp.getIFDs(); preview.close(); core[1].imageCount += ifds.size(); } core[1].sizeX = (int) ifds.get(0).getImageWidth(); core[1].sizeY = (int) ifds.get(0).getImageLength(); core[1].sizeZ = 1; core[1].sizeT = 1; core[1].sizeC = core[1].imageCount; core[1].rgb = false; int bits = ifds.get(0).getBitsPerSample()[0]; while ((bits % 8) != 0) bits++; bits /= 8; core[1].pixelType = FormatTools.pixelTypeFromBytes(bits, false, false); core[1].dimensionOrder = "XYCZT"; core[1].indexed = false; } } core[0].imageCount = filenames.size(); tiffs = new Vector<String>(getImageCount()); thumbReader = new BMPReader(); thumbId = replaceExtension(thumbId, "pty", "bmp"); thumbId = sanitizeFile(thumbId, path); LOGGER.info("Reading additional metadata"); // open each INI file (.pty extension) and build list of TIFF files String tiffPath = null; core[0].dimensionOrder = "XY"; for (int i=0, ii=0; ii<getImageCount(); i++, ii++) { String file = filenames.get(new Integer(i)); while (file == null) file = filenames.get(new Integer(++i)); file = sanitizeFile(file, path); if (file.indexOf(File.separator) != -1) { tiffPath = file.substring(0, file.lastIndexOf(File.separator)); } else tiffPath = file; Location ptyFile = new Location(file); if (!isOIB && !ptyFile.exists()) { LOGGER.warn("Could not find .pty file ({}); guessing at the " + "corresponding TIFF file.", file); String tiff = replaceExtension(file, ".pty", ".tif"); tiffs.add(ii, tiff); continue; } IniList pty = getIniFile(file); IniTable fileInfo = pty.getTable("File Info"); file = sanitizeValue(fileInfo.get("DataName")); if (!isPreviewName(file)) { while (file.indexOf("GST") != -1) { file = removeGST(file); } if (!mappedOIF) { if (isOIB) { file = tiffPath + File.separator + file; } else file = new Location(tiffPath, file).getAbsolutePath(); } tiffs.add(ii, file); } for (int dim=0; dim<NUM_DIMENSIONS; dim++) { IniTable axis = pty.getTable("Axis " + dim + " Parameters"); if (axis == null) break; boolean addAxis = Integer.parseInt(axis.get("Number")) > 1; if (dim == 2) { if (addAxis && getDimensionOrder().indexOf("C") == -1) { core[0].dimensionOrder += "C"; } } else if (dim == 3) { if (addAxis && getDimensionOrder().indexOf("Z") == -1) { core[0].dimensionOrder += "Z"; } } else if (dim == 4) { if (addAxis && getDimensionOrder().indexOf("T") == -1) { core[0].dimensionOrder += "T"; } } } IniTable acquisition = pty.getTable("Acquisition Parameters Common"); if (acquisition != null) { magnification = acquisition.get("Magnification"); lensNA = acquisition.get("ObjectiveLens NAValue"); objectiveName = acquisition.get("ObjectiveLens Name"); workingDistance = acquisition.get("ObjectiveLens WDValue"); pinholeSize = acquisition.get("PinholeDiameter"); String validBitCounts = acquisition.get("ValidBitCounts"); if (validBitCounts != null) { core[0].bitsPerPixel = Integer.parseInt(validBitCounts); } } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { for (IniTable table : pty) { String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { addGlobalMeta("Image " + ii + " : " + key, table.get(key)); } } } } if (tiffs.size() != getImageCount()) { core[0].imageCount = tiffs.size(); } usedFiles = new Vector<String>(); if (tiffPath != null) { usedFiles.add(id); if (!isOIB) { Location dir = new Location(tiffPath); if (!dir.exists()) { throw new FormatException( "Required directory " + tiffPath + " was not found."); } String[] list = mappedOIF ? Location.getIdMap().keySet().toArray(new String[0]) : dir.list(); for (int i=0; i<list.length; i++) { if (mappedOIF) usedFiles.add(list[i]); else { String p = new Location(tiffPath, list[i]).getAbsolutePath(); String check = p.toLowerCase(); if (!check.endsWith(".tif") && !check.endsWith(".pty") && !check.endsWith(".roi") && !check.endsWith(".lut") && !check.endsWith(".bmp")) { continue; } usedFiles.add(p); } } } } LOGGER.info("Populating metadata"); // calculate axis sizes int realChannels = 0; for (int i=0; i<NUM_DIMENSIONS; i++) { int ss = Integer.parseInt(size[i]); if (pixelSize[i] == null) pixelSize[i] = 1.0; if (code[i].equals("X")) core[0].sizeX = ss; - else if (code[i].equals("Y")) core[0].sizeY = ss; + else if (code[i].equals("Y") && ss > 1) core[0].sizeY = ss; else if (code[i].equals("Z")) { - core[0].sizeZ = ss; - // Z size stored in nm - pixelSizeZ = - Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000); + if (getSizeY() == 0) { + core[0].sizeY = ss; + } + else { + core[0].sizeZ = ss; + // Z size stored in nm + pixelSizeZ = + Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000); + } } else if (code[i].equals("T")) { - core[0].sizeT = ss; - pixelSizeT = - Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000); + if (getSizeY() == 0) { + core[0].sizeY = ss; + } + else { + core[0].sizeT = ss; + pixelSizeT = + Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000); + } } else if (ss > 0) { if (getSizeC() == 0) core[0].sizeC = ss; else core[0].sizeC *= ss; if (code[i].equals("C")) realChannels = ss; } } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeC() == 0) core[0].sizeC = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (getImageCount() == getSizeC() && getSizeY() == 1) { core[0].imageCount *= getSizeZ() * getSizeT(); } else if (getImageCount() == getSizeC()) { core[0].sizeZ = 1; core[0].sizeT = 1; } if (getSizeZ() * getSizeT() * getSizeC() != getImageCount()) { int diff = (getSizeZ() * getSizeC() * getSizeT()) - getImageCount(); if (diff == previewNames.size() || diff < 0) { diff /= getSizeC(); if (getSizeT() > 1 && getSizeZ() == 1) core[0].sizeT -= diff; else if (getSizeZ() > 1 && getSizeT() == 1) core[0].sizeZ -= diff; } else core[0].imageCount += diff; } if (getSizeC() > 1 && getSizeZ() == 1 && getSizeT() == 1) { if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) core[0].dimensionOrder += "Z"; if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; if (getDimensionOrder().indexOf("T") == -1) core[0].dimensionOrder += "T"; core[0].pixelType = FormatTools.pixelTypeFromBytes(imageDepth, false, false); // set up thumbnail file mapping try { RandomAccessInputStream thumb = getFile(thumbId); byte[] b = new byte[(int) thumb.length()]; thumb.read(b); thumb.close(); Location.mapFile("thumbnail.bmp", new ByteArrayHandle(b)); thumbReader.setId("thumbnail.bmp"); for (int i=0; i<getSeriesCount(); i++) { core[i].thumbSizeX = thumbReader.getSizeX(); core[i].thumbSizeY = thumbReader.getSizeY(); } Location.mapFile("thumbnail.bmp", null); } catch (IOException e) { LOGGER.debug("Could not read thumbnail", e); } catch (FormatException e) { LOGGER.debug("Could not read thumbnail", e); } // initialize lookup table lut = new short[getSizeC()][3][65536]; byte[] buffer = new byte[65536 * 4]; int count = (int) Math.min(getSizeC(), lutNames.size()); for (int c=0; c<count; c++) { Exception exc = null; try { RandomAccessInputStream stream = getFile(lutNames.get(c)); stream.seek(stream.length() - 65536 * 4); stream.read(buffer); stream.close(); for (int q=0; q<buffer.length; q+=4) { lut[c][0][q / 4] = buffer[q + 1]; lut[c][1][q / 4] = buffer[q + 2]; lut[c][2][q / 4] = buffer[q + 3]; } } catch (IOException e) { exc = e; } catch (FormatException e) { exc = e; } if (exc != null) { LOGGER.debug("Could not read LUT", exc); lut = null; break; } } for (int i=0; i<getSeriesCount(); i++) { core[i].rgb = false; core[i].littleEndian = true; core[i].interleaved = false; core[i].metadataComplete = true; core[i].indexed = false; core[i].falseColor = false; } // populate MetadataStore MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (creationDate != null) { creationDate = creationDate.replaceAll("'", ""); creationDate = DateTools.formatDate(creationDate, DATE_FORMAT); } for (int i=0; i<getSeriesCount(); i++) { // populate Image data store.setImageName("Series " + (i + 1), i); if (creationDate != null) store.setImageAcquiredDate(creationDate, i); else MetadataTools.setDefaultCreationDate(store, id, i); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { populateMetadataStore(store, path); } } private void populateMetadataStore(MetadataStore store, String path) throws FormatException, IOException { String instrumentID = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrumentID, 0); for (int i=0; i<getSeriesCount(); i++) { // link Instrument and Image store.setImageInstrumentRef(instrumentID, i); // populate Dimensions data if (pixelSizeX != null) { store.setPixelsPhysicalSizeX(new Double(pixelSizeX), i); } if (pixelSizeY != null) { store.setPixelsPhysicalSizeY(new Double(pixelSizeY), i); } if (pixelSizeZ == Double.NEGATIVE_INFINITY || pixelSizeZ == Double.POSITIVE_INFINITY || getSizeZ() == 1) { pixelSizeZ = 0d; } if (pixelSizeT == Double.NEGATIVE_INFINITY || pixelSizeT == Double.POSITIVE_INFINITY || getSizeT() == 1) { pixelSizeT = 0d; } store.setPixelsPhysicalSizeZ(pixelSizeZ, i); store.setPixelsTimeIncrement(pixelSizeT, i); // populate LogicalChannel data for (int c=0; c<core[i].sizeC; c++) { if (c < illuminations.size()) { store.setChannelIlluminationType( getIlluminationType(illuminations.get(c)), i, c); } } } int channelIndex = 0; for (ChannelData channel : channels) { if (!channel.active) continue; if (channelIndex >= getEffectiveSizeC()) break; // populate Detector data String detectorID = MetadataTools.createLSID("Detector", 0, channelIndex); store.setDetectorID(detectorID, 0, channelIndex); store.setDetectorSettingsID(detectorID, 0, channelIndex); store.setDetectorGain(channel.gain, 0, channelIndex); store.setDetectorVoltage(channel.voltage, 0, channelIndex); store.setDetectorType(getDetectorType("PMT"), 0, channelIndex); // populate LogicalChannel data store.setChannelName(channel.name, 0, channelIndex); String lightSourceID = MetadataTools.createLSID("LightSource", 0, channelIndex); store.setChannelLightSourceSettingsID(lightSourceID, 0, channelIndex); if (channel.emWave.intValue() > 0) { store.setChannelEmissionWavelength( new PositiveInteger(channel.emWave), 0, channelIndex); } if (channel.exWave.intValue() > 0) { store.setChannelExcitationWavelength( new PositiveInteger(channel.exWave), 0, channelIndex); store.setChannelLightSourceSettingsWavelength( new PositiveInteger(channel.exWave), 0, channelIndex); } // populate Filter data if (channel.barrierFilter != null) { String filterID = MetadataTools.createLSID("Filter", 0, channelIndex); store.setFilterID(filterID, 0, channelIndex); store.setFilterModel(channel.barrierFilter, 0, channelIndex); if (channel.barrierFilter.indexOf("-") != -1) { String[] emValues = channel.barrierFilter.split("-"); for (int i=0; i<emValues.length; i++) { emValues[i] = emValues[i].replaceAll("\\D", ""); } try { store.setTransmittanceRangeCutIn( new Integer(emValues[0]), 0, channelIndex); store.setTransmittanceRangeCutOut( new Integer(emValues[1]), 0, channelIndex); } catch (NumberFormatException e) { } } store.setLightPathEmissionFilterRef(filterID, 0, channelIndex, 0); } // populate FilterSet data int emIndex = channelIndex * 2; int exIndex = channelIndex * 2 + 1; String emFilter = MetadataTools.createLSID("Dichroic", 0, emIndex); String exFilter = MetadataTools.createLSID("Dichroic", 0, exIndex); // populate Dichroic data store.setDichroicID(emFilter, 0, emIndex); store.setDichroicModel(channel.emissionFilter, 0, emIndex); store.setDichroicID(exFilter, 0, exIndex); store.setDichroicModel(channel.excitationFilter, 0, exIndex); store.setLightPathDichroicRef(exFilter, 0, channelIndex); // populate Laser data store.setLaserID(lightSourceID, 0, channelIndex); store.setLaserLaserMedium(getLaserMedium(channel.dyeName), 0, channelIndex); if (channelIndex < wavelengths.size()) { store.setLaserWavelength( new PositiveInteger(wavelengths.get(channelIndex)), 0, channelIndex); } store.setLaserType(getLaserType("Other"), 0, channelIndex); channelIndex++; } // populate Objective data if (lensNA != null) store.setObjectiveLensNA(new Double(lensNA), 0, 0); store.setObjectiveModel(objectiveName, 0, 0); if (magnification != null) { int mag = (int) Float.parseFloat(magnification); store.setObjectiveNominalMagnification(mag, 0, 0); } if (workingDistance != null) { store.setObjectiveWorkingDistance(new Double(workingDistance), 0, 0); } store.setObjectiveCorrection(getCorrection("Other"), 0, 0); store.setObjectiveImmersion(getImmersion("Other"), 0, 0); // link Objective to Image using ObjectiveSettings String objectiveID = MetadataTools.createLSID("Objective", 0, 0); store.setObjectiveID(objectiveID, 0, 0); store.setImageObjectiveSettingsID(objectiveID, 0); int nextROI = -1; // populate ROI data - there is one ROI file per plane for (int i=0; i<roiFilenames.size(); i++) { if (i >= getImageCount()) break; String filename = roiFilenames.get(new Integer(i)); filename = sanitizeFile(filename, path); nextROI = parseROIFile(filename, store, nextROI, i); } } private int parseROIFile(String filename, MetadataStore store, int nextROI, int plane) throws FormatException, IOException { int[] coordinates = getZCTCoords(plane); IniList roiFile = null; try { roiFile = getIniFile(filename); } catch (FormatException e) { LOGGER.debug("Could not parse ROI file {}", filename, e); return nextROI; } boolean validROI = false; int shape = -1; int shapeType = -1; String[] xc = null, yc = null; int divide = 0; int fontSize = 0, lineWidth = 0, angle = 0; String fontName = null, name = null; for (IniTable table : roiFile) { String tableName = table.get(IniTable.HEADER_KEY); if (tableName.equals("ROIBase FileInformation")) { try { String roiName = table.get("Name").replaceAll("\"", ""); validROI = Integer.parseInt(roiName) > 1; } catch (NumberFormatException e) { validROI = false; } if (!validROI) continue; } else if (tableName.equals("ROIBase Body")) { shapeType = Integer.parseInt(table.get("SHAPE")); divide = Integer.parseInt(table.get("DIVIDE")); String[] fontAttributes = table.get("FONT").split(","); fontName = fontAttributes[0]; fontSize = Integer.parseInt(fontAttributes[1]); lineWidth = Integer.parseInt(table.get("LINEWIDTH")); name = table.get("NAME"); angle = Integer.parseInt(table.get("ANGLE")); xc = table.get("X").split(","); yc = table.get("Y").split(","); int x = Integer.parseInt(xc[0]); int width = xc.length > 1 ? Integer.parseInt(xc[1]) - x : 0; int y = Integer.parseInt(yc[0]); int height = yc.length > 1 ? Integer.parseInt(yc[1]) - y : 0; if (width + x <= getSizeX() && height + y <= getSizeY()) { shape++; Integer zIndex = new Integer(coordinates[0]); Integer tIndex = new Integer(coordinates[2]); if (shape == 0) { nextROI++; } if (shapeType == POINT) { store.setPointTheZ(zIndex, nextROI, shape); store.setPointTheT(tIndex, nextROI, shape); store.setPointFontSize(fontSize, nextROI, shape); store.setPointStrokeWidth(new Double(lineWidth), nextROI, shape); store.setPointX(new Double(xc[0]), nextROI, shape); store.setPointY(new Double(yc[0]), nextROI, shape); } else if (shapeType == GRID || shapeType == RECTANGLE) { if (shapeType == RECTANGLE) divide = 1; width /= divide; height /= divide; for (int row=0; row<divide; row++) { for (int col=0; col<divide; col++) { double realX = x + col * width; double realY = y + row * height; store.setRectangleX(realX, nextROI, shape); store.setRectangleY(realY, nextROI, shape); store.setRectangleWidth(new Double(width), nextROI, shape); store.setRectangleHeight(new Double(height), nextROI, shape); store.setRectangleTheZ(zIndex, nextROI, shape); store.setRectangleTheT(tIndex, nextROI, shape); store.setRectangleFontSize(fontSize, nextROI, shape); store.setRectangleStrokeWidth( new Double(lineWidth), nextROI, shape); double centerX = realX + (width / 2); double centerY = realY + (height / 2); store.setRectangleTransform(String.format(ROTATION, angle, centerX, centerY), nextROI, shape); if (row < divide - 1 || col < divide - 1) shape++; } } } else if (shapeType == LINE) { store.setLineX1(new Double(x), nextROI, shape); store.setLineY1(new Double(y), nextROI, shape); store.setLineX2(new Double(x + width), nextROI, shape); store.setLineY2(new Double(y + height), nextROI, shape); store.setLineTheZ(zIndex, nextROI, shape); store.setLineTheT(tIndex, nextROI, shape); store.setLineFontSize(fontSize, nextROI, shape); store.setLineStrokeWidth(new Double(lineWidth), nextROI, shape); int centerX = x + (width / 2); int centerY = y + (height / 2); store.setLineTransform(String.format(ROTATION, angle, (float) centerX, (float) centerY), nextROI, shape); } else if (shapeType == CIRCLE || shapeType == ELLIPSE) { double rx = width / 2; double ry = shapeType == CIRCLE ? rx : height / 2; store.setEllipseX(x + rx, nextROI, shape); store.setEllipseY(y + ry, nextROI, shape); store.setEllipseRadiusX(rx, nextROI, shape); store.setEllipseRadiusY(ry, nextROI, shape); store.setEllipseTheZ(zIndex, nextROI, shape); store.setEllipseTheT(tIndex, nextROI, shape); store.setEllipseFontSize(fontSize, nextROI, shape); store.setEllipseStrokeWidth(new Double(lineWidth), nextROI, shape); store.setEllipseTransform(String.format(ROTATION, angle, x + rx, y + ry), nextROI, shape); } else if (shapeType == POLYGON || shapeType == FREE_SHAPE || shapeType == POLYLINE || shapeType == FREE_LINE) { StringBuffer points = new StringBuffer(); for (int point=0; point<xc.length; point++) { points.append(xc[point]); points.append(","); points.append(yc[point]); if (point < xc.length - 1) points.append(" "); } store.setPolylinePoints(points.toString(), nextROI, shape); store.setPolylineTransform("rotate(" + angle + ")", nextROI, shape); store.setPolylineClosed( shapeType == POLYGON || shapeType == FREE_SHAPE, nextROI, shape); store.setPolylineTheZ(zIndex, nextROI, shape); store.setPolylineTheT(tIndex, nextROI, shape); store.setPolylineFontSize(fontSize, nextROI, shape); store.setPolylineStrokeWidth(new Double(lineWidth), nextROI, shape); } else { if (shape == 0) nextROI--; shape--; } } } } return nextROI; } private void addPtyFiles() throws FormatException { if (ptyStart != null && ptyEnd != null && ptyPattern != null) { // FV1000 version 2 gives the first .pty file, the last .pty and // the file name pattern. Version 1 lists each .pty file individually. // pattern is typically 's_C%03dT%03d.pty' // build list of block indexes String[] prefixes = ptyPattern.split("%03d"); // get first and last numbers for each block int[] first = scanFormat(ptyPattern, ptyStart); int[] last = scanFormat(ptyPattern, ptyEnd); int[] lengths = new int[prefixes.length - 1]; int totalFiles = 1; for (int i=0; i<first.length; i++) { lengths[i] = last[i] - first[i] + 1; totalFiles *= lengths[i]; } // add each .pty file for (int file=0; file<totalFiles; file++) { int[] pos = FormatTools.rasterToPosition(lengths, file); StringBuffer pty = new StringBuffer(); for (int block=0; block<prefixes.length; block++) { pty.append(prefixes[block]); if (block < pos.length) { String num = String.valueOf(pos[block] + 1); for (int q=0; q<3 - num.length(); q++) { pty.append("0"); } pty.append(num); } } filenames.put(new Integer(file), pty.toString()); } } } // -- Helper methods -- private String findOIFFile(String baseFile) throws FormatException { Location current = new Location(baseFile).getAbsoluteFile(); String parent = current.getParent(); Location tmp = new Location(parent).getParentFile(); parent = tmp.getAbsolutePath(); baseFile = current.getName(); if (baseFile == null || baseFile.indexOf("_") == -1) return null; baseFile = baseFile.substring(0, baseFile.lastIndexOf("_")); if (checkSuffix(current.getName(), "roi")) { // ROI files have an extra underscore baseFile = baseFile.substring(0, baseFile.lastIndexOf("_")); } baseFile += ".oif"; tmp = new Location(tmp, baseFile); String oifFile = tmp.getAbsolutePath(); if (!tmp.exists()) { oifFile = oifFile.substring(0, oifFile.lastIndexOf(".")) + ".OIF"; tmp = new Location(oifFile); if (!tmp.exists()) { // check in parent directory if (parent.endsWith(File.separator)) { parent = parent.substring(0, parent.length() - 1); } String dir = parent.substring(parent.lastIndexOf(File.separator)); dir = dir.substring(0, dir.lastIndexOf(".")); tmp = new Location(parent); oifFile = new Location(tmp, dir).getAbsolutePath(); if (!new Location(oifFile).exists()) { throw new FormatException("OIF file not found"); } } } return oifFile; } private String mapOIBFiles() throws FormatException, IOException { String oifName = null; String infoFile = null; Vector<String> list = poi.getDocumentList(); for (String name : list) { if (name.endsWith("OibInfo.txt")) { infoFile = name; break; } } if (infoFile == null) { throw new FormatException("OibInfo.txt not found in " + currentId); } RandomAccessInputStream ras = poi.getDocumentStream(infoFile); oibMapping = new Hashtable<String, String>(); // set up file name mappings String s = DataTools.stripString(ras.readString((int) ras.length())); ras.close(); String[] lines = s.split("\n"); // sort the lines to ensure that the // directory key is before the file names Arrays.sort(lines); String directoryKey = null, directoryValue = null, key = null, value = null; for (String line : lines) { line = line.trim(); if (line.indexOf("=") != -1) { key = line.substring(0, line.indexOf("=")); value = line.substring(line.indexOf("=") + 1); if (directoryKey != null && directoryValue != null) { value = value.replaceAll(directoryKey, directoryValue); } value = removeGST(value); if (key.startsWith("Stream")) { value = sanitizeFile(value, ""); if (checkSuffix(value, OIF_SUFFIX)) oifName = value; if (directoryKey != null && value.startsWith(directoryValue)) { oibMapping.put(value, "Root Entry" + File.separator + directoryKey + File.separator + key); } else { oibMapping.put(value, "Root Entry" + File.separator + key); } } else if (key.startsWith("Storage")) { directoryKey = key; directoryValue = value; } } } s = null; return oifName; } private String sanitizeValue(String value) { String f = value.replaceAll("\"", ""); f = f.replace('\\', File.separatorChar); f = f.replace('/', File.separatorChar); while (f.indexOf("GST") != -1) { f = removeGST(f); } return f; } private String sanitizeFile(String file, String path) { String f = sanitizeValue(file); if (path.equals("")) return f; return path + File.separator + f; } private String removeGST(String s) { if (s.indexOf("GST") != -1) { String first = s.substring(0, s.indexOf("GST")); int ndx = s.indexOf(File.separator) < s.indexOf("GST") ? s.length() : s.indexOf(File.separator); String last = s.substring(s.lastIndexOf("=", ndx) + 1); return first + last; } return s; } private RandomAccessInputStream getFile(String name) throws FormatException, IOException { if (isOIB) { name = name.replace('\\', File.separatorChar); name = name.replace('/', File.separatorChar); String realName = oibMapping.get(name); if (realName == null) { throw new FormatException("File " + name + " not found."); } return poi.getDocumentStream(realName); } else return new RandomAccessInputStream(name); } private boolean isPreviewName(String name) { // "-R" in the file name indicates that this is a preview image int index = name.indexOf("-R"); return index == name.length() - 9; } private String replaceExtension(String name, String oldExt, String newExt) { if (!name.endsWith("." + oldExt)) { return name; } return name.substring(0, name.length() - oldExt.length()) + newExt; } /* Return the numbers in the given string matching %..d style patterns */ private static int[] scanFormat(String pattern, String string) throws FormatException { Vector<Integer> percentOffsets = new Vector<Integer>(); int offset = -1; for (;;) { offset = pattern.indexOf('%', offset + 1); if (offset < 0 || offset + 1 >= pattern.length()) { break; } if (pattern.charAt(offset + 1) == '%') { continue; } percentOffsets.add(new Integer(offset)); } int[] result = new int[percentOffsets.size()]; int patternOffset = 0; offset = 0; for (int i=0; i<result.length; i++) { int percent = percentOffsets.get(i).intValue(); if (!string.regionMatches(offset, pattern, patternOffset, percent - patternOffset)) { throw new FormatException("String '" + string + "' does not match format '" + pattern + "'"); } offset += percent - patternOffset; patternOffset = percent; int endOffset = offset; while (endOffset < string.length() && Character.isDigit(string.charAt(endOffset))) { endOffset++; } result[i] = Integer.parseInt(string.substring(offset, endOffset)); offset = endOffset; while (++patternOffset < pattern.length() && pattern.charAt(patternOffset - 1) != 'd') { ; /* do nothing */ } } int remaining = pattern.length() - patternOffset; if (string.length() - offset != remaining || !string.regionMatches(offset, pattern, patternOffset, remaining)) { throw new FormatException("String '" + string + "' does not match format '" + pattern + "'"); } return result; } private IniList getIniFile(String filename) throws FormatException, IOException { RandomAccessInputStream stream = getFile(filename); stream.skipBytes(2); String data = stream.readString((int) stream.length() - 2); data = DataTools.stripString(data); BufferedReader reader = new BufferedReader(new StringReader(data)); stream.close(); IniList list = parser.parseINI(reader); // most of the values will be wrapped in double quotes for (IniTable table : list) { String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { table.put(key, sanitizeValue(table.get(key))); } } return list; } // -- Helper classes -- class ChannelData { public boolean active; public Double gain; public Double voltage; public String name; public String emissionFilter; public String excitationFilter; public Integer emWave; public Integer exWave; public String dyeName; public String barrierFilter; } }
false
true
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); parser.setCommentDelimiter(null); isOIB = checkSuffix(id, OIB_SUFFIX); if (isOIB) { try { ServiceFactory factory = new ServiceFactory(); poi = factory.getInstance(POIService.class); } catch (DependencyException de) { throw new FormatException("POI library not found", de); } poi.initialize(Location.getMappedId(id)); } // mappedOIF is used to distinguish between datasets that are being read // directly (e.g. using ImageJ or showinf), and datasets that are being // imported through omebf. In the latter case, the necessary directory // structure is not preserved (only relative file names are stored in // OMEIS), so we will need to use slightly different logic to build the // list of associated files. boolean mappedOIF = !isOIB && !new File(id).getAbsoluteFile().exists(); wavelengths = new Vector<Integer>(); illuminations = new Vector<String>(); channels = new Vector<ChannelData>(); String oifName = null; if (isOIB) { oifName = mapOIBFiles(); } else { // make sure we have the OIF file, not a TIFF if (!checkSuffix(id, OIF_SUFFIX)) { currentId = findOIFFile(id); initFile(currentId); } oifName = currentId; } String oifPath = new Location(oifName).getAbsoluteFile().getAbsolutePath(); String path = (isOIB || !oifPath.endsWith(oifName) || mappedOIF) ? "" : oifPath.substring(0, oifPath.lastIndexOf(File.separator) + 1); try { getFile(oifName); } catch (IOException e) { oifName = oifName.replaceAll(".oif", ".OIF"); } // parse key/value pairs from the OIF file code = new String[NUM_DIMENSIONS]; size = new String[NUM_DIMENSIONS]; pixelSize = new Double[NUM_DIMENSIONS]; previewNames = new Vector<String>(); boolean laserEnabled = true; IniList f = getIniFile(oifName); IniTable saveInfo = f.getTable("ProfileSaveInfo"); String[] saveKeys = saveInfo.keySet().toArray(new String[saveInfo.size()]); for (String key : saveKeys) { String value = saveInfo.get(key).toString(); value = sanitizeValue(value).trim(); if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } filenames.put(new Integer(key.substring(11)), value); } else if (key.startsWith("RoiFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } try { roiFilenames.put(new Integer(key.substring(11)), value); } catch (NumberFormatException e) { } } else if (key.equals("PtyFileNameS")) ptyStart = value; else if (key.equals("PtyFileNameE")) ptyEnd = value; else if (key.equals("PtyFileNameT2")) ptyPattern = value; else if (key.indexOf("Thumb") != -1) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } if (thumbId == null) thumbId = value.trim(); } else if (key.startsWith("LutFileName")) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } lutNames.add(path + value); } else if (isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } previewNames.add(path + value.trim()); } } if (filenames.size() == 0) addPtyFiles(); for (int i=0; i<NUM_DIMENSIONS; i++) { IniTable commonParams = f.getTable("Axis " + i + " Parameters Common"); code[i] = commonParams.get("AxisCode"); size[i] = commonParams.get("MaxSize"); double end = Double.parseDouble(commonParams.get("EndPosition")); double start = Double.parseDouble(commonParams.get("StartPosition")); pixelSize[i] = end - start; } IniTable referenceParams = f.getTable("Reference Image Parameter"); imageDepth = Integer.parseInt(referenceParams.get("ImageDepth")); pixelSizeX = referenceParams.get("WidthConvertValue"); pixelSizeY = referenceParams.get("HeightConvertValue"); int index = 0; IniTable laser = f.getTable("Laser " + index + " Parameters"); while (laser != null) { laserEnabled = laser.get("Laser Enable").equals("1"); if (laserEnabled) { wavelengths.add(new Integer(laser.get("LaserWavelength"))); } creationDate = laser.get("ImageCaputreDate"); if (creationDate == null) { creationDate = laser.get("ImageCaptureDate"); } index++; laser = f.getTable("Laser " + index + " Parameters"); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { index = 1; IniTable guiChannel = f.getTable("GUI Channel " + index + " Parameters"); while (guiChannel != null) { ChannelData channel = new ChannelData(); channel.gain = new Double(guiChannel.get("AnalogPMTGain")); channel.voltage = new Double(guiChannel.get("AnalogPMTVoltage")); channel.barrierFilter = guiChannel.get("BF Name"); channel.active = Integer.parseInt(guiChannel.get("CH Activate")) != 0; channel.name = guiChannel.get("CH Name"); channel.dyeName = guiChannel.get("DyeName"); channel.emissionFilter = guiChannel.get("EmissionDM Name"); channel.emWave = new Integer(guiChannel.get("EmissionWavelength")); channel.excitationFilter = guiChannel.get("ExcitationDM Name"); channel.exWave = new Integer(guiChannel.get("ExcitationWavelength")); channels.add(channel); index++; guiChannel = f.getTable("GUI Channel " + index + " Parameters"); } index = 1; IniTable channel = f.getTable("Channel " + index + " Parameters"); while (channel != null) { String illumination = channel.get("LightType"); if (illumination != null) illumination = illumination.toLowerCase(); if (illumination == null) { // Ignored } else if (illumination.indexOf("fluorescence") != -1) { illumination = "Epifluorescence"; } else if (illumination.indexOf("transmitted") != -1) { illumination = "Transmitted"; } else illumination = null; illuminations.add(illumination); index++; channel = f.getTable("Channel " + index + " Parameters"); } for (IniTable table : f) { String tableName = table.get(IniTable.HEADER_KEY); String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { addGlobalMeta(tableName + " " + key, table.get(key)); } } } LOGGER.info("Initializing helper readers"); // populate core metadata for preview series if (previewNames.size() > 0) { Vector<String> v = new Vector<String>(); for (int i=0; i<previewNames.size(); i++) { String ss = previewNames.get(i); ss = replaceExtension(ss, "pty", "tif"); if (ss.endsWith(".tif")) v.add(ss); } previewNames = v; if (previewNames.size() > 0) { core = new CoreMetadata[2]; core[0] = new CoreMetadata(); core[1] = new CoreMetadata(); IFDList ifds = null; for (String previewName : previewNames) { RandomAccessInputStream preview = getFile(previewName); TiffParser tp = new TiffParser(preview); ifds = tp.getIFDs(); preview.close(); core[1].imageCount += ifds.size(); } core[1].sizeX = (int) ifds.get(0).getImageWidth(); core[1].sizeY = (int) ifds.get(0).getImageLength(); core[1].sizeZ = 1; core[1].sizeT = 1; core[1].sizeC = core[1].imageCount; core[1].rgb = false; int bits = ifds.get(0).getBitsPerSample()[0]; while ((bits % 8) != 0) bits++; bits /= 8; core[1].pixelType = FormatTools.pixelTypeFromBytes(bits, false, false); core[1].dimensionOrder = "XYCZT"; core[1].indexed = false; } } core[0].imageCount = filenames.size(); tiffs = new Vector<String>(getImageCount()); thumbReader = new BMPReader(); thumbId = replaceExtension(thumbId, "pty", "bmp"); thumbId = sanitizeFile(thumbId, path); LOGGER.info("Reading additional metadata"); // open each INI file (.pty extension) and build list of TIFF files String tiffPath = null; core[0].dimensionOrder = "XY"; for (int i=0, ii=0; ii<getImageCount(); i++, ii++) { String file = filenames.get(new Integer(i)); while (file == null) file = filenames.get(new Integer(++i)); file = sanitizeFile(file, path); if (file.indexOf(File.separator) != -1) { tiffPath = file.substring(0, file.lastIndexOf(File.separator)); } else tiffPath = file; Location ptyFile = new Location(file); if (!isOIB && !ptyFile.exists()) { LOGGER.warn("Could not find .pty file ({}); guessing at the " + "corresponding TIFF file.", file); String tiff = replaceExtension(file, ".pty", ".tif"); tiffs.add(ii, tiff); continue; } IniList pty = getIniFile(file); IniTable fileInfo = pty.getTable("File Info"); file = sanitizeValue(fileInfo.get("DataName")); if (!isPreviewName(file)) { while (file.indexOf("GST") != -1) { file = removeGST(file); } if (!mappedOIF) { if (isOIB) { file = tiffPath + File.separator + file; } else file = new Location(tiffPath, file).getAbsolutePath(); } tiffs.add(ii, file); } for (int dim=0; dim<NUM_DIMENSIONS; dim++) { IniTable axis = pty.getTable("Axis " + dim + " Parameters"); if (axis == null) break; boolean addAxis = Integer.parseInt(axis.get("Number")) > 1; if (dim == 2) { if (addAxis && getDimensionOrder().indexOf("C") == -1) { core[0].dimensionOrder += "C"; } } else if (dim == 3) { if (addAxis && getDimensionOrder().indexOf("Z") == -1) { core[0].dimensionOrder += "Z"; } } else if (dim == 4) { if (addAxis && getDimensionOrder().indexOf("T") == -1) { core[0].dimensionOrder += "T"; } } } IniTable acquisition = pty.getTable("Acquisition Parameters Common"); if (acquisition != null) { magnification = acquisition.get("Magnification"); lensNA = acquisition.get("ObjectiveLens NAValue"); objectiveName = acquisition.get("ObjectiveLens Name"); workingDistance = acquisition.get("ObjectiveLens WDValue"); pinholeSize = acquisition.get("PinholeDiameter"); String validBitCounts = acquisition.get("ValidBitCounts"); if (validBitCounts != null) { core[0].bitsPerPixel = Integer.parseInt(validBitCounts); } } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { for (IniTable table : pty) { String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { addGlobalMeta("Image " + ii + " : " + key, table.get(key)); } } } } if (tiffs.size() != getImageCount()) { core[0].imageCount = tiffs.size(); } usedFiles = new Vector<String>(); if (tiffPath != null) { usedFiles.add(id); if (!isOIB) { Location dir = new Location(tiffPath); if (!dir.exists()) { throw new FormatException( "Required directory " + tiffPath + " was not found."); } String[] list = mappedOIF ? Location.getIdMap().keySet().toArray(new String[0]) : dir.list(); for (int i=0; i<list.length; i++) { if (mappedOIF) usedFiles.add(list[i]); else { String p = new Location(tiffPath, list[i]).getAbsolutePath(); String check = p.toLowerCase(); if (!check.endsWith(".tif") && !check.endsWith(".pty") && !check.endsWith(".roi") && !check.endsWith(".lut") && !check.endsWith(".bmp")) { continue; } usedFiles.add(p); } } } } LOGGER.info("Populating metadata"); // calculate axis sizes int realChannels = 0; for (int i=0; i<NUM_DIMENSIONS; i++) { int ss = Integer.parseInt(size[i]); if (pixelSize[i] == null) pixelSize[i] = 1.0; if (code[i].equals("X")) core[0].sizeX = ss; else if (code[i].equals("Y")) core[0].sizeY = ss; else if (code[i].equals("Z")) { core[0].sizeZ = ss; // Z size stored in nm pixelSizeZ = Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000); } else if (code[i].equals("T")) { core[0].sizeT = ss; pixelSizeT = Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000); } else if (ss > 0) { if (getSizeC() == 0) core[0].sizeC = ss; else core[0].sizeC *= ss; if (code[i].equals("C")) realChannels = ss; } } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeC() == 0) core[0].sizeC = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (getImageCount() == getSizeC() && getSizeY() == 1) { core[0].imageCount *= getSizeZ() * getSizeT(); } else if (getImageCount() == getSizeC()) { core[0].sizeZ = 1; core[0].sizeT = 1; } if (getSizeZ() * getSizeT() * getSizeC() != getImageCount()) { int diff = (getSizeZ() * getSizeC() * getSizeT()) - getImageCount(); if (diff == previewNames.size() || diff < 0) { diff /= getSizeC(); if (getSizeT() > 1 && getSizeZ() == 1) core[0].sizeT -= diff; else if (getSizeZ() > 1 && getSizeT() == 1) core[0].sizeZ -= diff; } else core[0].imageCount += diff; } if (getSizeC() > 1 && getSizeZ() == 1 && getSizeT() == 1) { if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) core[0].dimensionOrder += "Z"; if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; if (getDimensionOrder().indexOf("T") == -1) core[0].dimensionOrder += "T"; core[0].pixelType = FormatTools.pixelTypeFromBytes(imageDepth, false, false); // set up thumbnail file mapping try { RandomAccessInputStream thumb = getFile(thumbId); byte[] b = new byte[(int) thumb.length()]; thumb.read(b); thumb.close(); Location.mapFile("thumbnail.bmp", new ByteArrayHandle(b)); thumbReader.setId("thumbnail.bmp"); for (int i=0; i<getSeriesCount(); i++) { core[i].thumbSizeX = thumbReader.getSizeX(); core[i].thumbSizeY = thumbReader.getSizeY(); } Location.mapFile("thumbnail.bmp", null); } catch (IOException e) { LOGGER.debug("Could not read thumbnail", e); } catch (FormatException e) { LOGGER.debug("Could not read thumbnail", e); } // initialize lookup table lut = new short[getSizeC()][3][65536]; byte[] buffer = new byte[65536 * 4]; int count = (int) Math.min(getSizeC(), lutNames.size()); for (int c=0; c<count; c++) { Exception exc = null; try { RandomAccessInputStream stream = getFile(lutNames.get(c)); stream.seek(stream.length() - 65536 * 4); stream.read(buffer); stream.close(); for (int q=0; q<buffer.length; q+=4) { lut[c][0][q / 4] = buffer[q + 1]; lut[c][1][q / 4] = buffer[q + 2]; lut[c][2][q / 4] = buffer[q + 3]; } } catch (IOException e) { exc = e; } catch (FormatException e) { exc = e; } if (exc != null) { LOGGER.debug("Could not read LUT", exc); lut = null; break; } } for (int i=0; i<getSeriesCount(); i++) { core[i].rgb = false; core[i].littleEndian = true; core[i].interleaved = false; core[i].metadataComplete = true; core[i].indexed = false; core[i].falseColor = false; } // populate MetadataStore MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (creationDate != null) { creationDate = creationDate.replaceAll("'", ""); creationDate = DateTools.formatDate(creationDate, DATE_FORMAT); } for (int i=0; i<getSeriesCount(); i++) { // populate Image data store.setImageName("Series " + (i + 1), i); if (creationDate != null) store.setImageAcquiredDate(creationDate, i); else MetadataTools.setDefaultCreationDate(store, id, i); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { populateMetadataStore(store, path); } }
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); parser.setCommentDelimiter(null); isOIB = checkSuffix(id, OIB_SUFFIX); if (isOIB) { try { ServiceFactory factory = new ServiceFactory(); poi = factory.getInstance(POIService.class); } catch (DependencyException de) { throw new FormatException("POI library not found", de); } poi.initialize(Location.getMappedId(id)); } // mappedOIF is used to distinguish between datasets that are being read // directly (e.g. using ImageJ or showinf), and datasets that are being // imported through omebf. In the latter case, the necessary directory // structure is not preserved (only relative file names are stored in // OMEIS), so we will need to use slightly different logic to build the // list of associated files. boolean mappedOIF = !isOIB && !new File(id).getAbsoluteFile().exists(); wavelengths = new Vector<Integer>(); illuminations = new Vector<String>(); channels = new Vector<ChannelData>(); String oifName = null; if (isOIB) { oifName = mapOIBFiles(); } else { // make sure we have the OIF file, not a TIFF if (!checkSuffix(id, OIF_SUFFIX)) { currentId = findOIFFile(id); initFile(currentId); } oifName = currentId; } String oifPath = new Location(oifName).getAbsoluteFile().getAbsolutePath(); String path = (isOIB || !oifPath.endsWith(oifName) || mappedOIF) ? "" : oifPath.substring(0, oifPath.lastIndexOf(File.separator) + 1); try { getFile(oifName); } catch (IOException e) { oifName = oifName.replaceAll(".oif", ".OIF"); } // parse key/value pairs from the OIF file code = new String[NUM_DIMENSIONS]; size = new String[NUM_DIMENSIONS]; pixelSize = new Double[NUM_DIMENSIONS]; previewNames = new Vector<String>(); boolean laserEnabled = true; IniList f = getIniFile(oifName); IniTable saveInfo = f.getTable("ProfileSaveInfo"); String[] saveKeys = saveInfo.keySet().toArray(new String[saveInfo.size()]); for (String key : saveKeys) { String value = saveInfo.get(key).toString(); value = sanitizeValue(value).trim(); if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } filenames.put(new Integer(key.substring(11)), value); } else if (key.startsWith("RoiFileName") && key.indexOf("Thumb") == -1 && !isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1).trim(); } try { roiFilenames.put(new Integer(key.substring(11)), value); } catch (NumberFormatException e) { } } else if (key.equals("PtyFileNameS")) ptyStart = value; else if (key.equals("PtyFileNameE")) ptyEnd = value; else if (key.equals("PtyFileNameT2")) ptyPattern = value; else if (key.indexOf("Thumb") != -1) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } if (thumbId == null) thumbId = value.trim(); } else if (key.startsWith("LutFileName")) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } lutNames.add(path + value); } else if (isPreviewName(value)) { if (mappedOIF) { value = value.substring(value.lastIndexOf(File.separator) + 1); } previewNames.add(path + value.trim()); } } if (filenames.size() == 0) addPtyFiles(); for (int i=0; i<NUM_DIMENSIONS; i++) { IniTable commonParams = f.getTable("Axis " + i + " Parameters Common"); code[i] = commonParams.get("AxisCode"); size[i] = commonParams.get("MaxSize"); double end = Double.parseDouble(commonParams.get("EndPosition")); double start = Double.parseDouble(commonParams.get("StartPosition")); pixelSize[i] = end - start; } IniTable referenceParams = f.getTable("Reference Image Parameter"); imageDepth = Integer.parseInt(referenceParams.get("ImageDepth")); pixelSizeX = referenceParams.get("WidthConvertValue"); pixelSizeY = referenceParams.get("HeightConvertValue"); int index = 0; IniTable laser = f.getTable("Laser " + index + " Parameters"); while (laser != null) { laserEnabled = laser.get("Laser Enable").equals("1"); if (laserEnabled) { wavelengths.add(new Integer(laser.get("LaserWavelength"))); } creationDate = laser.get("ImageCaputreDate"); if (creationDate == null) { creationDate = laser.get("ImageCaptureDate"); } index++; laser = f.getTable("Laser " + index + " Parameters"); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { index = 1; IniTable guiChannel = f.getTable("GUI Channel " + index + " Parameters"); while (guiChannel != null) { ChannelData channel = new ChannelData(); channel.gain = new Double(guiChannel.get("AnalogPMTGain")); channel.voltage = new Double(guiChannel.get("AnalogPMTVoltage")); channel.barrierFilter = guiChannel.get("BF Name"); channel.active = Integer.parseInt(guiChannel.get("CH Activate")) != 0; channel.name = guiChannel.get("CH Name"); channel.dyeName = guiChannel.get("DyeName"); channel.emissionFilter = guiChannel.get("EmissionDM Name"); channel.emWave = new Integer(guiChannel.get("EmissionWavelength")); channel.excitationFilter = guiChannel.get("ExcitationDM Name"); channel.exWave = new Integer(guiChannel.get("ExcitationWavelength")); channels.add(channel); index++; guiChannel = f.getTable("GUI Channel " + index + " Parameters"); } index = 1; IniTable channel = f.getTable("Channel " + index + " Parameters"); while (channel != null) { String illumination = channel.get("LightType"); if (illumination != null) illumination = illumination.toLowerCase(); if (illumination == null) { // Ignored } else if (illumination.indexOf("fluorescence") != -1) { illumination = "Epifluorescence"; } else if (illumination.indexOf("transmitted") != -1) { illumination = "Transmitted"; } else illumination = null; illuminations.add(illumination); index++; channel = f.getTable("Channel " + index + " Parameters"); } for (IniTable table : f) { String tableName = table.get(IniTable.HEADER_KEY); String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { addGlobalMeta(tableName + " " + key, table.get(key)); } } } LOGGER.info("Initializing helper readers"); // populate core metadata for preview series if (previewNames.size() > 0) { Vector<String> v = new Vector<String>(); for (int i=0; i<previewNames.size(); i++) { String ss = previewNames.get(i); ss = replaceExtension(ss, "pty", "tif"); if (ss.endsWith(".tif")) v.add(ss); } previewNames = v; if (previewNames.size() > 0) { core = new CoreMetadata[2]; core[0] = new CoreMetadata(); core[1] = new CoreMetadata(); IFDList ifds = null; for (String previewName : previewNames) { RandomAccessInputStream preview = getFile(previewName); TiffParser tp = new TiffParser(preview); ifds = tp.getIFDs(); preview.close(); core[1].imageCount += ifds.size(); } core[1].sizeX = (int) ifds.get(0).getImageWidth(); core[1].sizeY = (int) ifds.get(0).getImageLength(); core[1].sizeZ = 1; core[1].sizeT = 1; core[1].sizeC = core[1].imageCount; core[1].rgb = false; int bits = ifds.get(0).getBitsPerSample()[0]; while ((bits % 8) != 0) bits++; bits /= 8; core[1].pixelType = FormatTools.pixelTypeFromBytes(bits, false, false); core[1].dimensionOrder = "XYCZT"; core[1].indexed = false; } } core[0].imageCount = filenames.size(); tiffs = new Vector<String>(getImageCount()); thumbReader = new BMPReader(); thumbId = replaceExtension(thumbId, "pty", "bmp"); thumbId = sanitizeFile(thumbId, path); LOGGER.info("Reading additional metadata"); // open each INI file (.pty extension) and build list of TIFF files String tiffPath = null; core[0].dimensionOrder = "XY"; for (int i=0, ii=0; ii<getImageCount(); i++, ii++) { String file = filenames.get(new Integer(i)); while (file == null) file = filenames.get(new Integer(++i)); file = sanitizeFile(file, path); if (file.indexOf(File.separator) != -1) { tiffPath = file.substring(0, file.lastIndexOf(File.separator)); } else tiffPath = file; Location ptyFile = new Location(file); if (!isOIB && !ptyFile.exists()) { LOGGER.warn("Could not find .pty file ({}); guessing at the " + "corresponding TIFF file.", file); String tiff = replaceExtension(file, ".pty", ".tif"); tiffs.add(ii, tiff); continue; } IniList pty = getIniFile(file); IniTable fileInfo = pty.getTable("File Info"); file = sanitizeValue(fileInfo.get("DataName")); if (!isPreviewName(file)) { while (file.indexOf("GST") != -1) { file = removeGST(file); } if (!mappedOIF) { if (isOIB) { file = tiffPath + File.separator + file; } else file = new Location(tiffPath, file).getAbsolutePath(); } tiffs.add(ii, file); } for (int dim=0; dim<NUM_DIMENSIONS; dim++) { IniTable axis = pty.getTable("Axis " + dim + " Parameters"); if (axis == null) break; boolean addAxis = Integer.parseInt(axis.get("Number")) > 1; if (dim == 2) { if (addAxis && getDimensionOrder().indexOf("C") == -1) { core[0].dimensionOrder += "C"; } } else if (dim == 3) { if (addAxis && getDimensionOrder().indexOf("Z") == -1) { core[0].dimensionOrder += "Z"; } } else if (dim == 4) { if (addAxis && getDimensionOrder().indexOf("T") == -1) { core[0].dimensionOrder += "T"; } } } IniTable acquisition = pty.getTable("Acquisition Parameters Common"); if (acquisition != null) { magnification = acquisition.get("Magnification"); lensNA = acquisition.get("ObjectiveLens NAValue"); objectiveName = acquisition.get("ObjectiveLens Name"); workingDistance = acquisition.get("ObjectiveLens WDValue"); pinholeSize = acquisition.get("PinholeDiameter"); String validBitCounts = acquisition.get("ValidBitCounts"); if (validBitCounts != null) { core[0].bitsPerPixel = Integer.parseInt(validBitCounts); } } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { for (IniTable table : pty) { String[] keys = table.keySet().toArray(new String[table.size()]); for (String key : keys) { addGlobalMeta("Image " + ii + " : " + key, table.get(key)); } } } } if (tiffs.size() != getImageCount()) { core[0].imageCount = tiffs.size(); } usedFiles = new Vector<String>(); if (tiffPath != null) { usedFiles.add(id); if (!isOIB) { Location dir = new Location(tiffPath); if (!dir.exists()) { throw new FormatException( "Required directory " + tiffPath + " was not found."); } String[] list = mappedOIF ? Location.getIdMap().keySet().toArray(new String[0]) : dir.list(); for (int i=0; i<list.length; i++) { if (mappedOIF) usedFiles.add(list[i]); else { String p = new Location(tiffPath, list[i]).getAbsolutePath(); String check = p.toLowerCase(); if (!check.endsWith(".tif") && !check.endsWith(".pty") && !check.endsWith(".roi") && !check.endsWith(".lut") && !check.endsWith(".bmp")) { continue; } usedFiles.add(p); } } } } LOGGER.info("Populating metadata"); // calculate axis sizes int realChannels = 0; for (int i=0; i<NUM_DIMENSIONS; i++) { int ss = Integer.parseInt(size[i]); if (pixelSize[i] == null) pixelSize[i] = 1.0; if (code[i].equals("X")) core[0].sizeX = ss; else if (code[i].equals("Y") && ss > 1) core[0].sizeY = ss; else if (code[i].equals("Z")) { if (getSizeY() == 0) { core[0].sizeY = ss; } else { core[0].sizeZ = ss; // Z size stored in nm pixelSizeZ = Math.abs((pixelSize[i].doubleValue() / (getSizeZ() - 1)) / 1000); } } else if (code[i].equals("T")) { if (getSizeY() == 0) { core[0].sizeY = ss; } else { core[0].sizeT = ss; pixelSizeT = Math.abs((pixelSize[i].doubleValue() / (getSizeT() - 1)) / 1000); } } else if (ss > 0) { if (getSizeC() == 0) core[0].sizeC = ss; else core[0].sizeC *= ss; if (code[i].equals("C")) realChannels = ss; } } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeC() == 0) core[0].sizeC = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (getImageCount() == getSizeC() && getSizeY() == 1) { core[0].imageCount *= getSizeZ() * getSizeT(); } else if (getImageCount() == getSizeC()) { core[0].sizeZ = 1; core[0].sizeT = 1; } if (getSizeZ() * getSizeT() * getSizeC() != getImageCount()) { int diff = (getSizeZ() * getSizeC() * getSizeT()) - getImageCount(); if (diff == previewNames.size() || diff < 0) { diff /= getSizeC(); if (getSizeT() > 1 && getSizeZ() == 1) core[0].sizeT -= diff; else if (getSizeZ() > 1 && getSizeT() == 1) core[0].sizeZ -= diff; } else core[0].imageCount += diff; } if (getSizeC() > 1 && getSizeZ() == 1 && getSizeT() == 1) { if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) core[0].dimensionOrder += "Z"; if (getDimensionOrder().indexOf("C") == -1) core[0].dimensionOrder += "C"; if (getDimensionOrder().indexOf("T") == -1) core[0].dimensionOrder += "T"; core[0].pixelType = FormatTools.pixelTypeFromBytes(imageDepth, false, false); // set up thumbnail file mapping try { RandomAccessInputStream thumb = getFile(thumbId); byte[] b = new byte[(int) thumb.length()]; thumb.read(b); thumb.close(); Location.mapFile("thumbnail.bmp", new ByteArrayHandle(b)); thumbReader.setId("thumbnail.bmp"); for (int i=0; i<getSeriesCount(); i++) { core[i].thumbSizeX = thumbReader.getSizeX(); core[i].thumbSizeY = thumbReader.getSizeY(); } Location.mapFile("thumbnail.bmp", null); } catch (IOException e) { LOGGER.debug("Could not read thumbnail", e); } catch (FormatException e) { LOGGER.debug("Could not read thumbnail", e); } // initialize lookup table lut = new short[getSizeC()][3][65536]; byte[] buffer = new byte[65536 * 4]; int count = (int) Math.min(getSizeC(), lutNames.size()); for (int c=0; c<count; c++) { Exception exc = null; try { RandomAccessInputStream stream = getFile(lutNames.get(c)); stream.seek(stream.length() - 65536 * 4); stream.read(buffer); stream.close(); for (int q=0; q<buffer.length; q+=4) { lut[c][0][q / 4] = buffer[q + 1]; lut[c][1][q / 4] = buffer[q + 2]; lut[c][2][q / 4] = buffer[q + 3]; } } catch (IOException e) { exc = e; } catch (FormatException e) { exc = e; } if (exc != null) { LOGGER.debug("Could not read LUT", exc); lut = null; break; } } for (int i=0; i<getSeriesCount(); i++) { core[i].rgb = false; core[i].littleEndian = true; core[i].interleaved = false; core[i].metadataComplete = true; core[i].indexed = false; core[i].falseColor = false; } // populate MetadataStore MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); if (creationDate != null) { creationDate = creationDate.replaceAll("'", ""); creationDate = DateTools.formatDate(creationDate, DATE_FORMAT); } for (int i=0; i<getSeriesCount(); i++) { // populate Image data store.setImageName("Series " + (i + 1), i); if (creationDate != null) store.setImageAcquiredDate(creationDate, i); else MetadataTools.setDefaultCreationDate(store, id, i); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { populateMetadataStore(store, path); } }
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandExecuter.java b/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandExecuter.java index 5fc44be4d..e4f8138c3 100644 --- a/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandExecuter.java +++ b/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandExecuter.java @@ -1,211 +1,211 @@ package net.aufdemrand.denizen.scripts.commands; import net.aufdemrand.denizen.Denizen; import net.aufdemrand.denizen.events.ScriptEntryExecuteEvent; import net.aufdemrand.denizen.exceptions.InvalidArgumentsException; import net.aufdemrand.denizen.objects.dNPC; import net.aufdemrand.denizen.objects.dPlayer; import net.aufdemrand.denizen.scripts.ScriptEntry; import net.aufdemrand.denizen.objects.aH; import net.aufdemrand.denizen.tags.TagManager; import net.aufdemrand.denizen.utilities.DenizenAPI; import net.aufdemrand.denizen.utilities.debugging.dB; import net.aufdemrand.denizen.utilities.debugging.dB.DebugElement; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CommandExecuter { private Denizen plugin; final Pattern definition_pattern = Pattern.compile("%(.+?)%"); public CommandExecuter(Denizen denizen) { plugin = denizen; } /* * Executes a command defined in scriptEntry */ public boolean execute(ScriptEntry scriptEntry) { Matcher m = definition_pattern.matcher(scriptEntry.getCommandName()); StringBuffer sb = new StringBuffer(); while (m.find()) { if (scriptEntry.getResidingQueue().hasDefinition(m.group(1).toLowerCase())) m.appendReplacement(sb, scriptEntry.getResidingQueue().getDefinition(m.group(1).toLowerCase())); else m.appendReplacement(sb, "null"); } m.appendTail(sb); scriptEntry.setCommandName(sb.toString()); if (plugin.getCommandRegistry().get(scriptEntry.getCommandName()) == null) { dB.echoDebug(scriptEntry, DebugElement.Header, "Executing command: " + scriptEntry.getCommandName()); dB.echoError(scriptEntry.getCommandName() + " is an invalid dCommand! Are you sure it loaded?"); dB.echoDebug(scriptEntry, DebugElement.Footer); return false; } // Get the command instance ready for the execution of the scriptEntry AbstractCommand command = plugin.getCommandRegistry().get(scriptEntry.getCommandName()); // Debugger information if (scriptEntry.getPlayer() != null) dB.echoDebug(scriptEntry, DebugElement.Header, "Executing dCommand: " + scriptEntry.getCommandName() + "/" + scriptEntry.getPlayer().getName()); else dB.echoDebug(scriptEntry, DebugElement.Header, "Executing dCommand: " + scriptEntry.getCommandName() + (scriptEntry.getNPC() != null ? "/" + scriptEntry.getNPC().getName() : "")); // Don't execute() if problems arise in parseArgs() boolean keepGoing = true; try { // Throw exception if arguments are required for this command, but not supplied. if (command.getOptions().REQUIRED_ARGS > scriptEntry.getArguments().size()) throw new InvalidArgumentsException(""); if (scriptEntry.has_tags) scriptEntry.setArguments(TagManager.fillArguments(scriptEntry.getArguments(), scriptEntry, true)); // Replace tags /* If using NPC:# or PLAYER:Name arguments, these need to be changed out immediately because... * 1) Denizen/Player flags need the desired NPC/PLAYER before parseArgs's getFilledArguments() so that * the Player/Denizen flags will read from the correct Object. If using PLAYER or NPCID arguments, * the desired Objects are obviously not the same objects that were sent with the ScriptEntry. * 2) These arguments should be valid for EVERY ScriptCommand, so why not just take care of it * here, instead of requiring each command to take care of the argument. */ List<String> newArgs = new ArrayList<String>(); // Don't fill in tags if there were brackets detected.. // This means we're probably in a nested if. int nested_depth = 0; // Watch for IF command to avoid filling player and npc arguments // prematurely boolean if_ignore = false; for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) { if (arg.getValue().equals("{")) nested_depth++; if (arg.getValue().equals("}")) nested_depth--; // If nested, continue. if (nested_depth > 0) { newArgs.add(arg.raw_value); continue; } m = definition_pattern.matcher(arg.raw_value); sb = new StringBuffer(); while (m.find()) { if (scriptEntry.getResidingQueue().hasDefinition(m.group(1).toLowerCase())) m.appendReplacement(sb, scriptEntry.getResidingQueue() .getDefinition(m.group(1).toLowerCase())); else m.appendReplacement(sb, "null"); } m.appendTail(sb); arg = aH.Argument.valueOf(sb.toString()); // If using IF, check if we've reached the command + args // so that we don't fill player: or npc: prematurely if (command.getName().equalsIgnoreCase("if") && DenizenAPI.getCurrentInstance().getCommandRegistry().get(arg.getValue()) != null) if_ignore = true; // Fill player/off-line player if (arg.matchesPrefix("player") && !if_ignore) { dB.echoDebug(scriptEntry, "...replacing the linked player with " + arg.getValue()); - String value = TagManager.tag(scriptEntry.getPlayer(), scriptEntry.getNPC(), arg.getValue(), false); + String value = TagManager.tag(scriptEntry.getPlayer(), scriptEntry.getNPC(), arg.getValue(), false, scriptEntry); dPlayer player = dPlayer.valueOf(value); if (player == null || !player.isValid()) { dB.echoError(value + " is an invalid player!"); return false; } scriptEntry.setPlayer(player); } // Fill NPCID/NPC argument else if (arg.matchesPrefix("npc, npcid") && !if_ignore) { dB.echoDebug(scriptEntry, "...replacing the linked NPC with " + arg.getValue()); - String value = TagManager.tag(scriptEntry.getPlayer(), scriptEntry.getNPC(), arg.getValue(), false); + String value = TagManager.tag(scriptEntry.getPlayer(), scriptEntry.getNPC(), arg.getValue(), false, scriptEntry); dNPC npc = dNPC.valueOf(value); if (npc == null || !npc.isValid()) { dB.echoError(value + " is an invalid NPC!"); return false; } scriptEntry.setNPC(npc); } // Save the scriptentry if needed later for fetching scriptentry context else if (arg.matchesPrefix("save") && !if_ignore) { dB.echoDebug(scriptEntry, "...remembering this script entry!"); scriptEntry.getResidingQueue().holdScriptEntry(arg.getValue(), scriptEntry); } else newArgs.add(arg.raw_value); } // Add the arguments back to the scriptEntry. scriptEntry.setArguments(newArgs); // Now process non-instant tags. if (scriptEntry.has_tags) scriptEntry.setArguments(TagManager.fillArguments(scriptEntry.getArguments(), scriptEntry, false)); // Parse the rest of the arguments for execution. command.parseArgs(scriptEntry); } catch (InvalidArgumentsException e) { keepGoing = false; // Give usage hint if InvalidArgumentsException was called. dB.echoError("Woah! Invalid arguments were specified!"); dB.log(ChatColor.YELLOW + "+> MESSAGE follows: " + ChatColor.WHITE + "'" + e.getMessage() + "'"); dB.log("Usage: " + command.getUsageHint()); dB.echoDebug(scriptEntry, DebugElement.Footer); } catch (Exception e) { keepGoing = false; dB.echoError("Woah! An exception has been called with this command!"); if (!dB.showStackTraces) dB.echoError("Enable '/denizen stacktrace' for the nitty-gritty."); else e.printStackTrace(); dB.echoDebug(scriptEntry, DebugElement.Footer); } finally { if (keepGoing) try { // Fire event for last minute cancellation/alterations ScriptEntryExecuteEvent event = new ScriptEntryExecuteEvent(scriptEntry); Bukkit.getServer().getPluginManager().callEvent(event); // If event is altered, update the scriptEntry. if (event.isAltered()) scriptEntry = event.getScriptEntry(); // Run the execute method in the command if (!event.isCancelled()) command.execute(scriptEntry); else dB.echoDebug(scriptEntry, "ScriptEntry has been cancelled."); } catch (Exception e) { dB.echoError("Woah!! An exception has been called with this command!"); if (!dB.showStackTraces) dB.echoError("Enable '/denizen stacktrace' for the nitty-gritty."); else e.printStackTrace(); } } return true; } }
false
true
public boolean execute(ScriptEntry scriptEntry) { Matcher m = definition_pattern.matcher(scriptEntry.getCommandName()); StringBuffer sb = new StringBuffer(); while (m.find()) { if (scriptEntry.getResidingQueue().hasDefinition(m.group(1).toLowerCase())) m.appendReplacement(sb, scriptEntry.getResidingQueue().getDefinition(m.group(1).toLowerCase())); else m.appendReplacement(sb, "null"); } m.appendTail(sb); scriptEntry.setCommandName(sb.toString()); if (plugin.getCommandRegistry().get(scriptEntry.getCommandName()) == null) { dB.echoDebug(scriptEntry, DebugElement.Header, "Executing command: " + scriptEntry.getCommandName()); dB.echoError(scriptEntry.getCommandName() + " is an invalid dCommand! Are you sure it loaded?"); dB.echoDebug(scriptEntry, DebugElement.Footer); return false; } // Get the command instance ready for the execution of the scriptEntry AbstractCommand command = plugin.getCommandRegistry().get(scriptEntry.getCommandName()); // Debugger information if (scriptEntry.getPlayer() != null) dB.echoDebug(scriptEntry, DebugElement.Header, "Executing dCommand: " + scriptEntry.getCommandName() + "/" + scriptEntry.getPlayer().getName()); else dB.echoDebug(scriptEntry, DebugElement.Header, "Executing dCommand: " + scriptEntry.getCommandName() + (scriptEntry.getNPC() != null ? "/" + scriptEntry.getNPC().getName() : "")); // Don't execute() if problems arise in parseArgs() boolean keepGoing = true; try { // Throw exception if arguments are required for this command, but not supplied. if (command.getOptions().REQUIRED_ARGS > scriptEntry.getArguments().size()) throw new InvalidArgumentsException(""); if (scriptEntry.has_tags) scriptEntry.setArguments(TagManager.fillArguments(scriptEntry.getArguments(), scriptEntry, true)); // Replace tags /* If using NPC:# or PLAYER:Name arguments, these need to be changed out immediately because... * 1) Denizen/Player flags need the desired NPC/PLAYER before parseArgs's getFilledArguments() so that * the Player/Denizen flags will read from the correct Object. If using PLAYER or NPCID arguments, * the desired Objects are obviously not the same objects that were sent with the ScriptEntry. * 2) These arguments should be valid for EVERY ScriptCommand, so why not just take care of it * here, instead of requiring each command to take care of the argument. */ List<String> newArgs = new ArrayList<String>(); // Don't fill in tags if there were brackets detected.. // This means we're probably in a nested if. int nested_depth = 0; // Watch for IF command to avoid filling player and npc arguments // prematurely boolean if_ignore = false; for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) { if (arg.getValue().equals("{")) nested_depth++; if (arg.getValue().equals("}")) nested_depth--; // If nested, continue. if (nested_depth > 0) { newArgs.add(arg.raw_value); continue; } m = definition_pattern.matcher(arg.raw_value); sb = new StringBuffer(); while (m.find()) { if (scriptEntry.getResidingQueue().hasDefinition(m.group(1).toLowerCase())) m.appendReplacement(sb, scriptEntry.getResidingQueue() .getDefinition(m.group(1).toLowerCase())); else m.appendReplacement(sb, "null"); } m.appendTail(sb); arg = aH.Argument.valueOf(sb.toString()); // If using IF, check if we've reached the command + args // so that we don't fill player: or npc: prematurely if (command.getName().equalsIgnoreCase("if") && DenizenAPI.getCurrentInstance().getCommandRegistry().get(arg.getValue()) != null) if_ignore = true; // Fill player/off-line player if (arg.matchesPrefix("player") && !if_ignore) { dB.echoDebug(scriptEntry, "...replacing the linked player with " + arg.getValue()); String value = TagManager.tag(scriptEntry.getPlayer(), scriptEntry.getNPC(), arg.getValue(), false); dPlayer player = dPlayer.valueOf(value); if (player == null || !player.isValid()) { dB.echoError(value + " is an invalid player!"); return false; } scriptEntry.setPlayer(player); } // Fill NPCID/NPC argument else if (arg.matchesPrefix("npc, npcid") && !if_ignore) { dB.echoDebug(scriptEntry, "...replacing the linked NPC with " + arg.getValue()); String value = TagManager.tag(scriptEntry.getPlayer(), scriptEntry.getNPC(), arg.getValue(), false); dNPC npc = dNPC.valueOf(value); if (npc == null || !npc.isValid()) { dB.echoError(value + " is an invalid NPC!"); return false; } scriptEntry.setNPC(npc); } // Save the scriptentry if needed later for fetching scriptentry context else if (arg.matchesPrefix("save") && !if_ignore) { dB.echoDebug(scriptEntry, "...remembering this script entry!"); scriptEntry.getResidingQueue().holdScriptEntry(arg.getValue(), scriptEntry); } else newArgs.add(arg.raw_value); } // Add the arguments back to the scriptEntry. scriptEntry.setArguments(newArgs); // Now process non-instant tags. if (scriptEntry.has_tags) scriptEntry.setArguments(TagManager.fillArguments(scriptEntry.getArguments(), scriptEntry, false)); // Parse the rest of the arguments for execution. command.parseArgs(scriptEntry); } catch (InvalidArgumentsException e) { keepGoing = false; // Give usage hint if InvalidArgumentsException was called. dB.echoError("Woah! Invalid arguments were specified!"); dB.log(ChatColor.YELLOW + "+> MESSAGE follows: " + ChatColor.WHITE + "'" + e.getMessage() + "'"); dB.log("Usage: " + command.getUsageHint()); dB.echoDebug(scriptEntry, DebugElement.Footer); } catch (Exception e) { keepGoing = false; dB.echoError("Woah! An exception has been called with this command!"); if (!dB.showStackTraces) dB.echoError("Enable '/denizen stacktrace' for the nitty-gritty."); else e.printStackTrace(); dB.echoDebug(scriptEntry, DebugElement.Footer); } finally { if (keepGoing) try { // Fire event for last minute cancellation/alterations ScriptEntryExecuteEvent event = new ScriptEntryExecuteEvent(scriptEntry); Bukkit.getServer().getPluginManager().callEvent(event); // If event is altered, update the scriptEntry. if (event.isAltered()) scriptEntry = event.getScriptEntry(); // Run the execute method in the command if (!event.isCancelled()) command.execute(scriptEntry); else dB.echoDebug(scriptEntry, "ScriptEntry has been cancelled."); } catch (Exception e) { dB.echoError("Woah!! An exception has been called with this command!"); if (!dB.showStackTraces) dB.echoError("Enable '/denizen stacktrace' for the nitty-gritty."); else e.printStackTrace(); } } return true; }
public boolean execute(ScriptEntry scriptEntry) { Matcher m = definition_pattern.matcher(scriptEntry.getCommandName()); StringBuffer sb = new StringBuffer(); while (m.find()) { if (scriptEntry.getResidingQueue().hasDefinition(m.group(1).toLowerCase())) m.appendReplacement(sb, scriptEntry.getResidingQueue().getDefinition(m.group(1).toLowerCase())); else m.appendReplacement(sb, "null"); } m.appendTail(sb); scriptEntry.setCommandName(sb.toString()); if (plugin.getCommandRegistry().get(scriptEntry.getCommandName()) == null) { dB.echoDebug(scriptEntry, DebugElement.Header, "Executing command: " + scriptEntry.getCommandName()); dB.echoError(scriptEntry.getCommandName() + " is an invalid dCommand! Are you sure it loaded?"); dB.echoDebug(scriptEntry, DebugElement.Footer); return false; } // Get the command instance ready for the execution of the scriptEntry AbstractCommand command = plugin.getCommandRegistry().get(scriptEntry.getCommandName()); // Debugger information if (scriptEntry.getPlayer() != null) dB.echoDebug(scriptEntry, DebugElement.Header, "Executing dCommand: " + scriptEntry.getCommandName() + "/" + scriptEntry.getPlayer().getName()); else dB.echoDebug(scriptEntry, DebugElement.Header, "Executing dCommand: " + scriptEntry.getCommandName() + (scriptEntry.getNPC() != null ? "/" + scriptEntry.getNPC().getName() : "")); // Don't execute() if problems arise in parseArgs() boolean keepGoing = true; try { // Throw exception if arguments are required for this command, but not supplied. if (command.getOptions().REQUIRED_ARGS > scriptEntry.getArguments().size()) throw new InvalidArgumentsException(""); if (scriptEntry.has_tags) scriptEntry.setArguments(TagManager.fillArguments(scriptEntry.getArguments(), scriptEntry, true)); // Replace tags /* If using NPC:# or PLAYER:Name arguments, these need to be changed out immediately because... * 1) Denizen/Player flags need the desired NPC/PLAYER before parseArgs's getFilledArguments() so that * the Player/Denizen flags will read from the correct Object. If using PLAYER or NPCID arguments, * the desired Objects are obviously not the same objects that were sent with the ScriptEntry. * 2) These arguments should be valid for EVERY ScriptCommand, so why not just take care of it * here, instead of requiring each command to take care of the argument. */ List<String> newArgs = new ArrayList<String>(); // Don't fill in tags if there were brackets detected.. // This means we're probably in a nested if. int nested_depth = 0; // Watch for IF command to avoid filling player and npc arguments // prematurely boolean if_ignore = false; for (aH.Argument arg : aH.interpret(scriptEntry.getArguments())) { if (arg.getValue().equals("{")) nested_depth++; if (arg.getValue().equals("}")) nested_depth--; // If nested, continue. if (nested_depth > 0) { newArgs.add(arg.raw_value); continue; } m = definition_pattern.matcher(arg.raw_value); sb = new StringBuffer(); while (m.find()) { if (scriptEntry.getResidingQueue().hasDefinition(m.group(1).toLowerCase())) m.appendReplacement(sb, scriptEntry.getResidingQueue() .getDefinition(m.group(1).toLowerCase())); else m.appendReplacement(sb, "null"); } m.appendTail(sb); arg = aH.Argument.valueOf(sb.toString()); // If using IF, check if we've reached the command + args // so that we don't fill player: or npc: prematurely if (command.getName().equalsIgnoreCase("if") && DenizenAPI.getCurrentInstance().getCommandRegistry().get(arg.getValue()) != null) if_ignore = true; // Fill player/off-line player if (arg.matchesPrefix("player") && !if_ignore) { dB.echoDebug(scriptEntry, "...replacing the linked player with " + arg.getValue()); String value = TagManager.tag(scriptEntry.getPlayer(), scriptEntry.getNPC(), arg.getValue(), false, scriptEntry); dPlayer player = dPlayer.valueOf(value); if (player == null || !player.isValid()) { dB.echoError(value + " is an invalid player!"); return false; } scriptEntry.setPlayer(player); } // Fill NPCID/NPC argument else if (arg.matchesPrefix("npc, npcid") && !if_ignore) { dB.echoDebug(scriptEntry, "...replacing the linked NPC with " + arg.getValue()); String value = TagManager.tag(scriptEntry.getPlayer(), scriptEntry.getNPC(), arg.getValue(), false, scriptEntry); dNPC npc = dNPC.valueOf(value); if (npc == null || !npc.isValid()) { dB.echoError(value + " is an invalid NPC!"); return false; } scriptEntry.setNPC(npc); } // Save the scriptentry if needed later for fetching scriptentry context else if (arg.matchesPrefix("save") && !if_ignore) { dB.echoDebug(scriptEntry, "...remembering this script entry!"); scriptEntry.getResidingQueue().holdScriptEntry(arg.getValue(), scriptEntry); } else newArgs.add(arg.raw_value); } // Add the arguments back to the scriptEntry. scriptEntry.setArguments(newArgs); // Now process non-instant tags. if (scriptEntry.has_tags) scriptEntry.setArguments(TagManager.fillArguments(scriptEntry.getArguments(), scriptEntry, false)); // Parse the rest of the arguments for execution. command.parseArgs(scriptEntry); } catch (InvalidArgumentsException e) { keepGoing = false; // Give usage hint if InvalidArgumentsException was called. dB.echoError("Woah! Invalid arguments were specified!"); dB.log(ChatColor.YELLOW + "+> MESSAGE follows: " + ChatColor.WHITE + "'" + e.getMessage() + "'"); dB.log("Usage: " + command.getUsageHint()); dB.echoDebug(scriptEntry, DebugElement.Footer); } catch (Exception e) { keepGoing = false; dB.echoError("Woah! An exception has been called with this command!"); if (!dB.showStackTraces) dB.echoError("Enable '/denizen stacktrace' for the nitty-gritty."); else e.printStackTrace(); dB.echoDebug(scriptEntry, DebugElement.Footer); } finally { if (keepGoing) try { // Fire event for last minute cancellation/alterations ScriptEntryExecuteEvent event = new ScriptEntryExecuteEvent(scriptEntry); Bukkit.getServer().getPluginManager().callEvent(event); // If event is altered, update the scriptEntry. if (event.isAltered()) scriptEntry = event.getScriptEntry(); // Run the execute method in the command if (!event.isCancelled()) command.execute(scriptEntry); else dB.echoDebug(scriptEntry, "ScriptEntry has been cancelled."); } catch (Exception e) { dB.echoError("Woah!! An exception has been called with this command!"); if (!dB.showStackTraces) dB.echoError("Enable '/denizen stacktrace' for the nitty-gritty."); else e.printStackTrace(); } } return true; }
diff --git a/bundles/org.eclipse.equinox.servletbridge/src/org/eclipse/equinox/servletbridge/FrameworkLauncher.java b/bundles/org.eclipse.equinox.servletbridge/src/org/eclipse/equinox/servletbridge/FrameworkLauncher.java index 471cd1a5..7e5daad9 100644 --- a/bundles/org.eclipse.equinox.servletbridge/src/org/eclipse/equinox/servletbridge/FrameworkLauncher.java +++ b/bundles/org.eclipse.equinox.servletbridge/src/org/eclipse/equinox/servletbridge/FrameworkLauncher.java @@ -1,664 +1,664 @@ /******************************************************************************* * Copyright (c) 2005 Cognos Incorporated. * 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: * Cognos Incorporated - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.servletbridge; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.*; import java.util.*; import java.util.jar.*; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; /** * The FrameworkLauncher provides the logic to: * 1) init * 2) deploy * 3) start * 4) stop * 5) undeploy * 6) destroy * an instance of the OSGi framework. * These 6 methods are provided to help manage the lifecycle and are called from outside this * class by the BridgeServlet. To create an extended FrameworkLauncher over-ride these methods to allow * custom behaviour. */ public class FrameworkLauncher { private static final String WS_DELIM = " \t\n\r\f"; //$NON-NLS-1$ protected static final String FILE_SCHEME = "file:"; //$NON-NLS-1$ protected static final String FRAMEWORK_BUNDLE_NAME = "org.eclipse.osgi"; //$NON-NLS-1$ protected static final String STARTER = "org.eclipse.core.runtime.adaptor.EclipseStarter"; //$NON-NLS-1$ protected static final String NULL_IDENTIFIER = "@null"; //$NON-NLS-1$ protected static final String OSGI_FRAMEWORK = "osgi.framework"; //$NON-NLS-1$ protected static final String OSGI_INSTANCE_AREA = "osgi.instance.area"; //$NON-NLS-1$ protected static final String OSGI_CONFIGURATION_AREA = "osgi.configuration.area"; //$NON-NLS-1$ protected static final String OSGI_INSTALL_AREA = "osgi.install.area"; //$NON-NLS-1$ protected static final String RESOURCE_BASE = "/WEB-INF/eclipse/"; //$NON-NLS-1$ protected static final String LAUNCH_INI = "launch.ini"; //$NON-NLS-1$ private static final String MANIFEST_VERSION = "Manifest-Version"; //$NON-NLS-1$ private static final String BUNDLE_MANIFEST_VERSION = "Bundle-ManifestVersion"; //$NON-NLS-1$ private static final String BUNDLE_NAME = "Bundle-Name"; //$NON-NLS-1$ private static final String BUNDLE_SYMBOLIC_NAME = "Bundle-SymbolicName"; //$NON-NLS-1$ private static final String BUNDLE_VERSION = "Bundle-Version"; //$NON-NLS-1$ private static final String FRAGMENT_HOST = "Fragment-Host"; //$NON-NLS-1$ private static final String EXPORT_PACKAGE = "Export-Package"; //$NON-NLS-1$ private static final String CONFIG_COMMANDLINE = "commandline"; //$NON-NLS-1$ private static final String CONFIG_EXTENDED_FRAMEWORK_EXPORTS = "extendedFrameworkExports"; //$NON-NLS-1$ protected ServletConfig config; protected ServletContext context; private File platformDirectory; private ClassLoader frameworkContextClassLoader; private URLClassLoader frameworkClassLoader; void init(ServletConfig servletConfig) { config = servletConfig; context = servletConfig.getServletContext(); init(); } /** * init is the first method called on the FrameworkLauncher and can be used for any initial setup. * The default behaviour is to do nothing. */ public void init() { // do nothing for now } /** * destory is the last method called on the FrameworkLauncher and can be used for any final cleanup. * The default behaviour is to do nothing. */ public void destroy() { // do nothing for now } /** * deploy is used to move the OSGi framework libraries into a location suitable for execution. * The default behaviour is to copy the contents of the webapps WEB-INF/eclipse directory * to the webapps temp directory. */ public synchronized void deploy() { if (platformDirectory != null) { context.log("Framework is already deployed"); //$NON-NLS-1$ return; } File servletTemp = (File) context.getAttribute("javax.servlet.context.tempdir"); //$NON-NLS-1$ platformDirectory = new File(servletTemp, "eclipse"); //$NON-NLS-1$ if (!platformDirectory.exists()) { platformDirectory.mkdirs(); } copyResource(RESOURCE_BASE + "configuration/", new File(platformDirectory, "configuration")); //$NON-NLS-1$ //$NON-NLS-2$ copyResource(RESOURCE_BASE + "features/", new File(platformDirectory, "features")); //$NON-NLS-1$ //$NON-NLS-2$ File plugins = new File(platformDirectory, "plugins"); //$NON-NLS-1$ copyResource(RESOURCE_BASE + "plugins/", plugins); //$NON-NLS-1$ deployExtensionBundle(plugins); copyResource(RESOURCE_BASE + ".eclipseproduct", new File(platformDirectory, ".eclipseproduct")); //$NON-NLS-1$ //$NON-NLS-2$ } /** * deployExtensionBundle will generate the Servletbridge extensionbundle if it is not already present in the platform's * plugin directory. By default it exports "org.eclipse.equinox.servletbridge" and a versioned export of the Servlet API. * Additional exports can be added by using the "extendedFrameworkExports" initial-param in the ServletConfig */ private void deployExtensionBundle(File plugins) { File extensionBundle = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0.jar"); //$NON-NLS-1$ File extensionBundleDir = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0"); //$NON-NLS-1$ if (extensionBundle.exists() || (extensionBundleDir.exists() && extensionBundleDir.isDirectory())) return; Manifest mf = new Manifest(); Attributes attribs = mf.getMainAttributes(); attribs.putValue(MANIFEST_VERSION,"1.0"); //$NON-NLS-1$ attribs.putValue(BUNDLE_MANIFEST_VERSION,"2"); //$NON-NLS-1$ attribs.putValue(BUNDLE_NAME,"Servletbridge Extension Bundle"); //$NON-NLS-1$ attribs.putValue(BUNDLE_SYMBOLIC_NAME,"org.eclipse.equinox.servletbridge.extensionbundle"); //$NON-NLS-1$ attribs.putValue(BUNDLE_VERSION,"1.0.0"); //$NON-NLS-1$ attribs.putValue(FRAGMENT_HOST,"system.bundle; extension:=framework"); //$NON-NLS-1$ String servletVersion = context.getMajorVersion() + "." + context.getMinorVersion(); //$NON-NLS-1$ String packageExports = "org.eclipse.equinox.servletbridge; version=1.0" + //$NON-NLS-1$ ", javax.servlet; version=" + servletVersion + //$NON-NLS-1$ ", javax.servlet.http; version=" + servletVersion + //$NON-NLS-1$ ", javax.servlet.resources; version=" + servletVersion; //$NON-NLS-1$ String extendedExports = config.getInitParameter(CONFIG_EXTENDED_FRAMEWORK_EXPORTS); if (extendedExports != null && extendedExports.trim().length()!=0) packageExports += ", " + extendedExports; //$NON-NLS-1$ attribs.putValue(EXPORT_PACKAGE, packageExports); try { JarOutputStream jos = null; try { jos = new JarOutputStream(new FileOutputStream(extensionBundle), mf); jos.finish(); } finally { if (jos != null) jos.close(); } } catch (IOException e) { context.log("Error generating extension bundle", e); //$NON-NLS-1$ } } /** undeploy is the reverse operation of deploy and removes the OSGi framework libraries from their * execution location. Typically this method will only be called if a manual undeploy is requested in the * ServletBridge. * By default, this method removes the OSGi install and also removes the workspace. */ public synchronized void undeploy() { if (platformDirectory == null) { context.log("Undeploy unnecessary. - (not deployed)"); //$NON-NLS-1$ return; } if (frameworkClassLoader != null) { throw new IllegalStateException("Could not undeploy Framework - (not stopped)"); //$NON-NLS-1$ } deleteDirectory(new File(platformDirectory, "configuration")); //$NON-NLS-1$ deleteDirectory(new File(platformDirectory, "features")); //$NON-NLS-1$ deleteDirectory(new File(platformDirectory, "plugins")); //$NON-NLS-1$ deleteDirectory(new File(platformDirectory, "workspace")); //$NON-NLS-1$ new File(platformDirectory, ".eclipseproduct").delete(); //$NON-NLS-1$ platformDirectory = null; } /** start is used to "start" a previously deployed OSGi framework * The default behaviour will read launcher.ini to create a set of initial properties and * use the "commandline" configuration parameter to create the equivalent command line arguments * available when starting Eclipse. */ public synchronized void start() { if (platformDirectory == null) throw new IllegalStateException("Could not start the Framework - (not deployed)"); //$NON-NLS-1$ if (frameworkClassLoader != null) { context.log("Framework is already started"); //$NON-NLS-1$ return; } Map initalPropertyMap = buildInitialPropertyMap(); String[] args = buildCommandLineArguments(); ClassLoader original = Thread.currentThread().getContextClassLoader(); try { System.setProperty("osgi.framework.useSystemProperties", "false"); //$NON-NLS-1$ //$NON-NLS-2$ URL[] osgiURLArray = {new URL((String) initalPropertyMap.get(OSGI_FRAMEWORK))}; frameworkClassLoader = new ChildFirstURLClassLoader(osgiURLArray, this.getClass().getClassLoader()); Class clazz = frameworkClassLoader.loadClass(STARTER); Method setInitialProperties = clazz.getMethod("setInitialProperties", new Class[] {Map.class}); //$NON-NLS-1$ setInitialProperties.invoke(null, new Object[] {initalPropertyMap}); Method runMethod = clazz.getMethod("startup", new Class[] {String[].class, Runnable.class}); //$NON-NLS-1$ runMethod.invoke(null, new Object[] {args, null}); frameworkContextClassLoader = Thread.currentThread().getContextClassLoader(); } catch (InvocationTargetException ite) { Throwable t = ite.getTargetException(); if (t == null) t = ite; context.log("Error while starting Framework", t); //$NON-NLS-1$ throw new RuntimeException(t.getMessage()); } catch (Exception e) { context.log("Error while starting Framework", e); //$NON-NLS-1$ throw new RuntimeException(e.getMessage()); } finally { Thread.currentThread().setContextClassLoader(original); } } /** buildInitialPropertyMap create the inital set of properties from the contents of launch.ini * and for a few other properties necessary to launch defaults are supplied if not provided. * The value '@null' will set the map value to null. * @return a map containing the initial properties */ protected Map buildInitialPropertyMap() { Map initialPropertyMap = new HashMap(); Properties launchProperties = loadProperties(RESOURCE_BASE + LAUNCH_INI); for (Iterator it = launchProperties.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); - if (key.endsWith("*")) { + if (key.endsWith("*")) { //$NON-NLS-1$ if (value.equals(NULL_IDENTIFIER)) { clearPrefixedSystemProperties(key.substring(0, key.length() -1), initialPropertyMap); } } else if (value.equals(NULL_IDENTIFIER)) initialPropertyMap.put(key, null); else initialPropertyMap.put(entry.getKey(), entry.getValue()); } try { // install.area if not specified if (initialPropertyMap.get(OSGI_INSTALL_AREA) == null) initialPropertyMap.put(OSGI_INSTALL_AREA, platformDirectory.toURL().toExternalForm()); // configuration.area if not specified if (initialPropertyMap.get(OSGI_CONFIGURATION_AREA) == null) { File configurationDirectory = new File(platformDirectory, "configuration"); //$NON-NLS-1$ if (!configurationDirectory.exists()) { configurationDirectory.mkdirs(); } initialPropertyMap.put(OSGI_CONFIGURATION_AREA, configurationDirectory.toURL().toExternalForm()); } // instance.area if not specified if (initialPropertyMap.get(OSGI_INSTANCE_AREA) == null) { File workspaceDirectory = new File(platformDirectory, "workspace"); //$NON-NLS-1$ if (!workspaceDirectory.exists()) { workspaceDirectory.mkdirs(); } initialPropertyMap.put(OSGI_INSTANCE_AREA, workspaceDirectory.toURL().toExternalForm()); } // osgi.framework if not specified if (initialPropertyMap.get(OSGI_FRAMEWORK) == null) { // search for osgi.framework in osgi.install.area String installArea = (String) initialPropertyMap.get(OSGI_INSTALL_AREA); // only support file type URLs for install area if (installArea.startsWith(FILE_SCHEME)) installArea = installArea.substring(FILE_SCHEME.length()); String path = new File(installArea, "plugins").toString(); //$NON-NLS-1$ path = searchFor(FRAMEWORK_BUNDLE_NAME, path); if (path == null) throw new RuntimeException("Could not find framework"); //$NON-NLS-1$ initialPropertyMap.put(OSGI_FRAMEWORK, new File(path).toURL().toExternalForm()); } } catch (MalformedURLException e) { throw new RuntimeException("Error establishing location"); //$NON-NLS-1$ } return initialPropertyMap; } /** * clearPrefixedSystemProperties clears System Properties by wiritng null properties in the targetPropertyMap that match a prefix */ private static void clearPrefixedSystemProperties(String prefix, Map targetPropertyMap) { for (Iterator it = System.getProperties().keySet().iterator(); it.hasNext();) { String propertyName = (String) it.next(); if (propertyName.startsWith(prefix) && !targetPropertyMap.containsKey(propertyName)) { targetPropertyMap.put(propertyName, null); } } } /** * buildCommandLineArguments parses the commandline config parameter into a set of arguments * @return an array of String containing the commandline arguments */ protected String[] buildCommandLineArguments() { List args = new ArrayList(); String commandLine = config.getInitParameter(CONFIG_COMMANDLINE); if (commandLine != null) { StringTokenizer tokenizer = new StringTokenizer(commandLine, WS_DELIM); while (tokenizer.hasMoreTokens()) { String arg = tokenizer.nextToken(); if (arg.startsWith("\"")) { //$NON-NLS-1$ String remainingArg = tokenizer.nextToken("\""); //$NON-NLS-1$ arg = arg.substring(1) + remainingArg; // skip to next whitespace separated token tokenizer.nextToken(WS_DELIM); } else if (arg.startsWith("'")) { //$NON-NLS-1$ String remainingArg = tokenizer.nextToken("'"); //$NON-NLS-1$ arg = arg.substring(1) + remainingArg; // skip to next whitespace separated token tokenizer.nextToken(WS_DELIM); } args.add(arg); } } return (String[]) args.toArray(new String[] {}); } /** * stop is used to "shutdown" the framework and make it avialable for garbage collection. * The default implementation also has special handling for Apache Commons Logging to "release" any * resources associated with the frameworkContextClassLoader. */ public synchronized void stop() { if (platformDirectory == null) { context.log("Shutdown unnecessary. (not deployed)"); //$NON-NLS-1$ return; } if (frameworkClassLoader == null) { context.log("Framework is already shutdown"); //$NON-NLS-1$ return; } ClassLoader original = Thread.currentThread().getContextClassLoader(); try { Class clazz = frameworkClassLoader.loadClass(STARTER); Method method = clazz.getDeclaredMethod("shutdown", (Class[]) null); //$NON-NLS-1$ Thread.currentThread().setContextClassLoader(frameworkContextClassLoader); method.invoke(clazz, (Object[]) null); // ACL keys its loggers off of the ContextClassLoader which prevents GC without calling release. // This section explicitly calls release if ACL is used. try { clazz = this.getClass().getClassLoader().loadClass("org.apache.commons.logging.LogFactory"); //$NON-NLS-1$ method = clazz.getDeclaredMethod("release", new Class[] {ClassLoader.class}); //$NON-NLS-1$ method.invoke(clazz, new Object[] {frameworkContextClassLoader}); } catch (ClassNotFoundException e) { // ignore, ACL is not being used } } catch (Exception e) { context.log("Error while stopping Framework", e); //$NON-NLS-1$ return; } finally { frameworkClassLoader = null; frameworkContextClassLoader = null; Thread.currentThread().setContextClassLoader(original); } } /** * copyResource is a convenience method to recursively copy resources from the ServletContext to * an installation target. The default behaviour will create a directory if the resourcepath ends * in '/' and a file otherwise. * @param resourcePath - The resource root path * @param target - The root location where resources are to be copied */ protected void copyResource(String resourcePath, File target) { if (resourcePath.endsWith("/")) { //$NON-NLS-1$ target.mkdir(); Set paths = context.getResourcePaths(resourcePath); if (paths == null) return; for (Iterator it = paths.iterator(); it.hasNext();) { String path = (String) it.next(); File newFile = new File(target, path.substring(resourcePath.length())); copyResource(path, newFile); } } else { try { if (target.createNewFile()) { InputStream is = null; OutputStream os = null; try { is = context.getResourceAsStream(resourcePath); if (is == null) return; os = new FileOutputStream(target); byte[] buffer = new byte[8192]; int bytesRead = is.read(buffer); while (bytesRead != -1) { os.write(buffer, 0, bytesRead); bytesRead = is.read(buffer); } } finally { if (is != null) is.close(); if (os != null) os.close(); } } } catch (IOException e) { context.log("Error copying resources", e); //$NON-NLS-1$ } } } /** * deleteDirectory is a convenience method to recursively delete a directory * @param directory - the directory to delete. * @return was the delete succesful */ protected static boolean deleteDirectory(File directory) { if (directory.exists() && directory.isDirectory()) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return directory.delete(); } /** * Used when to set the ContextClassLoader when the BridgeServlet delegates to a Servlet * inside the framework * @return a Classloader with the OSGi framework's context classloader. */ public synchronized ClassLoader getFrameworkContextClassLoader() { return frameworkContextClassLoader; } /** * Platfom Directory is where the OSGi software is installed * @return the framework install location */ protected synchronized File getPlatformDirectory() { return platformDirectory; } /** * loadProperties is a convenience method to load properties from a servlet context resource * @param resource - The target to read properties from * @return the properties */ protected Properties loadProperties(String resource) { Properties result = new Properties(); InputStream in = null; try { URL location = context.getResource(resource); if (location != null) { in = location.openStream(); result.load(in); } } catch (MalformedURLException e) { // no url to load from } catch (IOException e) { // its ok if there is no file } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } } return result; } /*************************************************************************** * See org.eclipse.core.launcher [copy of searchFor, findMax, * compareVersion, getVersionElements] TODO: If these methods were made * public and static we could use them directly **************************************************************************/ /** * Searches for the given target directory starting in the "plugins" subdirectory * of the given location. If one is found then this location is returned; * otherwise an exception is thrown. * @param target * * @return the location where target directory was found * @param start the location to begin searching */ protected String searchFor(final String target, String start) { FileFilter filter = new FileFilter() { public boolean accept(File candidate) { return candidate.getName().equals(target) || candidate.getName().startsWith(target + "_"); //$NON-NLS-1$ } }; File[] candidates = new File(start).listFiles(filter); if (candidates == null) return null; String[] arrays = new String[candidates.length]; for (int i = 0; i < arrays.length; i++) { arrays[i] = candidates[i].getName(); } int result = findMax(arrays); if (result == -1) return null; return candidates[result].getAbsolutePath().replace(File.separatorChar, '/') + (candidates[result].isDirectory() ? "/" : ""); //$NON-NLS-1$//$NON-NLS-2$ } protected int findMax(String[] candidates) { int result = -1; Object maxVersion = null; for (int i = 0; i < candidates.length; i++) { String name = candidates[i]; String version = ""; //$NON-NLS-1$ // Note: directory with version suffix is always > than directory without version suffix int index = name.indexOf('_'); if (index != -1) version = name.substring(index + 1); Object currentVersion = getVersionElements(version); if (maxVersion == null) { result = i; maxVersion = currentVersion; } else { if (compareVersion((Object[]) maxVersion, (Object[]) currentVersion) < 0) { result = i; maxVersion = currentVersion; } } } return result; } /** * Compares version strings. * @param left * @param right * @return result of comparison, as integer; * <code><0</code> if left < right; * <code>0</code> if left == right; * <code>>0</code> if left > right; */ private int compareVersion(Object[] left, Object[] right) { int result = ((Integer) left[0]).compareTo((Integer) right[0]); // compare major if (result != 0) return result; result = ((Integer) left[1]).compareTo((Integer) right[1]); // compare minor if (result != 0) return result; result = ((Integer) left[2]).compareTo((Integer) right[2]); // compare service if (result != 0) return result; return ((String) left[3]).compareTo((String) right[3]); // compare qualifier } /** * Do a quick parse of version identifier so its elements can be correctly compared. * If we are unable to parse the full version, remaining elements are initialized * with suitable defaults. * @param version * @return an array of size 4; first three elements are of type Integer (representing * major, minor and service) and the fourth element is of type String (representing * qualifier). Note, that returning anything else will cause exceptions in the caller. */ private Object[] getVersionElements(String version) { if (version.endsWith(".jar")) //$NON-NLS-1$ version = version.substring(0, version.length() - 4); Object[] result = {new Integer(0), new Integer(0), new Integer(0), ""}; //$NON-NLS-1$ StringTokenizer t = new StringTokenizer(version, "."); //$NON-NLS-1$ String token; int i = 0; while (t.hasMoreTokens() && i < 4) { token = t.nextToken(); if (i < 3) { // major, minor or service ... numeric values try { result[i++] = new Integer(token); } catch (Exception e) { // invalid number format - use default numbers (0) for the rest break; } } else { // qualifier ... string value result[i++] = token; } } return result; } /** * The ChildFirstURLClassLoader alters regular ClassLoader delegation and will check the URLs * used in its initialization for matching classes before delegating to it's parent. * Sometimes also referred to as a ParentLastClassLoader */ protected class ChildFirstURLClassLoader extends URLClassLoader { public ChildFirstURLClassLoader(URL[] urls) { super(urls); } public ChildFirstURLClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); } public ChildFirstURLClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) { super(urls, parent, factory); } public URL getResource(String name) { URL resource = findResource(name); if (resource == null) { ClassLoader parent = getParent(); if (parent != null) resource = parent.getResource(name); } return resource; } protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Class clazz = findLoadedClass(name); if (clazz == null) { try { clazz = findClass(name); } catch (ClassNotFoundException e) { ClassLoader parent = getParent(); if (parent != null) clazz = parent.loadClass(name); else clazz = getSystemClassLoader().loadClass(name); } } if (resolve) resolveClass(clazz); return clazz; } } }
true
true
protected Map buildInitialPropertyMap() { Map initialPropertyMap = new HashMap(); Properties launchProperties = loadProperties(RESOURCE_BASE + LAUNCH_INI); for (Iterator it = launchProperties.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); if (key.endsWith("*")) { if (value.equals(NULL_IDENTIFIER)) { clearPrefixedSystemProperties(key.substring(0, key.length() -1), initialPropertyMap); } } else if (value.equals(NULL_IDENTIFIER)) initialPropertyMap.put(key, null); else initialPropertyMap.put(entry.getKey(), entry.getValue()); } try { // install.area if not specified if (initialPropertyMap.get(OSGI_INSTALL_AREA) == null) initialPropertyMap.put(OSGI_INSTALL_AREA, platformDirectory.toURL().toExternalForm()); // configuration.area if not specified if (initialPropertyMap.get(OSGI_CONFIGURATION_AREA) == null) { File configurationDirectory = new File(platformDirectory, "configuration"); //$NON-NLS-1$ if (!configurationDirectory.exists()) { configurationDirectory.mkdirs(); } initialPropertyMap.put(OSGI_CONFIGURATION_AREA, configurationDirectory.toURL().toExternalForm()); } // instance.area if not specified if (initialPropertyMap.get(OSGI_INSTANCE_AREA) == null) { File workspaceDirectory = new File(platformDirectory, "workspace"); //$NON-NLS-1$ if (!workspaceDirectory.exists()) { workspaceDirectory.mkdirs(); } initialPropertyMap.put(OSGI_INSTANCE_AREA, workspaceDirectory.toURL().toExternalForm()); } // osgi.framework if not specified if (initialPropertyMap.get(OSGI_FRAMEWORK) == null) { // search for osgi.framework in osgi.install.area String installArea = (String) initialPropertyMap.get(OSGI_INSTALL_AREA); // only support file type URLs for install area if (installArea.startsWith(FILE_SCHEME)) installArea = installArea.substring(FILE_SCHEME.length()); String path = new File(installArea, "plugins").toString(); //$NON-NLS-1$ path = searchFor(FRAMEWORK_BUNDLE_NAME, path); if (path == null) throw new RuntimeException("Could not find framework"); //$NON-NLS-1$ initialPropertyMap.put(OSGI_FRAMEWORK, new File(path).toURL().toExternalForm()); } } catch (MalformedURLException e) { throw new RuntimeException("Error establishing location"); //$NON-NLS-1$ } return initialPropertyMap; }
protected Map buildInitialPropertyMap() { Map initialPropertyMap = new HashMap(); Properties launchProperties = loadProperties(RESOURCE_BASE + LAUNCH_INI); for (Iterator it = launchProperties.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); if (key.endsWith("*")) { //$NON-NLS-1$ if (value.equals(NULL_IDENTIFIER)) { clearPrefixedSystemProperties(key.substring(0, key.length() -1), initialPropertyMap); } } else if (value.equals(NULL_IDENTIFIER)) initialPropertyMap.put(key, null); else initialPropertyMap.put(entry.getKey(), entry.getValue()); } try { // install.area if not specified if (initialPropertyMap.get(OSGI_INSTALL_AREA) == null) initialPropertyMap.put(OSGI_INSTALL_AREA, platformDirectory.toURL().toExternalForm()); // configuration.area if not specified if (initialPropertyMap.get(OSGI_CONFIGURATION_AREA) == null) { File configurationDirectory = new File(platformDirectory, "configuration"); //$NON-NLS-1$ if (!configurationDirectory.exists()) { configurationDirectory.mkdirs(); } initialPropertyMap.put(OSGI_CONFIGURATION_AREA, configurationDirectory.toURL().toExternalForm()); } // instance.area if not specified if (initialPropertyMap.get(OSGI_INSTANCE_AREA) == null) { File workspaceDirectory = new File(platformDirectory, "workspace"); //$NON-NLS-1$ if (!workspaceDirectory.exists()) { workspaceDirectory.mkdirs(); } initialPropertyMap.put(OSGI_INSTANCE_AREA, workspaceDirectory.toURL().toExternalForm()); } // osgi.framework if not specified if (initialPropertyMap.get(OSGI_FRAMEWORK) == null) { // search for osgi.framework in osgi.install.area String installArea = (String) initialPropertyMap.get(OSGI_INSTALL_AREA); // only support file type URLs for install area if (installArea.startsWith(FILE_SCHEME)) installArea = installArea.substring(FILE_SCHEME.length()); String path = new File(installArea, "plugins").toString(); //$NON-NLS-1$ path = searchFor(FRAMEWORK_BUNDLE_NAME, path); if (path == null) throw new RuntimeException("Could not find framework"); //$NON-NLS-1$ initialPropertyMap.put(OSGI_FRAMEWORK, new File(path).toURL().toExternalForm()); } } catch (MalformedURLException e) { throw new RuntimeException("Error establishing location"); //$NON-NLS-1$ } return initialPropertyMap; }
diff --git a/ddms/libs/ddmuilib/src/com/android/ddmuilib/ScreenShotDialog.java b/ddms/libs/ddmuilib/src/com/android/ddmuilib/ScreenShotDialog.java index 88f1ad1ee..b60c837f8 100644 --- a/ddms/libs/ddmuilib/src/com/android/ddmuilib/ScreenShotDialog.java +++ b/ddms/libs/ddmuilib/src/com/android/ddmuilib/ScreenShotDialog.java @@ -1,285 +1,285 @@ /* * 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.ddmuilib; import com.android.ddmlib.IDevice; import com.android.ddmlib.Log; import com.android.ddmlib.RawImage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.ImageLoader; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import java.io.IOException; /** * Gather a screen shot from the device and save it to a file. */ public class ScreenShotDialog extends Dialog { private Label mBusyLabel; private Label mImageLabel; private Button mSave; private IDevice mDevice; private RawImage mRawImage; /** * Create with default style. */ public ScreenShotDialog(Shell parent) { this(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); } /** * Create with app-defined style. */ public ScreenShotDialog(Shell parent, int style) { super(parent, style); } /** * Prepare and display the dialog. * @param device The {@link IDevice} from which to get the screenshot. */ public void open(IDevice device) { mDevice = device; Shell parent = getParent(); Shell shell = new Shell(parent, getStyle()); shell.setText("Device Screen Capture"); createContents(shell); shell.pack(); shell.open(); updateDeviceImage(shell); Display display = parent.getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } } /* * Create the screen capture dialog contents. */ private void createContents(final Shell shell) { GridData data; final int colCount = 4; shell.setLayout(new GridLayout(colCount, true)); // "refresh" button Button refresh = new Button(shell, SWT.PUSH); refresh.setText("Refresh"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; refresh.setLayoutData(data); refresh.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateDeviceImage(shell); } }); // "rotate" button Button rotate = new Button(shell, SWT.PUSH); rotate.setText("Rotate"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; rotate.setLayoutData(data); rotate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (mRawImage != null) { mRawImage = mRawImage.getRotated(); updateImageDisplay(shell); } } }); // "save" button mSave = new Button(shell, SWT.PUSH); mSave.setText("Save"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; mSave.setLayoutData(data); mSave.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { saveImage(shell); } }); // "done" button Button done = new Button(shell, SWT.PUSH); done.setText("Done"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; done.setLayoutData(data); done.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { shell.close(); } }); // title/"capturing" label mBusyLabel = new Label(shell, SWT.NONE); mBusyLabel.setText("Preparing..."); data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - data.horizontalSpan = 3; + data.horizontalSpan = colCount; mBusyLabel.setLayoutData(data); // space for the image mImageLabel = new Label(shell, SWT.BORDER); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); - data.horizontalSpan = 3; + data.horizontalSpan = colCount; mImageLabel.setLayoutData(data); Display display = shell.getDisplay(); mImageLabel.setImage(ImageHelper.createPlaceHolderArt( display, 50, 50, display.getSystemColor(SWT.COLOR_BLUE))); shell.setDefaultButton(done); } /** * Captures a new image from the device, and display it. */ private void updateDeviceImage(Shell shell) { mBusyLabel.setText("Capturing..."); // no effect shell.setCursor(shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT)); mRawImage = getDeviceImage(); updateImageDisplay(shell); } /** * Updates the display with {@link #mRawImage}. * @param shell */ private void updateImageDisplay(Shell shell) { Image image; if (mRawImage == null) { Display display = shell.getDisplay(); image = ImageHelper.createPlaceHolderArt( display, 320, 240, display.getSystemColor(SWT.COLOR_BLUE)); mSave.setEnabled(false); mBusyLabel.setText("Screen not available"); } else { // convert raw data to an Image. PaletteData palette = new PaletteData( mRawImage.getRedMask(), mRawImage.getGreenMask(), mRawImage.getBlueMask()); ImageData imageData = new ImageData(mRawImage.width, mRawImage.height, mRawImage.bpp, palette, 1, mRawImage.data); image = new Image(getParent().getDisplay(), imageData); mSave.setEnabled(true); mBusyLabel.setText("Captured image:"); } mImageLabel.setImage(image); mImageLabel.pack(); shell.pack(); // there's no way to restore old cursor; assume it's ARROW shell.setCursor(shell.getDisplay().getSystemCursor(SWT.CURSOR_ARROW)); } /** * Grabs an image from an ADB-connected device and returns it as a {@link RawImage}. */ private RawImage getDeviceImage() { try { return mDevice.getScreenshot(); } catch (IOException ioe) { Log.w("ddms", "Unable to get frame buffer: " + ioe.getMessage()); return null; } } /* * Prompt the user to save the image to disk. */ private void saveImage(Shell shell) { FileDialog dlg = new FileDialog(shell, SWT.SAVE); String fileName; dlg.setText("Save image..."); dlg.setFileName("device.png"); dlg.setFilterPath(DdmUiPreferences.getStore().getString("lastImageSaveDir")); dlg.setFilterNames(new String[] { "PNG Files (*.png)" }); dlg.setFilterExtensions(new String[] { "*.png" //$NON-NLS-1$ }); fileName = dlg.open(); if (fileName != null) { DdmUiPreferences.getStore().setValue("lastImageSaveDir", dlg.getFilterPath()); Log.d("ddms", "Saving image to " + fileName); ImageData imageData = mImageLabel.getImage().getImageData(); try { WritePng.savePng(fileName, imageData); } catch (IOException ioe) { Log.w("ddms", "Unable to save " + fileName + ": " + ioe); } if (false) { ImageLoader loader = new ImageLoader(); loader.data = new ImageData[] { imageData }; // PNG writing not available until 3.3? See bug at: // https://bugs.eclipse.org/bugs/show_bug.cgi?id=24697 // GIF writing only works for 8 bits // JPEG uses lossy compression // BMP has screwed-up colors loader.save(fileName, SWT.IMAGE_JPEG); } } } }
false
true
private void createContents(final Shell shell) { GridData data; final int colCount = 4; shell.setLayout(new GridLayout(colCount, true)); // "refresh" button Button refresh = new Button(shell, SWT.PUSH); refresh.setText("Refresh"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; refresh.setLayoutData(data); refresh.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateDeviceImage(shell); } }); // "rotate" button Button rotate = new Button(shell, SWT.PUSH); rotate.setText("Rotate"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; rotate.setLayoutData(data); rotate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (mRawImage != null) { mRawImage = mRawImage.getRotated(); updateImageDisplay(shell); } } }); // "save" button mSave = new Button(shell, SWT.PUSH); mSave.setText("Save"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; mSave.setLayoutData(data); mSave.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { saveImage(shell); } }); // "done" button Button done = new Button(shell, SWT.PUSH); done.setText("Done"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; done.setLayoutData(data); done.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { shell.close(); } }); // title/"capturing" label mBusyLabel = new Label(shell, SWT.NONE); mBusyLabel.setText("Preparing..."); data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); data.horizontalSpan = 3; mBusyLabel.setLayoutData(data); // space for the image mImageLabel = new Label(shell, SWT.BORDER); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.horizontalSpan = 3; mImageLabel.setLayoutData(data); Display display = shell.getDisplay(); mImageLabel.setImage(ImageHelper.createPlaceHolderArt( display, 50, 50, display.getSystemColor(SWT.COLOR_BLUE))); shell.setDefaultButton(done); }
private void createContents(final Shell shell) { GridData data; final int colCount = 4; shell.setLayout(new GridLayout(colCount, true)); // "refresh" button Button refresh = new Button(shell, SWT.PUSH); refresh.setText("Refresh"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; refresh.setLayoutData(data); refresh.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateDeviceImage(shell); } }); // "rotate" button Button rotate = new Button(shell, SWT.PUSH); rotate.setText("Rotate"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; rotate.setLayoutData(data); rotate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (mRawImage != null) { mRawImage = mRawImage.getRotated(); updateImageDisplay(shell); } } }); // "save" button mSave = new Button(shell, SWT.PUSH); mSave.setText("Save"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; mSave.setLayoutData(data); mSave.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { saveImage(shell); } }); // "done" button Button done = new Button(shell, SWT.PUSH); done.setText("Done"); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.widthHint = 80; done.setLayoutData(data); done.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { shell.close(); } }); // title/"capturing" label mBusyLabel = new Label(shell, SWT.NONE); mBusyLabel.setText("Preparing..."); data = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); data.horizontalSpan = colCount; mBusyLabel.setLayoutData(data); // space for the image mImageLabel = new Label(shell, SWT.BORDER); data = new GridData(GridData.HORIZONTAL_ALIGN_CENTER); data.horizontalSpan = colCount; mImageLabel.setLayoutData(data); Display display = shell.getDisplay(); mImageLabel.setImage(ImageHelper.createPlaceHolderArt( display, 50, 50, display.getSystemColor(SWT.COLOR_BLUE))); shell.setDefaultButton(done); }
diff --git a/src/java/com/eviware/soapui/support/xml/SyntaxEditorUtil.java b/src/java/com/eviware/soapui/support/xml/SyntaxEditorUtil.java index 711383df2..9aa310099 100644 --- a/src/java/com/eviware/soapui/support/xml/SyntaxEditorUtil.java +++ b/src/java/com/eviware/soapui/support/xml/SyntaxEditorUtil.java @@ -1,128 +1,128 @@ package com.eviware.soapui.support.xml; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JPopupMenu; import javax.swing.JSeparator; import javax.swing.KeyStroke; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rtextarea.RTextScrollPane; import com.eviware.soapui.support.UISupport; import com.eviware.soapui.support.xml.actions.EnableLineNumbersAction; import com.eviware.soapui.support.xml.actions.FormatXmlAction; import com.eviware.soapui.support.xml.actions.GoToLineAction; import com.eviware.soapui.support.xml.actions.InsertBase64FileTextAreaAction; import com.eviware.soapui.support.xml.actions.LoadXmlTextAreaAction; import com.eviware.soapui.support.xml.actions.SaveXmlTextAreaAction; import com.eviware.soapui.ui.support.FindAndReplaceDialogView; public class SyntaxEditorUtil { public static RSyntaxTextArea createDefaultXmlSyntaxTextArea() { return createDefaultSyntaxTextArea( SyntaxConstants.SYNTAX_STYLE_XML ); } public static RSyntaxTextArea createDefaultJsonSyntaxTextArea() { return createDefaultSyntaxTextArea( SyntaxConstants.SYNTAX_STYLE_XML ); } public static RSyntaxTextArea createDefaultJavaScriptSyntaxTextArea() { return createDefaultSyntaxTextArea( SyntaxConstants.SYNTAX_STYLE_JAVASCRIPT ); } public static RSyntaxTextArea createDefaultSQLSyntaxTextArea() { return createDefaultSyntaxTextArea( SyntaxConstants.SYNTAX_STYLE_SQL ); } private static RSyntaxTextArea createDefaultSyntaxTextArea( String type ) { RSyntaxTextArea textArea = new RSyntaxTextArea(); textArea.setSyntaxEditingStyle( type ); textArea.setFont( UISupport.getEditorFont() ); textArea.setCodeFoldingEnabled( true ); textArea.setAntiAliasingEnabled( true ); textArea.setCaretPosition( 0 ); textArea.setBorder( BorderFactory.createMatteBorder( 0, 2, 0, 0, Color.WHITE ) ); return textArea; } public static RSyntaxTextArea addDefaultActions( RSyntaxTextArea editor, RTextScrollPane scrollPane, boolean readOnly ) { JPopupMenu popupMenu = editor.getPopupMenu(); SaveXmlTextAreaAction saveXmlTextAreaAction = new SaveXmlTextAreaAction( editor, "Save" ); EnableLineNumbersAction enableLineNumbersAction = new EnableLineNumbersAction( scrollPane, "Toggle Line Numbers" ); GoToLineAction goToLineAction = new GoToLineAction( editor, "Go To Line" ); int cnt = popupMenu.getComponentCount(); for( int i = cnt - 1; i >= 0; i-- ) { if( popupMenu.getComponent( i ) instanceof JSeparator ) { popupMenu.remove( popupMenu.getComponent( i ) ); } } FormatXmlAction formatXmlAction = null; if( !readOnly ) { - formatXmlAction = formatXmlAction = new FormatXmlAction( editor ); - FindAndReplaceDialogView findAndReplaceDialog = findAndReplaceDialog = new FindAndReplaceDialogView( editor ); + formatXmlAction = new FormatXmlAction( editor ); + FindAndReplaceDialogView findAndReplaceDialog = new FindAndReplaceDialogView( editor ); popupMenu.insert( formatXmlAction, 1 ); popupMenu.addSeparator(); popupMenu.add( findAndReplaceDialog ); editor.getInputMap().put( KeyStroke.getKeyStroke( "F3" ), findAndReplaceDialog ); } popupMenu.addSeparator(); popupMenu.add( goToLineAction ); popupMenu.add( enableLineNumbersAction ); popupMenu.addSeparator(); popupMenu.add( saveXmlTextAreaAction ); LoadXmlTextAreaAction loadXmlTextAreaAction = null; InsertBase64FileTextAreaAction insertBase64FileTextAreaAction = null; if( !readOnly ) { loadXmlTextAreaAction = new LoadXmlTextAreaAction( editor, "Load" ); insertBase64FileTextAreaAction = new InsertBase64FileTextAreaAction( editor, "Insert File as Base64" ); popupMenu.add( loadXmlTextAreaAction ); popupMenu.add( insertBase64FileTextAreaAction ); } if( UISupport.isMac() ) { editor.getInputMap().put( KeyStroke.getKeyStroke( "meta S" ), saveXmlTextAreaAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "control L" ), enableLineNumbersAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "control meta L" ), goToLineAction ); if( !readOnly ) { editor.getInputMap().put( KeyStroke.getKeyStroke( "shift meta F" ), formatXmlAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "meta L" ), loadXmlTextAreaAction ); } } else { editor.getInputMap().put( KeyStroke.getKeyStroke( "ctrl S" ), saveXmlTextAreaAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "alt L" ), enableLineNumbersAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "control alt L" ), goToLineAction ); if( !readOnly ) { editor.getInputMap().put( KeyStroke.getKeyStroke( "alt F" ), formatXmlAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "ctrl L" ), loadXmlTextAreaAction ); } } if( !readOnly ) { } return editor; } }
true
true
public static RSyntaxTextArea addDefaultActions( RSyntaxTextArea editor, RTextScrollPane scrollPane, boolean readOnly ) { JPopupMenu popupMenu = editor.getPopupMenu(); SaveXmlTextAreaAction saveXmlTextAreaAction = new SaveXmlTextAreaAction( editor, "Save" ); EnableLineNumbersAction enableLineNumbersAction = new EnableLineNumbersAction( scrollPane, "Toggle Line Numbers" ); GoToLineAction goToLineAction = new GoToLineAction( editor, "Go To Line" ); int cnt = popupMenu.getComponentCount(); for( int i = cnt - 1; i >= 0; i-- ) { if( popupMenu.getComponent( i ) instanceof JSeparator ) { popupMenu.remove( popupMenu.getComponent( i ) ); } } FormatXmlAction formatXmlAction = null; if( !readOnly ) { formatXmlAction = formatXmlAction = new FormatXmlAction( editor ); FindAndReplaceDialogView findAndReplaceDialog = findAndReplaceDialog = new FindAndReplaceDialogView( editor ); popupMenu.insert( formatXmlAction, 1 ); popupMenu.addSeparator(); popupMenu.add( findAndReplaceDialog ); editor.getInputMap().put( KeyStroke.getKeyStroke( "F3" ), findAndReplaceDialog ); } popupMenu.addSeparator(); popupMenu.add( goToLineAction ); popupMenu.add( enableLineNumbersAction ); popupMenu.addSeparator(); popupMenu.add( saveXmlTextAreaAction ); LoadXmlTextAreaAction loadXmlTextAreaAction = null; InsertBase64FileTextAreaAction insertBase64FileTextAreaAction = null; if( !readOnly ) { loadXmlTextAreaAction = new LoadXmlTextAreaAction( editor, "Load" ); insertBase64FileTextAreaAction = new InsertBase64FileTextAreaAction( editor, "Insert File as Base64" ); popupMenu.add( loadXmlTextAreaAction ); popupMenu.add( insertBase64FileTextAreaAction ); } if( UISupport.isMac() ) { editor.getInputMap().put( KeyStroke.getKeyStroke( "meta S" ), saveXmlTextAreaAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "control L" ), enableLineNumbersAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "control meta L" ), goToLineAction ); if( !readOnly ) { editor.getInputMap().put( KeyStroke.getKeyStroke( "shift meta F" ), formatXmlAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "meta L" ), loadXmlTextAreaAction ); } } else { editor.getInputMap().put( KeyStroke.getKeyStroke( "ctrl S" ), saveXmlTextAreaAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "alt L" ), enableLineNumbersAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "control alt L" ), goToLineAction ); if( !readOnly ) { editor.getInputMap().put( KeyStroke.getKeyStroke( "alt F" ), formatXmlAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "ctrl L" ), loadXmlTextAreaAction ); } } if( !readOnly ) { } return editor; }
public static RSyntaxTextArea addDefaultActions( RSyntaxTextArea editor, RTextScrollPane scrollPane, boolean readOnly ) { JPopupMenu popupMenu = editor.getPopupMenu(); SaveXmlTextAreaAction saveXmlTextAreaAction = new SaveXmlTextAreaAction( editor, "Save" ); EnableLineNumbersAction enableLineNumbersAction = new EnableLineNumbersAction( scrollPane, "Toggle Line Numbers" ); GoToLineAction goToLineAction = new GoToLineAction( editor, "Go To Line" ); int cnt = popupMenu.getComponentCount(); for( int i = cnt - 1; i >= 0; i-- ) { if( popupMenu.getComponent( i ) instanceof JSeparator ) { popupMenu.remove( popupMenu.getComponent( i ) ); } } FormatXmlAction formatXmlAction = null; if( !readOnly ) { formatXmlAction = new FormatXmlAction( editor ); FindAndReplaceDialogView findAndReplaceDialog = new FindAndReplaceDialogView( editor ); popupMenu.insert( formatXmlAction, 1 ); popupMenu.addSeparator(); popupMenu.add( findAndReplaceDialog ); editor.getInputMap().put( KeyStroke.getKeyStroke( "F3" ), findAndReplaceDialog ); } popupMenu.addSeparator(); popupMenu.add( goToLineAction ); popupMenu.add( enableLineNumbersAction ); popupMenu.addSeparator(); popupMenu.add( saveXmlTextAreaAction ); LoadXmlTextAreaAction loadXmlTextAreaAction = null; InsertBase64FileTextAreaAction insertBase64FileTextAreaAction = null; if( !readOnly ) { loadXmlTextAreaAction = new LoadXmlTextAreaAction( editor, "Load" ); insertBase64FileTextAreaAction = new InsertBase64FileTextAreaAction( editor, "Insert File as Base64" ); popupMenu.add( loadXmlTextAreaAction ); popupMenu.add( insertBase64FileTextAreaAction ); } if( UISupport.isMac() ) { editor.getInputMap().put( KeyStroke.getKeyStroke( "meta S" ), saveXmlTextAreaAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "control L" ), enableLineNumbersAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "control meta L" ), goToLineAction ); if( !readOnly ) { editor.getInputMap().put( KeyStroke.getKeyStroke( "shift meta F" ), formatXmlAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "meta L" ), loadXmlTextAreaAction ); } } else { editor.getInputMap().put( KeyStroke.getKeyStroke( "ctrl S" ), saveXmlTextAreaAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "alt L" ), enableLineNumbersAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "control alt L" ), goToLineAction ); if( !readOnly ) { editor.getInputMap().put( KeyStroke.getKeyStroke( "alt F" ), formatXmlAction ); editor.getInputMap().put( KeyStroke.getKeyStroke( "ctrl L" ), loadXmlTextAreaAction ); } } if( !readOnly ) { } return editor; }
diff --git a/contrib/Karma.java b/contrib/Karma.java index 731561b..32d9be5 100644 --- a/contrib/Karma.java +++ b/contrib/Karma.java @@ -1,418 +1,418 @@ import org.uwcs.choob.*; import org.uwcs.choob.modules.*; import org.uwcs.choob.support.*; import org.uwcs.choob.support.events.*; import java.sql.*; import java.util.*; import java.util.regex.*; import java.io.*; public class KarmaObject { public int id; public String string; public int up; public int down; public int value; boolean increase; } public class KarmaReasonObject { public int id; public String string; public int direction; public String reason; } public class Karma { // Java-- A better regex would be: (")?((?(1)(?:[ \\./a-zA-Z0-9_-]{2,})|(?:[\\./a-zA-Z0-9_-]{2,})))(?(1)")((?:\\+\\+)|(?:\\-\\-)) public String filterKarmaRegex = "(?x:\\b(?:" + "(" + "[\\./a-zA-Z0-9_-]{3,}" // 3 chars anywhere + "|" + "^[\\./a-zA-Z0-9_-]+" // Or anything at the start + ")" + "( \\+\\+ | \\-\\- )" // The actual karma change + ")\\B)"; public String[] helpCommandReason = { "Find out why something sucks or rocks." // XXX Add syntax here. }; public void commandReason( Message mes, Modules mods, IRCInterface irc ) throws ChoobException { Matcher whyMatch = Pattern.compile(".*(do|does)? ([\\./a-zA-Z0-9_-]+) (suck|rulz0r)\\?$") .matcher(mes.getMessage()); if (whyMatch.matches()) { List<KarmaReasonObject> results; results = mods.odb.retrieve(KarmaReasonObject.class, "WHERE string = '" + whyMatch.group(2) + "' AND direction = '" + (whyMatch.group(3).toLowerCase().equals("suck") ? -1 : 1) + "'"); if (results.size() == 0) { irc.sendContextReply(mes, whyMatch.group(2) + " " + whyMatch.group(1) + " NOT " + whyMatch.group(3) + "!"); } else { KarmaReasonObject reason = results.get((new Random()).nextInt(results.size())); irc.sendContextReply(mes, whyMatch.group(2) + " " + whyMatch.group(3) + (reason.string.endsWith("s") ? "" : "s") + ": " + reason.reason); } return; } } public String[] helpTopics = { "Using" }; public String[] helpUsing = { "To change the karma of something, simply send the message" + " 'something--' or 'something++'. You can also specify a reason, by" + " sending a line starting with a karma change then giving a reason," + " like: 'ntl-- they suck'." }; public void filterKarma( Message mes, Modules mods, IRCInterface irc ) throws ChoobException { if (mes instanceof PrivateEvent) { irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!"); return; } String special=""; ArrayList<KarmaObject> karmaObjs = new ArrayList(); HashSet used = new HashSet(); Matcher reasonMatch = Pattern.compile("(?x:^" + "([\\./a-zA-Z0-9_-]+)" // The karma string. + "(\\+\\+|\\-\\-)" // Up or down. + "\\s+(?:because)?" // Optional because. + "\\(? (.+?) \\)?" // The reason, optionally in brackets. + "$)") .matcher(mes.getMessage()); if (reasonMatch.matches()) { KarmaReasonObject reason = new KarmaReasonObject(); reason.string = reasonMatch.group(1); reason.direction = (reasonMatch.group(2).equals("++") ? 1 : -1); reason.reason = reasonMatch.group(3); mods.odb.save(reason); - special="*"; + special=" (with reason)"; } Matcher karmaMatch = Pattern.compile(filterKarmaRegex).matcher(mes.getMessage()); String nick=mods.nick.getBestPrimaryNick(mes.getNick()); List<String> names = new ArrayList<String>(); while (karmaMatch.find()) { String name = karmaMatch.group(1); name=name.replaceAll("-+","-"); // Have we already done this? if (used.contains(name.toLowerCase())) continue; used.add(name.toLowerCase()); boolean increase = karmaMatch.group(2).equals("++"); if (name.equalsIgnoreCase(nick)) increase=false; List<KarmaObject> results = retrieveKarmaObjects("WHERE string = '" + name + "'", mods); KarmaObject karmaObj; if (results.size() == 0) { karmaObj = new KarmaObject(); karmaObj.string = name; if (increase) { karmaObj.up=1; karmaObj.value=1; } else { karmaObj.down=1; karmaObj.value=-1; } } else { karmaObj = results.get(0); if (increase) { karmaObj.up++; karmaObj.value++; } else { karmaObj.down++; karmaObj.value--; } } karmaObj.increase = increase; karmaObjs.add(karmaObj); names.add(name); } saveKarmaObjects(karmaObjs, mods); // Generate a pretty reply, all actual processing is done now: if (karmaObjs.size() == 1) { KarmaObject info = karmaObjs.get(0); irc.sendContextReply(mes, (info.increase ? "Karma" : "Less karma") + " to " + names.get(0) + special + ", " + (info.increase ? "giving" : "leaving") + " a karma of " + info.value + "."); return; } StringBuffer output = new StringBuffer("Karma adjustments: "); for (int i=0; i<karmaObjs.size(); i++) { KarmaObject info = karmaObjs.get(i); output.append(names.get(i)); output.append(info.increase ? " up" : " down"); output.append(" (now " + info.value + ")"); if (i != karmaObjs.size() - 1) { if (i == karmaObjs.size() - 2) output.append(" and "); else output.append(", "); } } output.append("."); irc.sendContextReply( mes, output.toString()); } private String postfix(int n) { switch (n%10) { case 1: return "st"; case 2: return "nd"; case 3: return "rd"; } return "th"; } private void commandScores(Message mes, Modules mods, IRCInterface irc, boolean asc) throws ChoobException { List<KarmaObject> karmaObjs = retrieveKarmaObjects("SORT " + (asc ? "ASC" : "DESC") + " INTEGER value LIMIT (5)", mods); StringBuffer output = new StringBuffer((asc ? "Low" : "High" ) + " Scores: "); for (int i=0; i<karmaObjs.size(); i++) { output.append(String.valueOf(i+1) + postfix(i+1)); output.append(": "); output.append(karmaObjs.get(i).string); output.append(" (with " + karmaObjs.get(i).value + ")"); if (i != karmaObjs.size() - 1) { if (i == karmaObjs.size() - 2) output.append(" and "); else output.append(", "); } } output.append("."); irc.sendContextReply( mes, output.toString()); } public String[] helpCommandHighScores = { "Find out what has the highest karma" }; public void commandHighScores(Message mes, Modules mods, IRCInterface irc) throws ChoobException { commandScores(mes, mods, irc, false); } public String[] helpCommandLowScores = { "Find out what has the lowest karma" }; public void commandLowScores(Message mes, Modules mods, IRCInterface irc) throws ChoobException { commandScores(mes, mods, irc, true); } private void saveKarmaObjects (List<KarmaObject> karmaObjs, Modules mods) throws ChoobException { for (KarmaObject karmaObj: karmaObjs) if (karmaObj.id==0) mods.odb.save(karmaObj); else mods.odb.update(karmaObj); } private List<KarmaObject> retrieveKarmaObjects(String clause, Modules mods) throws ChoobException { return mods.odb.retrieve(KarmaObject.class, clause); } public String[] helpCommandGet = { "Find out the karma of some object or other.", "<Object> [<Object> ...]", "<Object> is the name of something to get the karma of" }; public void commandGet (Message mes, Modules mods, IRCInterface irc) throws ChoobException { List<String> params = mods.util.getParams( mes ); List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>(); List<String> names = new ArrayList<String>(); if (params.size()>1) for (int i=1; i<params.size(); i++) { String name = params.get(i); names.add(name); List<KarmaObject> results = retrieveKarmaObjects("WHERE string = '" + name + "'", mods); if (results.size()!=0) karmaObjs.add((KarmaObject)results.get(0)); else { KarmaObject karmaObj = new KarmaObject(); karmaObj.string = name; karmaObj.value = 0; karmaObjs.add(karmaObj); } } if (karmaObjs.size()==1) { irc.sendContextReply(mes, karmaObjs.get(0).string + " has a karma of " + karmaObjs.get(0).value + "."); return; } StringBuffer output = new StringBuffer("Karmas: "); for (int i=0; i<karmaObjs.size(); i++) { output.append(names.get(i)); output.append(": " + karmaObjs.get(i).value); if (i != karmaObjs.size() - 1) { if (i == karmaObjs.size() - 2) output.append(" and "); else output.append(", "); } } output.append("."); irc.sendContextReply( mes, output.toString()); } public String[] helpCommandSet = { "Set out the karma of some object or other.", "<Object>=<Value> [<Object>=<Value> ...]", "<Object> is the name of something to set the karma of", "<Value> is the value to set the karma to" }; public void commandSet( Message mes, Modules mods, IRCInterface irc ) throws ChoobException { mods.security.checkNickPerm(new ChoobPermission("plugins.karma.set"), mes.getNick()); List<String> params = mods.util.getParams( mes ); List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>(); List<String> names = new ArrayList<String>(); for (int i=1; i<params.size(); i++) { KarmaObject karmaObj; String param = params.get(i); String[] items = param.split("="); if (items.length != 2) { irc.sendContextReply(mes, "Bad syntax: Use OBJECT=VALUE OBJECT=VALUE ..."); return; } String name = items[0].trim(); int val; try { val = Integer.parseInt(items[1]); } catch (NumberFormatException e) { irc.sendContextReply(mes, "Bad syntax: Karma value " + items[1] + " is not a valid integer."); return; } names.add(name); List<KarmaObject> results = retrieveKarmaObjects("WHERE string = '" + name + "'", mods); if (results.size()==0) { karmaObj = new KarmaObject(); karmaObj.string = name; } else karmaObj = results.get(0); karmaObj.value = val; karmaObjs.add(karmaObj); } if (karmaObjs.size()==0) { irc.sendContextReply(mes, "You need to specify some bobdamn karma to set!"); return; } saveKarmaObjects(karmaObjs, mods); StringBuffer output = new StringBuffer("Karma adjustment"); output.append(karmaObjs.size() == 1 ? "" : "s"); output.append(": "); for (int i=0; i<karmaObjs.size(); i++) { output.append(names.get(i)); output.append(": now "); output.append(karmaObjs.get(i).value); if (i != karmaObjs.size() - 1) { if (i == karmaObjs.size() - 2) output.append(" and "); else output.append(", "); } } output.append("."); irc.sendContextReply( mes, output.toString()); } public String[] helpCommandList = { "Get a list of all karma objects.", }; public void commandList (Message mes, Modules mods, IRCInterface irc) { irc.sendContextReply(mes, "No chance, matey."); } public void webList(Modules mods, IRCInterface irc, PrintWriter out, String params, String[] user) throws ChoobException { out.println("HTTP/1.0 200 OK"); out.println("Content-Type: text/html"); out.println(); List<KarmaObject> res = retrieveKarmaObjects("WHERE 1 ORDER BY value", mods); out.println(res.size()); } }
true
true
public void filterKarma( Message mes, Modules mods, IRCInterface irc ) throws ChoobException { if (mes instanceof PrivateEvent) { irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!"); return; } String special=""; ArrayList<KarmaObject> karmaObjs = new ArrayList(); HashSet used = new HashSet(); Matcher reasonMatch = Pattern.compile("(?x:^" + "([\\./a-zA-Z0-9_-]+)" // The karma string. + "(\\+\\+|\\-\\-)" // Up or down. + "\\s+(?:because)?" // Optional because. + "\\(? (.+?) \\)?" // The reason, optionally in brackets. + "$)") .matcher(mes.getMessage()); if (reasonMatch.matches()) { KarmaReasonObject reason = new KarmaReasonObject(); reason.string = reasonMatch.group(1); reason.direction = (reasonMatch.group(2).equals("++") ? 1 : -1); reason.reason = reasonMatch.group(3); mods.odb.save(reason); special="*"; } Matcher karmaMatch = Pattern.compile(filterKarmaRegex).matcher(mes.getMessage()); String nick=mods.nick.getBestPrimaryNick(mes.getNick()); List<String> names = new ArrayList<String>(); while (karmaMatch.find()) { String name = karmaMatch.group(1); name=name.replaceAll("-+","-"); // Have we already done this? if (used.contains(name.toLowerCase())) continue; used.add(name.toLowerCase()); boolean increase = karmaMatch.group(2).equals("++"); if (name.equalsIgnoreCase(nick)) increase=false; List<KarmaObject> results = retrieveKarmaObjects("WHERE string = '" + name + "'", mods); KarmaObject karmaObj; if (results.size() == 0) { karmaObj = new KarmaObject(); karmaObj.string = name; if (increase) { karmaObj.up=1; karmaObj.value=1; } else { karmaObj.down=1; karmaObj.value=-1; } } else { karmaObj = results.get(0); if (increase) { karmaObj.up++; karmaObj.value++; } else { karmaObj.down++; karmaObj.value--; } } karmaObj.increase = increase; karmaObjs.add(karmaObj); names.add(name); } saveKarmaObjects(karmaObjs, mods); // Generate a pretty reply, all actual processing is done now: if (karmaObjs.size() == 1) { KarmaObject info = karmaObjs.get(0); irc.sendContextReply(mes, (info.increase ? "Karma" : "Less karma") + " to " + names.get(0) + special + ", " + (info.increase ? "giving" : "leaving") + " a karma of " + info.value + "."); return; } StringBuffer output = new StringBuffer("Karma adjustments: "); for (int i=0; i<karmaObjs.size(); i++) { KarmaObject info = karmaObjs.get(i); output.append(names.get(i)); output.append(info.increase ? " up" : " down"); output.append(" (now " + info.value + ")"); if (i != karmaObjs.size() - 1) { if (i == karmaObjs.size() - 2) output.append(" and "); else output.append(", "); } } output.append("."); irc.sendContextReply( mes, output.toString()); }
public void filterKarma( Message mes, Modules mods, IRCInterface irc ) throws ChoobException { if (mes instanceof PrivateEvent) { irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!"); return; } String special=""; ArrayList<KarmaObject> karmaObjs = new ArrayList(); HashSet used = new HashSet(); Matcher reasonMatch = Pattern.compile("(?x:^" + "([\\./a-zA-Z0-9_-]+)" // The karma string. + "(\\+\\+|\\-\\-)" // Up or down. + "\\s+(?:because)?" // Optional because. + "\\(? (.+?) \\)?" // The reason, optionally in brackets. + "$)") .matcher(mes.getMessage()); if (reasonMatch.matches()) { KarmaReasonObject reason = new KarmaReasonObject(); reason.string = reasonMatch.group(1); reason.direction = (reasonMatch.group(2).equals("++") ? 1 : -1); reason.reason = reasonMatch.group(3); mods.odb.save(reason); special=" (with reason)"; } Matcher karmaMatch = Pattern.compile(filterKarmaRegex).matcher(mes.getMessage()); String nick=mods.nick.getBestPrimaryNick(mes.getNick()); List<String> names = new ArrayList<String>(); while (karmaMatch.find()) { String name = karmaMatch.group(1); name=name.replaceAll("-+","-"); // Have we already done this? if (used.contains(name.toLowerCase())) continue; used.add(name.toLowerCase()); boolean increase = karmaMatch.group(2).equals("++"); if (name.equalsIgnoreCase(nick)) increase=false; List<KarmaObject> results = retrieveKarmaObjects("WHERE string = '" + name + "'", mods); KarmaObject karmaObj; if (results.size() == 0) { karmaObj = new KarmaObject(); karmaObj.string = name; if (increase) { karmaObj.up=1; karmaObj.value=1; } else { karmaObj.down=1; karmaObj.value=-1; } } else { karmaObj = results.get(0); if (increase) { karmaObj.up++; karmaObj.value++; } else { karmaObj.down++; karmaObj.value--; } } karmaObj.increase = increase; karmaObjs.add(karmaObj); names.add(name); } saveKarmaObjects(karmaObjs, mods); // Generate a pretty reply, all actual processing is done now: if (karmaObjs.size() == 1) { KarmaObject info = karmaObjs.get(0); irc.sendContextReply(mes, (info.increase ? "Karma" : "Less karma") + " to " + names.get(0) + special + ", " + (info.increase ? "giving" : "leaving") + " a karma of " + info.value + "."); return; } StringBuffer output = new StringBuffer("Karma adjustments: "); for (int i=0; i<karmaObjs.size(); i++) { KarmaObject info = karmaObjs.get(i); output.append(names.get(i)); output.append(info.increase ? " up" : " down"); output.append(" (now " + info.value + ")"); if (i != karmaObjs.size() - 1) { if (i == karmaObjs.size() - 2) output.append(" and "); else output.append(", "); } } output.append("."); irc.sendContextReply( mes, output.toString()); }
diff --git a/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java b/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java index 9052672d..dce26228 100644 --- a/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java +++ b/tools/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java @@ -1,832 +1,832 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Eclipse 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://www.eclipse.org/org/documents/epl-v10.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.eclipse.adt.internal.resources.manager; import com.android.ide.eclipse.adt.internal.resources.IResourceRepository; import com.android.ide.eclipse.adt.internal.resources.ResourceItem; import com.android.ide.eclipse.adt.internal.resources.ResourceType; import com.android.ide.eclipse.adt.internal.resources.configurations.FolderConfiguration; import com.android.ide.eclipse.adt.internal.resources.configurations.LanguageQualifier; import com.android.ide.eclipse.adt.internal.resources.configurations.RegionQualifier; import com.android.ide.eclipse.adt.internal.resources.configurations.ResourceQualifier; import com.android.ide.eclipse.adt.internal.resources.manager.files.IAbstractFolder; import com.android.layoutlib.api.IResourceValue; import com.android.layoutlib.utils.ResourceValue; import org.eclipse.core.resources.IFolder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Represents the resources of a project. This is a file view of the resources, with handling * for the alternate resource types. For a compiled view use CompiledResources. */ public class ProjectResources implements IResourceRepository { private final HashMap<ResourceFolderType, List<ResourceFolder>> mFolderMap = new HashMap<ResourceFolderType, List<ResourceFolder>>(); private final HashMap<ResourceType, List<ProjectResourceItem>> mResourceMap = new HashMap<ResourceType, List<ProjectResourceItem>>(); /** Map of (name, id) for resources of type {@link ResourceType#ID} coming from R.java */ private Map<String, Map<String, Integer>> mResourceValueMap; /** Map of (id, [name, resType]) for all resources coming from R.java */ private Map<Integer, String[]> mResIdValueToNameMap; /** Map of (int[], name) for styleable resources coming from R.java */ private Map<IntArrayWrapper, String> mStyleableValueToNameMap; /** Cached list of {@link IdResourceItem}. This is mix of IdResourceItem created by * {@link MultiResourceFile} for ids coming from XML files under res/values and * {@link IdResourceItem} created manually, from the list coming from R.java */ private final ArrayList<IdResourceItem> mIdResourceList = new ArrayList<IdResourceItem>(); private final boolean mIsFrameworkRepository; private final IntArrayWrapper mWrapper = new IntArrayWrapper(null); public ProjectResources(boolean isFrameworkRepository) { mIsFrameworkRepository = isFrameworkRepository; } public boolean isSystemRepository() { return mIsFrameworkRepository; } /** * Adds a Folder Configuration to the project. * @param type The resource type. * @param config The resource configuration. * @param folder The workspace folder object. * @return the {@link ResourceFolder} object associated to this folder. */ protected ResourceFolder add(ResourceFolderType type, FolderConfiguration config, IAbstractFolder folder) { // get the list for the resource type List<ResourceFolder> list = mFolderMap.get(type); if (list == null) { list = new ArrayList<ResourceFolder>(); ResourceFolder cf = new ResourceFolder(type, config, folder, mIsFrameworkRepository); list.add(cf); mFolderMap.put(type, list); return cf; } // look for an already existing folder configuration. for (ResourceFolder cFolder : list) { if (cFolder.mConfiguration.equals(config)) { // config already exist. Nothing to be done really, besides making sure // the IFolder object is up to date. cFolder.mFolder = folder; return cFolder; } } // If we arrive here, this means we didn't find a matching configuration. // So we add one. ResourceFolder cf = new ResourceFolder(type, config, folder, mIsFrameworkRepository); list.add(cf); return cf; } /** * Removes a {@link ResourceFolder} associated with the specified {@link IAbstractFolder}. * @param type The type of the folder * @param folder the IFolder object. */ protected void removeFolder(ResourceFolderType type, IFolder folder) { // get the list of folders for the resource type. List<ResourceFolder> list = mFolderMap.get(type); if (list != null) { int count = list.size(); for (int i = 0 ; i < count ; i++) { ResourceFolder resFolder = list.get(i); if (resFolder.getFolder().getIFolder().equals(folder)) { // we found the matching ResourceFolder. we need to remove it. list.remove(i); // we now need to invalidate this resource type. // The easiest way is to touch one of the other folders of the same type. if (list.size() > 0) { list.get(0).touch(); } else { // if the list is now empty, and we have a single ResouceType out of this // ResourceFolderType, then we are done. // However, if another ResourceFolderType can generate similar ResourceType // than this, we need to update those ResourceTypes as well. // For instance, if the last "drawable-*" folder is deleted, we need to // refresh the ResourceItem associated with ResourceType.DRAWABLE. // Those can be found in ResourceFolderType.DRAWABLE but also in // ResourceFolderType.VALUES. // If we don't find a single folder to touch, then it's fine, as the top // level items (the list of generated resource types) is not cached // (for now) // get the lists of ResourceTypes generated by this ResourceFolderType ResourceType[] resTypes = FolderTypeRelationship.getRelatedResourceTypes( type); // for each of those, make sure to find one folder to touch so that the // list of ResourceItem associated with the type is rebuilt. for (ResourceType resType : resTypes) { // get the list of folder that can generate this type ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(resType); // we only need to touch one folder in any of those (since it's one // folder per type, not per folder type). for (ResourceFolderType folderType : folderTypes) { List<ResourceFolder> resFolders = mFolderMap.get(folderType); if (resFolders != null && resFolders.size() > 0) { resFolders.get(0).touch(); break; } } } } // we're done updating/touching, we can stop break; } } } } /** * Returns a list of {@link ResourceFolder} for a specific {@link ResourceFolderType}. * @param type The {@link ResourceFolderType} */ public List<ResourceFolder> getFolders(ResourceFolderType type) { return mFolderMap.get(type); } /* (non-Javadoc) * @see com.android.ide.eclipse.editors.resources.IResourceRepository#getAvailableResourceTypes() */ public ResourceType[] getAvailableResourceTypes() { ArrayList<ResourceType> list = new ArrayList<ResourceType>(); // For each key, we check if there's a single ResourceType match. // If not, we look for the actual content to give us the resource type. for (ResourceFolderType folderType : mFolderMap.keySet()) { ResourceType types[] = FolderTypeRelationship.getRelatedResourceTypes(folderType); if (types.length == 1) { // before we add it we check if it's not already present, since a ResourceType // could be created from multiple folders, even for the folders that only create // one type of resource (drawable for instance, can be created from drawable/ and // values/) if (list.indexOf(types[0]) == -1) { list.add(types[0]); } } else { // there isn't a single resource type out of this folder, so we look for all // content. List<ResourceFolder> folders = mFolderMap.get(folderType); if (folders != null) { for (ResourceFolder folder : folders) { Collection<ResourceType> folderContent = folder.getResourceTypes(); // then we add them, but only if they aren't already in the list. for (ResourceType folderResType : folderContent) { if (list.indexOf(folderResType) == -1) { list.add(folderResType); } } } } } } // in case ResourceType.ID haven't been added yet because there's no id defined // in XML, we check on the list of compiled id resources. if (list.indexOf(ResourceType.ID) == -1 && mResourceValueMap != null) { Map<String, Integer> map = mResourceValueMap.get(ResourceType.ID.getName()); if (map != null && map.size() > 0) { list.add(ResourceType.ID); } } // at this point the list is full of ResourceType defined in the files. // We need to sort it. Collections.sort(list); return list.toArray(new ResourceType[list.size()]); } /* (non-Javadoc) * @see com.android.ide.eclipse.editors.resources.IResourceRepository#getResources(com.android.ide.eclipse.common.resources.ResourceType) */ public ProjectResourceItem[] getResources(ResourceType type) { checkAndUpdate(type); if (type == ResourceType.ID) { synchronized (mIdResourceList) { return mIdResourceList.toArray(new ProjectResourceItem[mIdResourceList.size()]); } } List<ProjectResourceItem> items = mResourceMap.get(type); return items.toArray(new ProjectResourceItem[items.size()]); } /* (non-Javadoc) * @see com.android.ide.eclipse.editors.resources.IResourceRepository#hasResources(com.android.ide.eclipse.common.resources.ResourceType) */ public boolean hasResources(ResourceType type) { checkAndUpdate(type); if (type == ResourceType.ID) { synchronized (mIdResourceList) { return mIdResourceList.size() > 0; } } List<ProjectResourceItem> items = mResourceMap.get(type); return (items != null && items.size() > 0); } /** * Returns the {@link ResourceFolder} associated with a {@link IFolder}. * @param folder The {@link IFolder} object. * @return the {@link ResourceFolder} or null if it was not found. */ public ResourceFolder getResourceFolder(IFolder folder) { for (List<ResourceFolder> list : mFolderMap.values()) { for (ResourceFolder resFolder : list) { if (resFolder.getFolder().getIFolder().equals(folder)) { return resFolder; } } } return null; } /** * Returns the {@link ResourceFile} matching the given name, {@link ResourceFolderType} and * configuration. * <p/>This only works with files generating one resource named after the file (for instance, * layouts, bitmap based drawable, xml, anims). * @return the matching file or <code>null</code> if no match was found. */ public ResourceFile getMatchingFile(String name, ResourceFolderType type, FolderConfiguration config) { // get the folders for the given type List<ResourceFolder> folders = mFolderMap.get(type); // look for folders containing a file with the given name. ArrayList<ResourceFolder> matchingFolders = new ArrayList<ResourceFolder>(); // remove the folders that do not have a file with the given name, or if their config // is incompatible. for (int i = 0 ; i < folders.size(); i++) { ResourceFolder folder = folders.get(i); if (folder.hasFile(name) == true) { matchingFolders.add(folder); } } // from those, get the folder with a config matching the given reference configuration. Resource match = findMatchingConfiguredResource(matchingFolders, config); // do we have a matching folder? if (match instanceof ResourceFolder) { // get the ResourceFile from the filename return ((ResourceFolder)match).getFile(name); } return null; } /** * Returns the resources values matching a given {@link FolderConfiguration}. * @param referenceConfig the configuration that each value must match. */ public Map<String, Map<String, IResourceValue>> getConfiguredResources( FolderConfiguration referenceConfig) { Map<String, Map<String, IResourceValue>> map = new HashMap<String, Map<String, IResourceValue>>(); // special case for Id since there's a mix of compiled id (declared inline) and id declared // in the XML files. if (mIdResourceList.size() > 0) { Map<String, IResourceValue> idMap = new HashMap<String, IResourceValue>(); String idType = ResourceType.ID.getName(); for (IdResourceItem id : mIdResourceList) { // FIXME: cache the ResourceValue! idMap.put(id.getName(), new ResourceValue(idType, id.getName(), mIsFrameworkRepository)); } map.put(ResourceType.ID.getName(), idMap); } Set<ResourceType> keys = mResourceMap.keySet(); for (ResourceType key : keys) { // we don't process ID resources since we already did it above. if (key != ResourceType.ID) { map.put(key.getName(), getConfiguredResource(key, referenceConfig)); } } return map; } /** * Loads all the resources. Essentially this forces to load the values from the * {@link ResourceFile} objects to make sure they are up to date and loaded * in {@link #mResourceMap}. */ public void loadAll() { // gets all the resource types available. ResourceType[] types = getAvailableResourceTypes(); // loop on them and load them for (ResourceType type: types) { checkAndUpdate(type); } } /** * Resolves a compiled resource id into the resource name and type * @param id * @return an array of 2 strings { name, type } or null if the id could not be resolved */ public String[] resolveResourceValue(int id) { if (mResIdValueToNameMap != null) { return mResIdValueToNameMap.get(id); } return null; } /** * Resolves a compiled resource id of type int[] into the resource name. */ public String resolveResourceValue(int[] id) { if (mStyleableValueToNameMap != null) { mWrapper.set(id); return mStyleableValueToNameMap.get(mWrapper); } return null; } /** * Returns the value of a resource by its type and name. */ public Integer getResourceValue(String type, String name) { if (mResourceValueMap != null) { Map<String, Integer> map = mResourceValueMap.get(type); if (map != null) { return map.get(name); } } return null; } /** * Returns the sorted list of languages used in the resources. */ public SortedSet<String> getLanguages() { SortedSet<String> set = new TreeSet<String>(); Collection<List<ResourceFolder>> folderList = mFolderMap.values(); for (List<ResourceFolder> folderSubList : folderList) { for (ResourceFolder folder : folderSubList) { FolderConfiguration config = folder.getConfiguration(); LanguageQualifier lang = config.getLanguageQualifier(); if (lang != null) { set.add(lang.getStringValue()); } } } return set; } /** * Returns the sorted list of regions used in the resources with the given language. * @param currentLanguage the current language the region must be associated with. */ public SortedSet<String> getRegions(String currentLanguage) { SortedSet<String> set = new TreeSet<String>(); Collection<List<ResourceFolder>> folderList = mFolderMap.values(); for (List<ResourceFolder> folderSubList : folderList) { for (ResourceFolder folder : folderSubList) { FolderConfiguration config = folder.getConfiguration(); // get the language LanguageQualifier lang = config.getLanguageQualifier(); if (lang != null && lang.getStringValue().equals(currentLanguage)) { RegionQualifier region = config.getRegionQualifier(); if (region != null) { set.add(region.getStringValue()); } } } } return set; } /** * Returns a map of (resource name, resource value) for the given {@link ResourceType}. * <p/>The values returned are taken from the resource files best matching a given * {@link FolderConfiguration}. * @param type the type of the resources. * @param referenceConfig the configuration to best match. */ private Map<String, IResourceValue> getConfiguredResource(ResourceType type, FolderConfiguration referenceConfig) { // get the resource item for the given type List<ProjectResourceItem> items = mResourceMap.get(type); // create the map HashMap<String, IResourceValue> map = new HashMap<String, IResourceValue>(); for (ProjectResourceItem item : items) { // get the source files generating this resource List<ResourceFile> list = item.getSourceFileList(); // look for the best match for the given configuration Resource match = findMatchingConfiguredResource(list, referenceConfig); if (match instanceof ResourceFile) { ResourceFile matchResFile = (ResourceFile)match; // get the value of this configured resource. IResourceValue value = matchResFile.getValue(type, item.getName()); if (value != null) { map.put(item.getName(), value); } } } return map; } /** * Returns the best matching {@link Resource}. * @param resources the list of {@link Resource} to choose from. * @param referenceConfig the {@link FolderConfiguration} to match. * @see http://d.android.com/guide/topics/resources/resources-i18n.html#best-match */ private Resource findMatchingConfiguredResource(List<? extends Resource> resources, FolderConfiguration referenceConfig) { // // 1: eliminate resources that contradict the reference configuration // 2: pick next qualifier type // 3: check if any resources use this qualifier, if no, back to 2, else move on to 4. // 4: eliminate resources that don't use this qualifier. // 5: if more than one resource left, go back to 2. // // The precedence of the qualifiers is more important than the number of qualifiers that // exactly match the device. // 1: eliminate resources that contradict ArrayList<Resource> matchingResources = new ArrayList<Resource>(); for (int i = 0 ; i < resources.size(); i++) { Resource res = resources.get(i); if (res.getConfiguration().isMatchFor(referenceConfig)) { matchingResources.add(res); } } // if there is only one match, just take it if (matchingResources.size() == 1) { return matchingResources.get(0); } else if (matchingResources.size() == 0) { return null; } // 2. Loop on the qualifiers, and eliminate matches final int count = FolderConfiguration.getQualifierCount(); for (int q = 0 ; q < count ; q++) { // look to see if one resource has this qualifier. // At the same time also record the best match value for the qualifier (if applicable). // The reference value, to find the best match. // Note that this qualifier could be null. In which case any qualifier found in the // possible match, will all be considered best match. ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q); boolean found = false; ResourceQualifier bestMatch = null; // this is to store the best match. for (Resource res : matchingResources) { ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier != null) { // set the flag. found = true; // Now check for a best match. If the reference qualifier is null , // any qualifier is a "best" match (we don't need to record all of them. // Instead the non compatible ones are removed below) if (referenceQualifier != null) { if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) { bestMatch = qualifier; } } } } // 4. If a resources has a qualifier at the current index, remove all the resources that // do not have one, or whose qualifier value does not equal the best match found above // unless there's no reference qualifier, in which case they are all considered // "best" match. if (found) { for (int i = 0 ; i < matchingResources.size(); ) { Resource res = matchingResources.get(i); ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier == null) { // this resources has no qualifier of this type: rejected. matchingResources.remove(res); } else if (referenceQualifier != null && bestMatch != null && bestMatch.equals(qualifier) == false) { // there's a reference qualifier and there is a better match for it than // this resource, so we reject it. matchingResources.remove(res); } else { // looks like we keep this resource, move on to the next one. i++; } } // at this point we may have run out of matching resources before going // through all the qualifiers. if (matchingResources.size() < 2) { break; } } } // Because we accept resources whose configuration have qualifiers where the reference // configuration doesn't, we can end up with more than one match. In this case, we just // take the first one. if (matchingResources.size() == 0) { return null; } - return matchingResources.get(1); + return matchingResources.get(0); } /** * Checks if the list of {@link ResourceItem}s for the specified {@link ResourceType} needs * to be updated. * @param type the Resource Type. */ private void checkAndUpdate(ResourceType type) { // get the list of folder that can output this type ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(type); for (ResourceFolderType folderType : folderTypes) { List<ResourceFolder> folders = mFolderMap.get(folderType); if (folders != null) { for (ResourceFolder folder : folders) { if (folder.isTouched()) { // if this folder is touched we need to update all the types that can // be generated from a file in this folder. // This will include 'type' obviously. ResourceType[] resTypes = FolderTypeRelationship.getRelatedResourceTypes( folderType); for (ResourceType resType : resTypes) { update(resType); } return; } } } } } /** * Updates the list of {@link ResourceItem} objects associated with a {@link ResourceType}. * This will reset the touch status of all the folders that can generate this resource type. * @param type the Resource Type. */ private void update(ResourceType type) { // get the cache list, and lets make a backup List<ProjectResourceItem> items = mResourceMap.get(type); List<ProjectResourceItem> backup = new ArrayList<ProjectResourceItem>(); if (items == null) { items = new ArrayList<ProjectResourceItem>(); mResourceMap.put(type, items); } else { // backup the list backup.addAll(items); // we reset the list itself. items.clear(); } // get the list of folder that can output this type ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(type); for (ResourceFolderType folderType : folderTypes) { List<ResourceFolder> folders = mFolderMap.get(folderType); if (folders != null) { for (ResourceFolder folder : folders) { items.addAll(folder.getResources(type, this)); folder.resetTouch(); } } } // now items contains the new list. We "merge" it with the backup list. // Basically, we need to keep the old instances of ResourceItem (where applicable), // but replace them by the content of the new items. // This will let the resource explorer keep the expanded state of the nodes whose data // is a ResourceItem object. if (backup.size() > 0) { // this is not going to change as we're only replacing instances. int count = items.size(); for (int i = 0 ; i < count;) { // get the "new" item ProjectResourceItem item = items.get(i); // look for a similar item in the old list. ProjectResourceItem foundOldItem = null; for (ProjectResourceItem oldItem : backup) { if (oldItem.getName().equals(item.getName())) { foundOldItem = oldItem; break; } } if (foundOldItem != null) { // erase the data of the old item with the data from the new one. foundOldItem.replaceWith(item); // remove the old and new item from their respective lists items.remove(i); backup.remove(foundOldItem); // add the old item to the new list items.add(foundOldItem); } else { // this is a new item, we skip to the next object i++; } } } // if this is the ResourceType.ID, we create the actual list, from this list and // the compiled resource list. if (type == ResourceType.ID) { mergeIdResources(); } else { // else this is the list that will actually be displayed, so we sort it. Collections.sort(items); } } /** * Looks up an existing {@link ProjectResourceItem} by {@link ResourceType} and name. * @param type the Resource Type. * @param name the Resource name. * @return the existing ResourceItem or null if no match was found. */ protected ProjectResourceItem findResourceItem(ResourceType type, String name) { List<ProjectResourceItem> list = mResourceMap.get(type); for (ProjectResourceItem item : list) { if (name.equals(item.getName())) { return item; } } return null; } /** * Sets compiled resource information. * @param resIdValueToNameMap a map of compiled resource id to resource name. * The map is acquired by the {@link ProjectResources} object. * @param styleableValueMap * @param resourceValueMap a map of (name, id) for resources of type {@link ResourceType#ID}. * The list is acquired by the {@link ProjectResources} object. */ void setCompiledResources(Map<Integer, String[]> resIdValueToNameMap, Map<IntArrayWrapper, String> styleableValueMap, Map<String, Map<String, Integer>> resourceValueMap) { mResourceValueMap = resourceValueMap; mResIdValueToNameMap = resIdValueToNameMap; mStyleableValueToNameMap = styleableValueMap; mergeIdResources(); } /** * Merges the list of ID resource coming from R.java and the list of ID resources * coming from XML declaration into the cached list {@link #mIdResourceList}. */ void mergeIdResources() { // get the list of IDs coming from XML declaration. Those ids are present in // mCompiledIdResources already, so we'll need to use those instead of creating // new IdResourceItem List<ProjectResourceItem> xmlIdResources = mResourceMap.get(ResourceType.ID); synchronized (mIdResourceList) { // copy the currently cached items. ArrayList<IdResourceItem> oldItems = new ArrayList<IdResourceItem>(); oldItems.addAll(mIdResourceList); // empty the current list mIdResourceList.clear(); // get the list of compile id resources. Map<String, Integer> idMap = null; if (mResourceValueMap != null) { idMap = mResourceValueMap.get(ResourceType.ID.getName()); } if (idMap == null) { if (xmlIdResources != null) { for (ProjectResourceItem resourceItem : xmlIdResources) { // check the actual class just for safety. if (resourceItem instanceof IdResourceItem) { mIdResourceList.add((IdResourceItem)resourceItem); } } } } else { // loop on the full list of id, and look for a match in the old list, // in the list coming from XML (in case a new XML item was created.) Set<String> idSet = idMap.keySet(); idLoop: for (String idResource : idSet) { // first look in the XML list in case an id went from inline to XML declared. if (xmlIdResources != null) { for (ProjectResourceItem resourceItem : xmlIdResources) { if (resourceItem instanceof IdResourceItem && resourceItem.getName().equals(idResource)) { mIdResourceList.add((IdResourceItem)resourceItem); continue idLoop; } } } // if we haven't found it, look in the old items. int count = oldItems.size(); for (int i = 0 ; i < count ; i++) { IdResourceItem resourceItem = oldItems.get(i); if (resourceItem.getName().equals(idResource)) { oldItems.remove(i); mIdResourceList.add(resourceItem); continue idLoop; } } // if we haven't found it, it looks like it's a new id that was // declared inline. mIdResourceList.add(new IdResourceItem(idResource, true /* isDeclaredInline */)); } } // now we sort the list Collections.sort(mIdResourceList); } } }
true
true
private Resource findMatchingConfiguredResource(List<? extends Resource> resources, FolderConfiguration referenceConfig) { // // 1: eliminate resources that contradict the reference configuration // 2: pick next qualifier type // 3: check if any resources use this qualifier, if no, back to 2, else move on to 4. // 4: eliminate resources that don't use this qualifier. // 5: if more than one resource left, go back to 2. // // The precedence of the qualifiers is more important than the number of qualifiers that // exactly match the device. // 1: eliminate resources that contradict ArrayList<Resource> matchingResources = new ArrayList<Resource>(); for (int i = 0 ; i < resources.size(); i++) { Resource res = resources.get(i); if (res.getConfiguration().isMatchFor(referenceConfig)) { matchingResources.add(res); } } // if there is only one match, just take it if (matchingResources.size() == 1) { return matchingResources.get(0); } else if (matchingResources.size() == 0) { return null; } // 2. Loop on the qualifiers, and eliminate matches final int count = FolderConfiguration.getQualifierCount(); for (int q = 0 ; q < count ; q++) { // look to see if one resource has this qualifier. // At the same time also record the best match value for the qualifier (if applicable). // The reference value, to find the best match. // Note that this qualifier could be null. In which case any qualifier found in the // possible match, will all be considered best match. ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q); boolean found = false; ResourceQualifier bestMatch = null; // this is to store the best match. for (Resource res : matchingResources) { ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier != null) { // set the flag. found = true; // Now check for a best match. If the reference qualifier is null , // any qualifier is a "best" match (we don't need to record all of them. // Instead the non compatible ones are removed below) if (referenceQualifier != null) { if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) { bestMatch = qualifier; } } } } // 4. If a resources has a qualifier at the current index, remove all the resources that // do not have one, or whose qualifier value does not equal the best match found above // unless there's no reference qualifier, in which case they are all considered // "best" match. if (found) { for (int i = 0 ; i < matchingResources.size(); ) { Resource res = matchingResources.get(i); ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier == null) { // this resources has no qualifier of this type: rejected. matchingResources.remove(res); } else if (referenceQualifier != null && bestMatch != null && bestMatch.equals(qualifier) == false) { // there's a reference qualifier and there is a better match for it than // this resource, so we reject it. matchingResources.remove(res); } else { // looks like we keep this resource, move on to the next one. i++; } } // at this point we may have run out of matching resources before going // through all the qualifiers. if (matchingResources.size() < 2) { break; } } } // Because we accept resources whose configuration have qualifiers where the reference // configuration doesn't, we can end up with more than one match. In this case, we just // take the first one. if (matchingResources.size() == 0) { return null; } return matchingResources.get(1); }
private Resource findMatchingConfiguredResource(List<? extends Resource> resources, FolderConfiguration referenceConfig) { // // 1: eliminate resources that contradict the reference configuration // 2: pick next qualifier type // 3: check if any resources use this qualifier, if no, back to 2, else move on to 4. // 4: eliminate resources that don't use this qualifier. // 5: if more than one resource left, go back to 2. // // The precedence of the qualifiers is more important than the number of qualifiers that // exactly match the device. // 1: eliminate resources that contradict ArrayList<Resource> matchingResources = new ArrayList<Resource>(); for (int i = 0 ; i < resources.size(); i++) { Resource res = resources.get(i); if (res.getConfiguration().isMatchFor(referenceConfig)) { matchingResources.add(res); } } // if there is only one match, just take it if (matchingResources.size() == 1) { return matchingResources.get(0); } else if (matchingResources.size() == 0) { return null; } // 2. Loop on the qualifiers, and eliminate matches final int count = FolderConfiguration.getQualifierCount(); for (int q = 0 ; q < count ; q++) { // look to see if one resource has this qualifier. // At the same time also record the best match value for the qualifier (if applicable). // The reference value, to find the best match. // Note that this qualifier could be null. In which case any qualifier found in the // possible match, will all be considered best match. ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q); boolean found = false; ResourceQualifier bestMatch = null; // this is to store the best match. for (Resource res : matchingResources) { ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier != null) { // set the flag. found = true; // Now check for a best match. If the reference qualifier is null , // any qualifier is a "best" match (we don't need to record all of them. // Instead the non compatible ones are removed below) if (referenceQualifier != null) { if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) { bestMatch = qualifier; } } } } // 4. If a resources has a qualifier at the current index, remove all the resources that // do not have one, or whose qualifier value does not equal the best match found above // unless there's no reference qualifier, in which case they are all considered // "best" match. if (found) { for (int i = 0 ; i < matchingResources.size(); ) { Resource res = matchingResources.get(i); ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier == null) { // this resources has no qualifier of this type: rejected. matchingResources.remove(res); } else if (referenceQualifier != null && bestMatch != null && bestMatch.equals(qualifier) == false) { // there's a reference qualifier and there is a better match for it than // this resource, so we reject it. matchingResources.remove(res); } else { // looks like we keep this resource, move on to the next one. i++; } } // at this point we may have run out of matching resources before going // through all the qualifiers. if (matchingResources.size() < 2) { break; } } } // Because we accept resources whose configuration have qualifiers where the reference // configuration doesn't, we can end up with more than one match. In this case, we just // take the first one. if (matchingResources.size() == 0) { return null; } return matchingResources.get(0); }
diff --git a/utilities/bin2asmbin/Application.java b/utilities/bin2asmbin/Application.java index b8c8350..749cffd 100644 --- a/utilities/bin2asmbin/Application.java +++ b/utilities/bin2asmbin/Application.java @@ -1,206 +1,206 @@ package net.plusmid.bin2asmbin; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; public class Application { private final static int MAJOR = 0; private final static int MINOR = 1; private final static int REV = 1; static String inputfile = null; static String outputfile = null; static boolean verbose = false; static boolean lines = false; public static void main(String[] args) { // check if no arguments are provided if (args.length == 0) { showHelp(); System.exit(1); } // parse command line arguments parseCLI(args); FileInputStream fi = null; DataInputStream di = null; try { // open input file fi = new FileInputStream(inputfile); di = new DataInputStream(fi); } catch (FileNotFoundException e) { fatal_error("could not find file \"" + inputfile + "\""); } int buffer = 0; int buffer2 = 0; int count = 0; FileWriter fw = null; BufferedWriter bw = null; if (outputfile != null) { try { fw = new FileWriter(outputfile); bw = new BufferedWriter(fw); } catch (IOException e) { fatal_error("could not write output file \"" + outputfile + "\""); } } try { while ((buffer = di.read()) != -1) { if ((buffer2 = di.read()) != -1) buffer |= (buffer2 << 8); if ((lines && (count % 8) == 0) || count == 0) { if (bw != null) bw.write("\ndat 0x" + toHex(buffer)); if (verbose) - bw.write("\ndat 0x" + toHex(buffer)); + System.out.print("\ndat 0x" + toHex(buffer)); } else { if (fw != null) bw.write(", 0x" + toHex(buffer)); if (verbose) System.out.print(", 0x" + toHex(buffer)); } ++count; } } catch (IOException e) { error("unable to read file \"" + inputfile + "\""); } try { fi.close(); di.close(); if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException e) { error("unable to close filestream of \"" + inputfile + "\""); } } private static String toHex(int value) { String buffer = Integer.toHexString(value); while (4 - buffer.length() > 0) buffer = "0" + buffer; return buffer; } private static void parseCLI(String[] args) { for (int i=0; i<args.length; i++) { if (args[i].equals("-v") || args[i].equals("-verbose")) verbose = true; else if (args[i].equals("-l") || args[i].equals("-lines")) lines = true; else if (args[i].equals("-ver") || args[i].equals("-version")) showVersion(true); else if (inputfile == null) inputfile = args[i]; else if (outputfile == null) outputfile = args[i]; else error("unrecognized command \"" + args[i] + "\""); } if (inputfile == null) fatal_error("no input file specified!"); if (outputfile == null && verbose == false) fatal_error("no output file specified!"); } private static void fatal_error(String msg) { say("fatal error: " + msg); showHelp(); System.exit(1); } private static void error(String msg) { say("error: " + msg); } private static void say(String msg) { System.err.println(msg); } private static void showHelp() { showVersion(); System.out.println( "Usage:\n" + "bin2asmbin inputfile outputfile [arguments]\n" + "Arguments:\n" + "-v -verbose Prints the output on stdout (you may omit outputfile if using this).\n" + "-l -lines Inserts a linefeed every 8 words.\n" + "-ver -version Shows the version of this application."); } private static void showVersion(boolean exit) { System.out.println( "bin2asmbin v" + MAJOR + "." + MINOR + "." + REV); if (exit) System.exit(0); } private static void showVersion() { showVersion(false); } }
true
true
public static void main(String[] args) { // check if no arguments are provided if (args.length == 0) { showHelp(); System.exit(1); } // parse command line arguments parseCLI(args); FileInputStream fi = null; DataInputStream di = null; try { // open input file fi = new FileInputStream(inputfile); di = new DataInputStream(fi); } catch (FileNotFoundException e) { fatal_error("could not find file \"" + inputfile + "\""); } int buffer = 0; int buffer2 = 0; int count = 0; FileWriter fw = null; BufferedWriter bw = null; if (outputfile != null) { try { fw = new FileWriter(outputfile); bw = new BufferedWriter(fw); } catch (IOException e) { fatal_error("could not write output file \"" + outputfile + "\""); } } try { while ((buffer = di.read()) != -1) { if ((buffer2 = di.read()) != -1) buffer |= (buffer2 << 8); if ((lines && (count % 8) == 0) || count == 0) { if (bw != null) bw.write("\ndat 0x" + toHex(buffer)); if (verbose) bw.write("\ndat 0x" + toHex(buffer)); } else { if (fw != null) bw.write(", 0x" + toHex(buffer)); if (verbose) System.out.print(", 0x" + toHex(buffer)); } ++count; } } catch (IOException e) { error("unable to read file \"" + inputfile + "\""); } try { fi.close(); di.close(); if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException e) { error("unable to close filestream of \"" + inputfile + "\""); } }
public static void main(String[] args) { // check if no arguments are provided if (args.length == 0) { showHelp(); System.exit(1); } // parse command line arguments parseCLI(args); FileInputStream fi = null; DataInputStream di = null; try { // open input file fi = new FileInputStream(inputfile); di = new DataInputStream(fi); } catch (FileNotFoundException e) { fatal_error("could not find file \"" + inputfile + "\""); } int buffer = 0; int buffer2 = 0; int count = 0; FileWriter fw = null; BufferedWriter bw = null; if (outputfile != null) { try { fw = new FileWriter(outputfile); bw = new BufferedWriter(fw); } catch (IOException e) { fatal_error("could not write output file \"" + outputfile + "\""); } } try { while ((buffer = di.read()) != -1) { if ((buffer2 = di.read()) != -1) buffer |= (buffer2 << 8); if ((lines && (count % 8) == 0) || count == 0) { if (bw != null) bw.write("\ndat 0x" + toHex(buffer)); if (verbose) System.out.print("\ndat 0x" + toHex(buffer)); } else { if (fw != null) bw.write(", 0x" + toHex(buffer)); if (verbose) System.out.print(", 0x" + toHex(buffer)); } ++count; } } catch (IOException e) { error("unable to read file \"" + inputfile + "\""); } try { fi.close(); di.close(); if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException e) { error("unable to close filestream of \"" + inputfile + "\""); } }
diff --git a/eu.alert-project.iccs.stardom.core/eu.alert-project.iccs.stardom.simulator/src/main/java/eu/alertproject/iccs/stardom/simulator/Run.java b/eu.alert-project.iccs.stardom.core/eu.alert-project.iccs.stardom.simulator/src/main/java/eu/alertproject/iccs/stardom/simulator/Run.java index 2aec6eb..0ec86e4 100644 --- a/eu.alert-project.iccs.stardom.core/eu.alert-project.iccs.stardom.simulator/src/main/java/eu/alertproject/iccs/stardom/simulator/Run.java +++ b/eu.alert-project.iccs.stardom.core/eu.alert-project.iccs.stardom.simulator/src/main/java/eu/alertproject/iccs/stardom/simulator/Run.java @@ -1,99 +1,99 @@ package eu.alertproject.iccs.stardom.simulator; import eu.alertproject.iccs.events.api.Topics; import eu.alertproject.iccs.stardom.simulator.services.*; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jms.core.JmsTemplate; import java.io.File; import java.util.Properties; /** * User: fotis * Date: 19/04/12 * Time: 17:52 */ public class Run { private static Logger logger = LoggerFactory.getLogger(Run.class); public static void main(String[] args) { if(args == null || args.length < 1 ){ System.out.println("Please enter either kde, optimis or petals as per you configuration file"); } ApplicationContext context = new ClassPathXmlApplicationContext( "/applicationContext.xml" ); Properties systemProperties = (Properties) context.getBean("systemProperties"); String repo = args[0]; logger.info("Extracting information for {} ",repo); String basePath = systemProperties.getProperty("data.basePath")+File.separator; String commitFile = basePath+systemProperties.getProperty(repo+".path.commits"); String issuesNewFile = basePath+systemProperties.getProperty(repo+".path.issuesNew"); String issuesUpdateFile = basePath+systemProperties.getProperty(repo+".path.issuesUpdate"); String mailNewFile = basePath+systemProperties.getProperty(repo+".path.mailnew"); String forumPostNewFile = basePath+systemProperties.getProperty(repo+".path.forums"); handleFile(context,Topics.ALERT_METADATA_CommitNew_Updated,commitFile); handleFile(context,Topics.ALERT_METADATA_IssueNew_Updated,issuesNewFile); handleFile(context,Topics.ALERT_METADATA_IssueUpdate_Updated,issuesUpdateFile); handleFile(context,Topics.ALERT_METADATA_MailNew_Updated,mailNewFile); handleFile(context,Topics.ALERT_METADATA_ForumPost_Updated,forumPostNewFile); System.exit(0); } private static void handleFile(ApplicationContext context, String topic, String commitFile) { Properties systemProperties = (Properties) context.getBean("systemProperties"); if(StringUtils.isEmpty(commitFile)){ return; } File file = new File(commitFile); if(file.exists() && file.canRead()){ //determine service String absolutePath = file.getAbsolutePath(); String service = "zipSimulationService"; if(absolutePath.toLowerCase().endsWith("tar.gz")){ service = "targzSimulationService"; }else if(absolutePath.toLowerCase().endsWith("rar")){ service = "rarSimulationService"; }else if(absolutePath.toLowerCase().endsWith("zip")){ service = "zipSimulationService"; }else{ logger.error("Couldn't find service for this file"); return; } logger.info("Using service {} ",service); ((SimulationService)context.getBean(service)).start( absolutePath, new InputStreamTopicVisitor(topic, - Boolean.valueOf(systemProperties.getProperty("activemq.processDisabled")), + !Boolean.valueOf(systemProperties.getProperty("activemq.processDisabled")), (JmsTemplate) context.getBean("jmsTemplate"))); }else{ logger.error("Couldn't handle {} ",commitFile); } } }
true
true
private static void handleFile(ApplicationContext context, String topic, String commitFile) { Properties systemProperties = (Properties) context.getBean("systemProperties"); if(StringUtils.isEmpty(commitFile)){ return; } File file = new File(commitFile); if(file.exists() && file.canRead()){ //determine service String absolutePath = file.getAbsolutePath(); String service = "zipSimulationService"; if(absolutePath.toLowerCase().endsWith("tar.gz")){ service = "targzSimulationService"; }else if(absolutePath.toLowerCase().endsWith("rar")){ service = "rarSimulationService"; }else if(absolutePath.toLowerCase().endsWith("zip")){ service = "zipSimulationService"; }else{ logger.error("Couldn't find service for this file"); return; } logger.info("Using service {} ",service); ((SimulationService)context.getBean(service)).start( absolutePath, new InputStreamTopicVisitor(topic, Boolean.valueOf(systemProperties.getProperty("activemq.processDisabled")), (JmsTemplate) context.getBean("jmsTemplate"))); }else{ logger.error("Couldn't handle {} ",commitFile); } }
private static void handleFile(ApplicationContext context, String topic, String commitFile) { Properties systemProperties = (Properties) context.getBean("systemProperties"); if(StringUtils.isEmpty(commitFile)){ return; } File file = new File(commitFile); if(file.exists() && file.canRead()){ //determine service String absolutePath = file.getAbsolutePath(); String service = "zipSimulationService"; if(absolutePath.toLowerCase().endsWith("tar.gz")){ service = "targzSimulationService"; }else if(absolutePath.toLowerCase().endsWith("rar")){ service = "rarSimulationService"; }else if(absolutePath.toLowerCase().endsWith("zip")){ service = "zipSimulationService"; }else{ logger.error("Couldn't find service for this file"); return; } logger.info("Using service {} ",service); ((SimulationService)context.getBean(service)).start( absolutePath, new InputStreamTopicVisitor(topic, !Boolean.valueOf(systemProperties.getProperty("activemq.processDisabled")), (JmsTemplate) context.getBean("jmsTemplate"))); }else{ logger.error("Couldn't handle {} ",commitFile); } }
diff --git a/app/src/processing/app/preproc/PdeEmitter.java b/app/src/processing/app/preproc/PdeEmitter.java index 060d20668..8210d9fcd 100644 --- a/app/src/processing/app/preproc/PdeEmitter.java +++ b/app/src/processing/app/preproc/PdeEmitter.java @@ -1,832 +1,833 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app.preproc; import java.io.PrintStream; import java.util.BitSet; import java.util.Stack; import processing.app.Preferences; import processing.app.antlr.PdeTokenTypes; import processing.app.debug.RunnerException; import antlr.CommonHiddenStreamToken; import antlr.collections.AST; /* Based on original code copyright (c) 2003 Andy Tripp <[email protected]>. * shipped under GPL with permission. */ /** * PDEEmitter: A class that can take an ANTLR Java AST and produce * reasonably formatted Java code from it. To use it, create a * PDEEmitter object, call setOut() if you want to print to something * other than System.out, and then call print(), passing the * AST. Typically, the AST node that you pass would be the root of a * tree - the ROOT_ID node that represents a Java file. * * Modified March 2010 to support Java 5 type arguments and for loops */ @SuppressWarnings("unused") public class PdeEmitter implements PdeTokenTypes { private final PdePreprocessor pdePreprocessor; private final PrintStream out; private final PrintStream debug = System.err; private final Stack stack = new Stack(); private final static int ROOT_ID = 0; public PdeEmitter(final PdePreprocessor pdePreprocessor, final PrintStream out) { this.pdePreprocessor = pdePreprocessor; this.out = out; } /** * Find a child of the given AST that has the given type * @returns a child AST of the given type. If it can't find a child of the * given type, return null. */ private AST getChild(final AST ast, final int childType) { AST child = ast.getFirstChild(); while (child != null) { if (child.getType() == childType) { // debug.println("getChild: found:" + name(ast)); return child; } child = child.getNextSibling(); } return null; } /** * Dump the list of hidden tokens linked to after the AST node passed in. * Most hidden tokens are dumped from this function. */ private void dumpHiddenAfter(final AST ast) { dumpHiddenTokens(((antlr.CommonASTWithHiddenTokens) ast).getHiddenAfter()); } /** * Dump the list of hidden tokens linked to before the AST node passed in. * The only time hidden tokens need to be dumped with this function is when * dealing parts of the tree where automatic tree construction was * turned off with the ! operator in the grammar file and the nodes were * manually constructed in such a way that the usual tokens don't have the * necessary hiddenAfter links. */ private void dumpHiddenBefore(final AST ast) { antlr.CommonHiddenStreamToken child = null, parent = ((antlr.CommonASTWithHiddenTokens) ast).getHiddenBefore(); // if there aren't any hidden tokens here, quietly return // if (parent == null) { return; } // traverse back to the head of the list of tokens before this node do { child = parent; parent = child.getHiddenBefore(); } while (parent != null); // dump that list dumpHiddenTokens(child); } /** * Dump the list of hidden tokens linked to from the token passed in. */ private void dumpHiddenTokens(CommonHiddenStreamToken t) { for (; t != null; t = pdePreprocessor.getHiddenAfter(t)) { out.print(t.getText()); } } /** * Print the children of the given AST * @param ast The AST to print * @returns true iff anything was printed */ private boolean printChildren(final AST ast) throws RunnerException { boolean ret = false; AST child = ast.getFirstChild(); while (child != null) { ret = true; print(child); child = child.getNextSibling(); } return ret; } /** * Tells whether an AST has any children or not. * @return true iff the AST has at least one child */ private boolean hasChildren(final AST ast) { return (ast.getFirstChild() != null); } /** * Gets the best node in the subtree for printing. This really means * the next node which could potentially have hiddenBefore data. It's * usually the first printable leaf, but not always. * * @param includeThisNode Should this node be included in the search? * If false, only descendants are searched. * * @return the first printable leaf node in an AST */ private AST getBestPrintableNode(final AST ast, final boolean includeThisNode) { AST child; if (includeThisNode) { child = ast; } else { child = ast.getFirstChild(); } if (child != null) { switch (child.getType()) { // the following node types are printing nodes that print before // any children, but then also recurse over children. So they // may have hiddenBefore chains that need to be printed first. Many // statements and all unary expression types qualify. Return these // nodes directly case CLASS_DEF: case LITERAL_if: case LITERAL_new: case LITERAL_for: case LITERAL_while: case LITERAL_do: case LITERAL_break: case LITERAL_continue: case LITERAL_return: case LITERAL_switch: case LITERAL_try: case LITERAL_throw: case LITERAL_synchronized: case LITERAL_assert: case BNOT: case LNOT: case INC: case DEC: case UNARY_MINUS: case UNARY_PLUS: return child; // Some non-terminal node types (at the moment, I only know of // MODIFIERS, but there may be other such types), can be // leaves in the tree but not have any children. If this is // such a node, move on to the next sibling. case MODIFIERS: if (child.getFirstChild() == null) { return getBestPrintableNode(child.getNextSibling(), false); } // new jikes doesn't like fallthrough, so just duplicated here: return getBestPrintableNode(child, false); default: return getBestPrintableNode(child, false); } } return ast; } // Because the meanings of <, >, >>, and >>> are overloaded to support // type arguments and type parameters, we have to treat them // as copyable to hidden text (or else the following syntax, // such as (); and what not gets lost under certain circumstances // // Since they are copied to the hidden stream, you don't want // to print them explicitly; they come out in the dumpHiddenXXX methods. // -- jdf private static final BitSet OTHER_COPIED_TOKENS = new BitSet() { { set(LT); set(GT); set(SR); set(BSR); } }; /** * Prints a binary operator */ private void printBinaryOperator(final AST ast) throws RunnerException { print(ast.getFirstChild()); if (!OTHER_COPIED_TOKENS.get(ast.getType())) { out.print(ast.getText()); } dumpHiddenAfter(ast); print(ast.getFirstChild().getNextSibling()); } private void printIfThenElse(final AST literalIf) throws RunnerException { out.print(literalIf.getText()); dumpHiddenAfter(literalIf); final AST condition = literalIf.getFirstChild(); print(condition); // the "if" condition: an EXPR // the "then" clause is either an SLIST or an EXPR final AST thenPath = condition.getNextSibling(); print(thenPath); // optional "else" clause: an SLIST or an EXPR final AST elsePath = thenPath.getNextSibling(); if (elsePath != null) { out.print("else"); dumpHiddenBefore(getBestPrintableNode(elsePath, true)); print(elsePath); } } /** * Print the given AST. Call this function to print your PDE code. * * It works by making recursive calls to print children. * So the code below is one big "switch" statement on the passed AST type. */ public void print(final AST ast) throws RunnerException { if (ast == null) { return; } AST parent = null; if (!stack.isEmpty()) { parent = (AST) stack.peek(); } stack.push(ast); final AST child1 = ast.getFirstChild(); AST child2 = null; AST child3 = null; if (child1 != null) { child2 = child1.getNextSibling(); if (child2 != null) { child3 = child2.getNextSibling(); } } switch (ast.getType()) { // The top of the tree looks like this: // ROOT_ID "Whatever.java" // package // imports // class definition case ROOT_ID: dumpHiddenTokens(pdePreprocessor.getInitialHiddenToken()); printChildren(ast); break; // supporting a "package" statement in a PDE program has // a bunch of issues with it that need to dealt in the compilation // code too, so this isn't actually tested. case PACKAGE_DEF: out.print("package"); dumpHiddenAfter(ast); print(ast.getFirstChild()); break; // IMPORT has exactly one child case IMPORT: out.print("import"); dumpHiddenAfter(ast); print(ast.getFirstChild()); break; case STATIC_IMPORT: out.print("import static"); dumpHiddenAfter(ast); print(ast.getFirstChild()); break; case CLASS_DEF: case INTERFACE_DEF: print(getChild(ast, MODIFIERS)); if (ast.getType() == CLASS_DEF) { out.print("class"); } else { out.print("interface"); } dumpHiddenBefore(getChild(ast, IDENT)); print(getChild(ast, IDENT)); print(getChild(ast, TYPE_PARAMETERS)); print(getChild(ast, EXTENDS_CLAUSE)); print(getChild(ast, IMPLEMENTS_CLAUSE)); print(getChild(ast, OBJBLOCK)); break; case EXTENDS_CLAUSE: if (hasChildren(ast)) { out.print("extends"); dumpHiddenBefore(getBestPrintableNode(ast, false)); printChildren(ast); } break; case IMPLEMENTS_CLAUSE: if (hasChildren(ast)) { out.print("implements"); dumpHiddenBefore(getBestPrintableNode(ast, false)); printChildren(ast); } break; // DOT always has exactly two children. case DOT: print(child1); out.print("."); dumpHiddenAfter(ast); print(child2); break; case MODIFIERS: case OBJBLOCK: case CTOR_DEF: //case METHOD_DEF: case PARAMETERS: case PARAMETER_DEF: case VARIABLE_PARAMETER_DEF: case VARIABLE_DEF: case TYPE: case SLIST: case ELIST: case ARRAY_DECLARATOR: case TYPECAST: case EXPR: case ARRAY_INIT: case FOR_INIT: case FOR_CONDITION: case FOR_ITERATOR: case METHOD_CALL: case INSTANCE_INIT: case INDEX_OP: case SUPER_CTOR_CALL: case CTOR_CALL: printChildren(ast); break; case METHOD_DEF: // kids seem to be: MODIFIERS TYPE setup PARAMETERS //AST parent = (AST) stack.peek(); final AST modifiersChild = ast.getFirstChild(); final AST typeChild = modifiersChild.getNextSibling(); final AST methodNameChild = typeChild.getNextSibling(); final AST parametersChild = methodNameChild.getNextSibling(); // to output, use print(child) on each of the four final String methodName = methodNameChild.getText(); if (methodName.equals("main")) { pdePreprocessor.setFoundMain(true); } // if this method doesn't have a specifier, make it public // (useful for setup/keyPressed/etc) boolean foundSpecifier = false; AST child = modifiersChild.getFirstChild(); while (child != null) { final String childText = child.getText(); if (childText.equals("public") || childText.equals("protected") || childText.equals("private")) { foundSpecifier = true; child = null; } else { //out.print("." + child.getText() + "."); child = child.getNextSibling(); } } if (!foundSpecifier) { out.print("public "); } printChildren(ast); // everything is fine break; // if we have two children, it's of the form "a=0" // if just one child, it's of the form "=0" (where the // lhs is above this AST). case ASSIGN: if (child2 != null) { print(child1); out.print("="); dumpHiddenAfter(ast); print(child2); } else { out.print("="); dumpHiddenAfter(ast); print(child1); } break; // binary operators: case PLUS: case MINUS: case DIV: case MOD: case NOT_EQUAL: case EQUAL: case LT: case GT: case LE: case GE: case LOR: case LAND: case BOR: case BXOR: case BAND: case SL: case SR: case BSR: case LITERAL_instanceof: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: printBinaryOperator(ast); break; case LITERAL_for: out.print(ast.getText()); dumpHiddenAfter(ast); if (child1.getType() == FOR_EACH_CLAUSE) { printChildren(child1); print(child2); } else { printChildren(ast); } break; case POST_INC: case POST_DEC: print(child1); out.print(ast.getText()); dumpHiddenAfter(ast); break; // unary operators: case BNOT: case LNOT: case INC: case DEC: case UNARY_MINUS: case UNARY_PLUS: out.print(ast.getText()); dumpHiddenAfter(ast); print(child1); break; case LITERAL_new: out.print("new"); dumpHiddenAfter(ast); print(child1); print(child2); // "new String[] {...}": the stuff in {} is child3 if (child3 != null) { print(child3); } break; case LITERAL_return: out.print("return"); dumpHiddenAfter(ast); print(child1); break; case STATIC_INIT: out.print("static"); dumpHiddenBefore(getBestPrintableNode(ast, false)); print(child1); break; case LITERAL_switch: out.print("switch"); dumpHiddenAfter(ast); printChildren(ast); break; case LABELED_STAT: case CASE_GROUP: printChildren(ast); break; case LITERAL_case: out.print("case"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_default: out.print("default"); dumpHiddenAfter(ast); printChildren(ast); break; case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: out.print(ast.getText()); dumpHiddenAfter(ast); break; case LITERAL_synchronized: // 0137 to fix bug #136 + case LITERAL_assert: out.print(ast.getText()); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_static: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: //case LITERAL_synchronized: // 0137 to fix bug #136 case LITERAL_volatile: case LITERAL_class: // 0176 to fix bug #1466 case FINAL: case ABSTRACT: case LITERAL_package: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_true: case LITERAL_false: case LITERAL_null: case SEMI: case LITERAL_this: case LITERAL_super: out.print(ast.getText()); dumpHiddenAfter(ast); break; case EMPTY_STAT: case EMPTY_FIELD: break; case LITERAL_continue: case LITERAL_break: out.print(ast.getText()); dumpHiddenAfter(ast); if (child1 != null) {// maybe label print(child1); } break; // yuck: Distinguish between "import x.y.*" and "x = 1 * 3" case STAR: if (hasChildren(ast)) { // the binary mult. operator printBinaryOperator(ast); } else { // the special "*" in import: out.print("*"); dumpHiddenAfter(ast); } break; case LITERAL_throws: out.print("throws"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_if: printIfThenElse(ast); break; case LITERAL_while: out.print("while"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_do: out.print("do"); dumpHiddenAfter(ast); print(child1); // an SLIST out.print("while"); dumpHiddenBefore(getBestPrintableNode(child2, false)); print(child2); // an EXPR break; case LITERAL_try: out.print("try"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_catch: out.print("catch"); dumpHiddenAfter(ast); printChildren(ast); break; // the first child is the "try" and the second is the SLIST case LITERAL_finally: out.print("finally"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_throw: out.print("throw"); dumpHiddenAfter(ast); print(child1); break; // the dreaded trinary operator case QUESTION: print(child1); out.print("?"); dumpHiddenAfter(ast); print(child2); print(child3); break; // pde specific or modified tokens start here // Image -> BImage, Font -> BFont as appropriate case IDENT: /* if (ast.getText().equals("Image") && Preferences.getBoolean("preproc.substitute_image")) { //, true)) { out.print("BImage"); } else if (ast.getText().equals("Font") && Preferences.getBoolean("preproc.substitute_font")) { //, true)) { out.print("BFont"); } else { */ out.print(ast.getText()); //} dumpHiddenAfter(ast); break; // the color datatype is just an alias for int case LITERAL_color: out.print("int"); dumpHiddenAfter(ast); break; case WEBCOLOR_LITERAL: if (ast.getText().length() != 6) { System.err.println("Internal error: incorrect length of webcolor " + "literal should have been detected sooner."); break; } out.print("0xff" + ast.getText()); dumpHiddenAfter(ast); break; // allow for stuff like int(43.2). case CONSTRUCTOR_CAST: final AST nonTerminalTypeNode = child1; final AST terminalTypeNode = child1.getFirstChild(); final AST exprToCast = child2; /* // if this is a string type, add .valueOf() if (nonTerminalTypeNode.getType() == PdeRecognizer.TYPE && terminalTypeNode.getText().equals("String")) { out.print(terminalTypeNode.getText() + ".valueOf"); dumpHiddenAfter(terminalTypeNode); print(exprToCast); // if the expresion to be cast is a string literal, try and parse it. // // ideally, we'd be able to do this for all expressions with a // string type, not just string literals. however, the parser // doesn't currently track expression type, and for full // functionality, we'd need to do semantic analysis to handle // imports so that we could know the return types of method calls. // } else if (exprToCast.getFirstChild().getType() == STRING_LITERAL ) { switch (terminalTypeNode.getType()) { case PdeRecognizer.LITERAL_byte: out.print("Byte.parseByte"); dumpHiddenAfter(terminalTypeNode); print(exprToCast); break; case PdeRecognizer.LITERAL_double: out.print("(new Double"); dumpHiddenAfter(terminalTypeNode); out.print(exprToCast.getFirstChild().getText() + ").doubleValue()"); dumpHiddenAfter(exprToCast.getFirstChild()); break; case PdeRecognizer.LITERAL_float: out.print("(new Float"); dumpHiddenAfter(terminalTypeNode); out.print(exprToCast.getFirstChild().getText() + ").floatValue()"); dumpHiddenAfter(exprToCast.getFirstChild()); break; case PdeRecognizer.LITERAL_int: case PdeRecognizer.LITERAL_color: out.print("Integer.parseInt"); dumpHiddenAfter(terminalTypeNode); print(exprToCast); break; case PdeRecognizer.LITERAL_long: out.print("Long.parseLong"); break; case PdeRecognizer.LITERAL_short: out.print("Short.parseShort"); break; default: throw new RunnerException(Compiler.SUPER_BADNESS); } // for builtin types, use regular casting syntax } else { */ // result of below is (int)(4.0 //out.print("("); //out.print(terminalTypeNode.getText() + ")"); // typename //dumpHiddenAfter(terminalTypeNode); //print(exprToCast); //} //out.print("("); final String pooType = terminalTypeNode.getText(); out.print("PApplet.parse" + Character.toUpperCase(pooType.charAt(0)) + pooType.substring(1)); dumpHiddenAfter(terminalTypeNode); // the left paren print(exprToCast); //out.print("x)"); break; // making floating point literals default to floats, not doubles case NUM_DOUBLE: out.print(ast.getText()); if (Preferences.getBoolean("preproc.substitute_floats")) { //, true) ) { out.print("f"); } dumpHiddenAfter(ast); break; case TYPE_ARGUMENTS: case TYPE_PARAMETERS: printChildren(ast); break; case TYPE_ARGUMENT: case TYPE_PARAMETER: print(ast.getFirstChild()); break; case WILDCARD_TYPE: out.print("? "); print(ast.getFirstChild()); break; case TYPE_LOWER_BOUNDS: out.print("super "); print(ast.getFirstChild()); break; case TYPE_UPPER_BOUNDS: out.print("extends "); print(ast.getFirstChild()); break; default: debug.println("Unrecognized type:" + ast.getType() + " (" + TokenUtil.nameOf(ast) + ")"); break; } stack.pop(); } }
true
true
public void print(final AST ast) throws RunnerException { if (ast == null) { return; } AST parent = null; if (!stack.isEmpty()) { parent = (AST) stack.peek(); } stack.push(ast); final AST child1 = ast.getFirstChild(); AST child2 = null; AST child3 = null; if (child1 != null) { child2 = child1.getNextSibling(); if (child2 != null) { child3 = child2.getNextSibling(); } } switch (ast.getType()) { // The top of the tree looks like this: // ROOT_ID "Whatever.java" // package // imports // class definition case ROOT_ID: dumpHiddenTokens(pdePreprocessor.getInitialHiddenToken()); printChildren(ast); break; // supporting a "package" statement in a PDE program has // a bunch of issues with it that need to dealt in the compilation // code too, so this isn't actually tested. case PACKAGE_DEF: out.print("package"); dumpHiddenAfter(ast); print(ast.getFirstChild()); break; // IMPORT has exactly one child case IMPORT: out.print("import"); dumpHiddenAfter(ast); print(ast.getFirstChild()); break; case STATIC_IMPORT: out.print("import static"); dumpHiddenAfter(ast); print(ast.getFirstChild()); break; case CLASS_DEF: case INTERFACE_DEF: print(getChild(ast, MODIFIERS)); if (ast.getType() == CLASS_DEF) { out.print("class"); } else { out.print("interface"); } dumpHiddenBefore(getChild(ast, IDENT)); print(getChild(ast, IDENT)); print(getChild(ast, TYPE_PARAMETERS)); print(getChild(ast, EXTENDS_CLAUSE)); print(getChild(ast, IMPLEMENTS_CLAUSE)); print(getChild(ast, OBJBLOCK)); break; case EXTENDS_CLAUSE: if (hasChildren(ast)) { out.print("extends"); dumpHiddenBefore(getBestPrintableNode(ast, false)); printChildren(ast); } break; case IMPLEMENTS_CLAUSE: if (hasChildren(ast)) { out.print("implements"); dumpHiddenBefore(getBestPrintableNode(ast, false)); printChildren(ast); } break; // DOT always has exactly two children. case DOT: print(child1); out.print("."); dumpHiddenAfter(ast); print(child2); break; case MODIFIERS: case OBJBLOCK: case CTOR_DEF: //case METHOD_DEF: case PARAMETERS: case PARAMETER_DEF: case VARIABLE_PARAMETER_DEF: case VARIABLE_DEF: case TYPE: case SLIST: case ELIST: case ARRAY_DECLARATOR: case TYPECAST: case EXPR: case ARRAY_INIT: case FOR_INIT: case FOR_CONDITION: case FOR_ITERATOR: case METHOD_CALL: case INSTANCE_INIT: case INDEX_OP: case SUPER_CTOR_CALL: case CTOR_CALL: printChildren(ast); break; case METHOD_DEF: // kids seem to be: MODIFIERS TYPE setup PARAMETERS //AST parent = (AST) stack.peek(); final AST modifiersChild = ast.getFirstChild(); final AST typeChild = modifiersChild.getNextSibling(); final AST methodNameChild = typeChild.getNextSibling(); final AST parametersChild = methodNameChild.getNextSibling(); // to output, use print(child) on each of the four final String methodName = methodNameChild.getText(); if (methodName.equals("main")) { pdePreprocessor.setFoundMain(true); } // if this method doesn't have a specifier, make it public // (useful for setup/keyPressed/etc) boolean foundSpecifier = false; AST child = modifiersChild.getFirstChild(); while (child != null) { final String childText = child.getText(); if (childText.equals("public") || childText.equals("protected") || childText.equals("private")) { foundSpecifier = true; child = null; } else { //out.print("." + child.getText() + "."); child = child.getNextSibling(); } } if (!foundSpecifier) { out.print("public "); } printChildren(ast); // everything is fine break; // if we have two children, it's of the form "a=0" // if just one child, it's of the form "=0" (where the // lhs is above this AST). case ASSIGN: if (child2 != null) { print(child1); out.print("="); dumpHiddenAfter(ast); print(child2); } else { out.print("="); dumpHiddenAfter(ast); print(child1); } break; // binary operators: case PLUS: case MINUS: case DIV: case MOD: case NOT_EQUAL: case EQUAL: case LT: case GT: case LE: case GE: case LOR: case LAND: case BOR: case BXOR: case BAND: case SL: case SR: case BSR: case LITERAL_instanceof: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: printBinaryOperator(ast); break; case LITERAL_for: out.print(ast.getText()); dumpHiddenAfter(ast); if (child1.getType() == FOR_EACH_CLAUSE) { printChildren(child1); print(child2); } else { printChildren(ast); } break; case POST_INC: case POST_DEC: print(child1); out.print(ast.getText()); dumpHiddenAfter(ast); break; // unary operators: case BNOT: case LNOT: case INC: case DEC: case UNARY_MINUS: case UNARY_PLUS: out.print(ast.getText()); dumpHiddenAfter(ast); print(child1); break; case LITERAL_new: out.print("new"); dumpHiddenAfter(ast); print(child1); print(child2); // "new String[] {...}": the stuff in {} is child3 if (child3 != null) { print(child3); } break; case LITERAL_return: out.print("return"); dumpHiddenAfter(ast); print(child1); break; case STATIC_INIT: out.print("static"); dumpHiddenBefore(getBestPrintableNode(ast, false)); print(child1); break; case LITERAL_switch: out.print("switch"); dumpHiddenAfter(ast); printChildren(ast); break; case LABELED_STAT: case CASE_GROUP: printChildren(ast); break; case LITERAL_case: out.print("case"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_default: out.print("default"); dumpHiddenAfter(ast); printChildren(ast); break; case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: out.print(ast.getText()); dumpHiddenAfter(ast); break; case LITERAL_synchronized: // 0137 to fix bug #136 out.print(ast.getText()); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_static: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: //case LITERAL_synchronized: // 0137 to fix bug #136 case LITERAL_volatile: case LITERAL_class: // 0176 to fix bug #1466 case FINAL: case ABSTRACT: case LITERAL_package: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_true: case LITERAL_false: case LITERAL_null: case SEMI: case LITERAL_this: case LITERAL_super: out.print(ast.getText()); dumpHiddenAfter(ast); break; case EMPTY_STAT: case EMPTY_FIELD: break; case LITERAL_continue: case LITERAL_break: out.print(ast.getText()); dumpHiddenAfter(ast); if (child1 != null) {// maybe label print(child1); } break; // yuck: Distinguish between "import x.y.*" and "x = 1 * 3" case STAR: if (hasChildren(ast)) { // the binary mult. operator printBinaryOperator(ast); } else { // the special "*" in import: out.print("*"); dumpHiddenAfter(ast); } break; case LITERAL_throws: out.print("throws"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_if: printIfThenElse(ast); break; case LITERAL_while: out.print("while"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_do: out.print("do"); dumpHiddenAfter(ast); print(child1); // an SLIST out.print("while"); dumpHiddenBefore(getBestPrintableNode(child2, false)); print(child2); // an EXPR break; case LITERAL_try: out.print("try"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_catch: out.print("catch"); dumpHiddenAfter(ast); printChildren(ast); break; // the first child is the "try" and the second is the SLIST case LITERAL_finally: out.print("finally"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_throw: out.print("throw"); dumpHiddenAfter(ast); print(child1); break; // the dreaded trinary operator case QUESTION: print(child1); out.print("?"); dumpHiddenAfter(ast); print(child2); print(child3); break; // pde specific or modified tokens start here // Image -> BImage, Font -> BFont as appropriate case IDENT: /* if (ast.getText().equals("Image") && Preferences.getBoolean("preproc.substitute_image")) { //, true)) { out.print("BImage"); } else if (ast.getText().equals("Font") && Preferences.getBoolean("preproc.substitute_font")) { //, true)) { out.print("BFont"); } else { */ out.print(ast.getText()); //} dumpHiddenAfter(ast); break; // the color datatype is just an alias for int case LITERAL_color: out.print("int"); dumpHiddenAfter(ast); break; case WEBCOLOR_LITERAL: if (ast.getText().length() != 6) { System.err.println("Internal error: incorrect length of webcolor " + "literal should have been detected sooner."); break; } out.print("0xff" + ast.getText()); dumpHiddenAfter(ast); break; // allow for stuff like int(43.2). case CONSTRUCTOR_CAST: final AST nonTerminalTypeNode = child1; final AST terminalTypeNode = child1.getFirstChild(); final AST exprToCast = child2; /* // if this is a string type, add .valueOf() if (nonTerminalTypeNode.getType() == PdeRecognizer.TYPE && terminalTypeNode.getText().equals("String")) { out.print(terminalTypeNode.getText() + ".valueOf"); dumpHiddenAfter(terminalTypeNode); print(exprToCast); // if the expresion to be cast is a string literal, try and parse it. // // ideally, we'd be able to do this for all expressions with a // string type, not just string literals. however, the parser // doesn't currently track expression type, and for full // functionality, we'd need to do semantic analysis to handle // imports so that we could know the return types of method calls. // } else if (exprToCast.getFirstChild().getType() == STRING_LITERAL ) { switch (terminalTypeNode.getType()) { case PdeRecognizer.LITERAL_byte: out.print("Byte.parseByte"); dumpHiddenAfter(terminalTypeNode); print(exprToCast); break; case PdeRecognizer.LITERAL_double: out.print("(new Double"); dumpHiddenAfter(terminalTypeNode); out.print(exprToCast.getFirstChild().getText() + ").doubleValue()"); dumpHiddenAfter(exprToCast.getFirstChild()); break; case PdeRecognizer.LITERAL_float: out.print("(new Float"); dumpHiddenAfter(terminalTypeNode); out.print(exprToCast.getFirstChild().getText() + ").floatValue()"); dumpHiddenAfter(exprToCast.getFirstChild()); break; case PdeRecognizer.LITERAL_int: case PdeRecognizer.LITERAL_color: out.print("Integer.parseInt"); dumpHiddenAfter(terminalTypeNode); print(exprToCast); break; case PdeRecognizer.LITERAL_long: out.print("Long.parseLong"); break; case PdeRecognizer.LITERAL_short: out.print("Short.parseShort"); break; default: throw new RunnerException(Compiler.SUPER_BADNESS); } // for builtin types, use regular casting syntax } else { */ // result of below is (int)(4.0 //out.print("("); //out.print(terminalTypeNode.getText() + ")"); // typename //dumpHiddenAfter(terminalTypeNode); //print(exprToCast); //} //out.print("("); final String pooType = terminalTypeNode.getText(); out.print("PApplet.parse" + Character.toUpperCase(pooType.charAt(0)) + pooType.substring(1)); dumpHiddenAfter(terminalTypeNode); // the left paren print(exprToCast); //out.print("x)"); break; // making floating point literals default to floats, not doubles case NUM_DOUBLE: out.print(ast.getText()); if (Preferences.getBoolean("preproc.substitute_floats")) { //, true) ) { out.print("f"); } dumpHiddenAfter(ast); break; case TYPE_ARGUMENTS: case TYPE_PARAMETERS: printChildren(ast); break; case TYPE_ARGUMENT: case TYPE_PARAMETER: print(ast.getFirstChild()); break; case WILDCARD_TYPE: out.print("? "); print(ast.getFirstChild()); break; case TYPE_LOWER_BOUNDS: out.print("super "); print(ast.getFirstChild()); break; case TYPE_UPPER_BOUNDS: out.print("extends "); print(ast.getFirstChild()); break; default: debug.println("Unrecognized type:" + ast.getType() + " (" + TokenUtil.nameOf(ast) + ")"); break; } stack.pop(); } }
public void print(final AST ast) throws RunnerException { if (ast == null) { return; } AST parent = null; if (!stack.isEmpty()) { parent = (AST) stack.peek(); } stack.push(ast); final AST child1 = ast.getFirstChild(); AST child2 = null; AST child3 = null; if (child1 != null) { child2 = child1.getNextSibling(); if (child2 != null) { child3 = child2.getNextSibling(); } } switch (ast.getType()) { // The top of the tree looks like this: // ROOT_ID "Whatever.java" // package // imports // class definition case ROOT_ID: dumpHiddenTokens(pdePreprocessor.getInitialHiddenToken()); printChildren(ast); break; // supporting a "package" statement in a PDE program has // a bunch of issues with it that need to dealt in the compilation // code too, so this isn't actually tested. case PACKAGE_DEF: out.print("package"); dumpHiddenAfter(ast); print(ast.getFirstChild()); break; // IMPORT has exactly one child case IMPORT: out.print("import"); dumpHiddenAfter(ast); print(ast.getFirstChild()); break; case STATIC_IMPORT: out.print("import static"); dumpHiddenAfter(ast); print(ast.getFirstChild()); break; case CLASS_DEF: case INTERFACE_DEF: print(getChild(ast, MODIFIERS)); if (ast.getType() == CLASS_DEF) { out.print("class"); } else { out.print("interface"); } dumpHiddenBefore(getChild(ast, IDENT)); print(getChild(ast, IDENT)); print(getChild(ast, TYPE_PARAMETERS)); print(getChild(ast, EXTENDS_CLAUSE)); print(getChild(ast, IMPLEMENTS_CLAUSE)); print(getChild(ast, OBJBLOCK)); break; case EXTENDS_CLAUSE: if (hasChildren(ast)) { out.print("extends"); dumpHiddenBefore(getBestPrintableNode(ast, false)); printChildren(ast); } break; case IMPLEMENTS_CLAUSE: if (hasChildren(ast)) { out.print("implements"); dumpHiddenBefore(getBestPrintableNode(ast, false)); printChildren(ast); } break; // DOT always has exactly two children. case DOT: print(child1); out.print("."); dumpHiddenAfter(ast); print(child2); break; case MODIFIERS: case OBJBLOCK: case CTOR_DEF: //case METHOD_DEF: case PARAMETERS: case PARAMETER_DEF: case VARIABLE_PARAMETER_DEF: case VARIABLE_DEF: case TYPE: case SLIST: case ELIST: case ARRAY_DECLARATOR: case TYPECAST: case EXPR: case ARRAY_INIT: case FOR_INIT: case FOR_CONDITION: case FOR_ITERATOR: case METHOD_CALL: case INSTANCE_INIT: case INDEX_OP: case SUPER_CTOR_CALL: case CTOR_CALL: printChildren(ast); break; case METHOD_DEF: // kids seem to be: MODIFIERS TYPE setup PARAMETERS //AST parent = (AST) stack.peek(); final AST modifiersChild = ast.getFirstChild(); final AST typeChild = modifiersChild.getNextSibling(); final AST methodNameChild = typeChild.getNextSibling(); final AST parametersChild = methodNameChild.getNextSibling(); // to output, use print(child) on each of the four final String methodName = methodNameChild.getText(); if (methodName.equals("main")) { pdePreprocessor.setFoundMain(true); } // if this method doesn't have a specifier, make it public // (useful for setup/keyPressed/etc) boolean foundSpecifier = false; AST child = modifiersChild.getFirstChild(); while (child != null) { final String childText = child.getText(); if (childText.equals("public") || childText.equals("protected") || childText.equals("private")) { foundSpecifier = true; child = null; } else { //out.print("." + child.getText() + "."); child = child.getNextSibling(); } } if (!foundSpecifier) { out.print("public "); } printChildren(ast); // everything is fine break; // if we have two children, it's of the form "a=0" // if just one child, it's of the form "=0" (where the // lhs is above this AST). case ASSIGN: if (child2 != null) { print(child1); out.print("="); dumpHiddenAfter(ast); print(child2); } else { out.print("="); dumpHiddenAfter(ast); print(child1); } break; // binary operators: case PLUS: case MINUS: case DIV: case MOD: case NOT_EQUAL: case EQUAL: case LT: case GT: case LE: case GE: case LOR: case LAND: case BOR: case BXOR: case BAND: case SL: case SR: case BSR: case LITERAL_instanceof: case PLUS_ASSIGN: case MINUS_ASSIGN: case STAR_ASSIGN: case DIV_ASSIGN: case MOD_ASSIGN: case SR_ASSIGN: case BSR_ASSIGN: case SL_ASSIGN: case BAND_ASSIGN: case BXOR_ASSIGN: case BOR_ASSIGN: printBinaryOperator(ast); break; case LITERAL_for: out.print(ast.getText()); dumpHiddenAfter(ast); if (child1.getType() == FOR_EACH_CLAUSE) { printChildren(child1); print(child2); } else { printChildren(ast); } break; case POST_INC: case POST_DEC: print(child1); out.print(ast.getText()); dumpHiddenAfter(ast); break; // unary operators: case BNOT: case LNOT: case INC: case DEC: case UNARY_MINUS: case UNARY_PLUS: out.print(ast.getText()); dumpHiddenAfter(ast); print(child1); break; case LITERAL_new: out.print("new"); dumpHiddenAfter(ast); print(child1); print(child2); // "new String[] {...}": the stuff in {} is child3 if (child3 != null) { print(child3); } break; case LITERAL_return: out.print("return"); dumpHiddenAfter(ast); print(child1); break; case STATIC_INIT: out.print("static"); dumpHiddenBefore(getBestPrintableNode(ast, false)); print(child1); break; case LITERAL_switch: out.print("switch"); dumpHiddenAfter(ast); printChildren(ast); break; case LABELED_STAT: case CASE_GROUP: printChildren(ast); break; case LITERAL_case: out.print("case"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_default: out.print("default"); dumpHiddenAfter(ast); printChildren(ast); break; case NUM_INT: case CHAR_LITERAL: case STRING_LITERAL: case NUM_FLOAT: case NUM_LONG: out.print(ast.getText()); dumpHiddenAfter(ast); break; case LITERAL_synchronized: // 0137 to fix bug #136 case LITERAL_assert: out.print(ast.getText()); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_private: case LITERAL_public: case LITERAL_protected: case LITERAL_static: case LITERAL_transient: case LITERAL_native: case LITERAL_threadsafe: //case LITERAL_synchronized: // 0137 to fix bug #136 case LITERAL_volatile: case LITERAL_class: // 0176 to fix bug #1466 case FINAL: case ABSTRACT: case LITERAL_package: case LITERAL_void: case LITERAL_boolean: case LITERAL_byte: case LITERAL_char: case LITERAL_short: case LITERAL_int: case LITERAL_float: case LITERAL_long: case LITERAL_double: case LITERAL_true: case LITERAL_false: case LITERAL_null: case SEMI: case LITERAL_this: case LITERAL_super: out.print(ast.getText()); dumpHiddenAfter(ast); break; case EMPTY_STAT: case EMPTY_FIELD: break; case LITERAL_continue: case LITERAL_break: out.print(ast.getText()); dumpHiddenAfter(ast); if (child1 != null) {// maybe label print(child1); } break; // yuck: Distinguish between "import x.y.*" and "x = 1 * 3" case STAR: if (hasChildren(ast)) { // the binary mult. operator printBinaryOperator(ast); } else { // the special "*" in import: out.print("*"); dumpHiddenAfter(ast); } break; case LITERAL_throws: out.print("throws"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_if: printIfThenElse(ast); break; case LITERAL_while: out.print("while"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_do: out.print("do"); dumpHiddenAfter(ast); print(child1); // an SLIST out.print("while"); dumpHiddenBefore(getBestPrintableNode(child2, false)); print(child2); // an EXPR break; case LITERAL_try: out.print("try"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_catch: out.print("catch"); dumpHiddenAfter(ast); printChildren(ast); break; // the first child is the "try" and the second is the SLIST case LITERAL_finally: out.print("finally"); dumpHiddenAfter(ast); printChildren(ast); break; case LITERAL_throw: out.print("throw"); dumpHiddenAfter(ast); print(child1); break; // the dreaded trinary operator case QUESTION: print(child1); out.print("?"); dumpHiddenAfter(ast); print(child2); print(child3); break; // pde specific or modified tokens start here // Image -> BImage, Font -> BFont as appropriate case IDENT: /* if (ast.getText().equals("Image") && Preferences.getBoolean("preproc.substitute_image")) { //, true)) { out.print("BImage"); } else if (ast.getText().equals("Font") && Preferences.getBoolean("preproc.substitute_font")) { //, true)) { out.print("BFont"); } else { */ out.print(ast.getText()); //} dumpHiddenAfter(ast); break; // the color datatype is just an alias for int case LITERAL_color: out.print("int"); dumpHiddenAfter(ast); break; case WEBCOLOR_LITERAL: if (ast.getText().length() != 6) { System.err.println("Internal error: incorrect length of webcolor " + "literal should have been detected sooner."); break; } out.print("0xff" + ast.getText()); dumpHiddenAfter(ast); break; // allow for stuff like int(43.2). case CONSTRUCTOR_CAST: final AST nonTerminalTypeNode = child1; final AST terminalTypeNode = child1.getFirstChild(); final AST exprToCast = child2; /* // if this is a string type, add .valueOf() if (nonTerminalTypeNode.getType() == PdeRecognizer.TYPE && terminalTypeNode.getText().equals("String")) { out.print(terminalTypeNode.getText() + ".valueOf"); dumpHiddenAfter(terminalTypeNode); print(exprToCast); // if the expresion to be cast is a string literal, try and parse it. // // ideally, we'd be able to do this for all expressions with a // string type, not just string literals. however, the parser // doesn't currently track expression type, and for full // functionality, we'd need to do semantic analysis to handle // imports so that we could know the return types of method calls. // } else if (exprToCast.getFirstChild().getType() == STRING_LITERAL ) { switch (terminalTypeNode.getType()) { case PdeRecognizer.LITERAL_byte: out.print("Byte.parseByte"); dumpHiddenAfter(terminalTypeNode); print(exprToCast); break; case PdeRecognizer.LITERAL_double: out.print("(new Double"); dumpHiddenAfter(terminalTypeNode); out.print(exprToCast.getFirstChild().getText() + ").doubleValue()"); dumpHiddenAfter(exprToCast.getFirstChild()); break; case PdeRecognizer.LITERAL_float: out.print("(new Float"); dumpHiddenAfter(terminalTypeNode); out.print(exprToCast.getFirstChild().getText() + ").floatValue()"); dumpHiddenAfter(exprToCast.getFirstChild()); break; case PdeRecognizer.LITERAL_int: case PdeRecognizer.LITERAL_color: out.print("Integer.parseInt"); dumpHiddenAfter(terminalTypeNode); print(exprToCast); break; case PdeRecognizer.LITERAL_long: out.print("Long.parseLong"); break; case PdeRecognizer.LITERAL_short: out.print("Short.parseShort"); break; default: throw new RunnerException(Compiler.SUPER_BADNESS); } // for builtin types, use regular casting syntax } else { */ // result of below is (int)(4.0 //out.print("("); //out.print(terminalTypeNode.getText() + ")"); // typename //dumpHiddenAfter(terminalTypeNode); //print(exprToCast); //} //out.print("("); final String pooType = terminalTypeNode.getText(); out.print("PApplet.parse" + Character.toUpperCase(pooType.charAt(0)) + pooType.substring(1)); dumpHiddenAfter(terminalTypeNode); // the left paren print(exprToCast); //out.print("x)"); break; // making floating point literals default to floats, not doubles case NUM_DOUBLE: out.print(ast.getText()); if (Preferences.getBoolean("preproc.substitute_floats")) { //, true) ) { out.print("f"); } dumpHiddenAfter(ast); break; case TYPE_ARGUMENTS: case TYPE_PARAMETERS: printChildren(ast); break; case TYPE_ARGUMENT: case TYPE_PARAMETER: print(ast.getFirstChild()); break; case WILDCARD_TYPE: out.print("? "); print(ast.getFirstChild()); break; case TYPE_LOWER_BOUNDS: out.print("super "); print(ast.getFirstChild()); break; case TYPE_UPPER_BOUNDS: out.print("extends "); print(ast.getFirstChild()); break; default: debug.println("Unrecognized type:" + ast.getType() + " (" + TokenUtil.nameOf(ast) + ")"); break; } stack.pop(); } }
diff --git a/src/main/java/de/frosner/datagenerator/gui/main/SwingMenu.java b/src/main/java/de/frosner/datagenerator/gui/main/SwingMenu.java index 71c4356..03faad0 100644 --- a/src/main/java/de/frosner/datagenerator/gui/main/SwingMenu.java +++ b/src/main/java/de/frosner/datagenerator/gui/main/SwingMenu.java @@ -1,557 +1,558 @@ package de.frosner.datagenerator.gui.main; import static de.frosner.datagenerator.gui.verifiers.InputVerifier.isDouble; import static de.frosner.datagenerator.gui.verifiers.InputVerifier.isInteger; import static de.frosner.datagenerator.gui.verifiers.InputVerifier.isName; import static de.frosner.datagenerator.gui.verifiers.InputVerifier.verifyComponent; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SpringLayout; import javax.swing.border.LineBorder; import javax.swing.filechooser.FileFilter; import com.google.common.collect.Lists; import de.frosner.datagenerator.distributions.BernoulliDistribution; import de.frosner.datagenerator.distributions.CategorialDistribution; import de.frosner.datagenerator.distributions.GaussianDistribution; import de.frosner.datagenerator.exceptions.UnknownActionEventSourceException; import de.frosner.datagenerator.exceptions.UnsupportedSelectionException; import de.frosner.datagenerator.export.CsvFileExportConfiguration; import de.frosner.datagenerator.features.FeatureDefinition; import de.frosner.datagenerator.gui.services.DataGeneratorService; import de.frosner.datagenerator.gui.services.GenerationButtonsToggleManager; import de.frosner.datagenerator.gui.services.PreviewTableManager; import de.frosner.datagenerator.gui.services.ProgressBarManager; import de.frosner.datagenerator.gui.services.TextAreaLogManager; import de.frosner.datagenerator.util.ApplicationMetaData; import de.frosner.datagenerator.util.VisibleForTesting; public final class SwingMenu extends JFrame implements ActionListener { private static final long serialVersionUID = ApplicationMetaData.SERIAL_VERSION_UID; private static final int LINE_HEIGHT = 30; private static final int LINE_WIDTH = 180; private static final int PADDING = 5; @VisibleForTesting final JButton _addFeatureButton; @VisibleForTesting final JButton _removeFeatureButton; @VisibleForTesting final JButton _generateDataButton; @VisibleForTesting final JButton _abortDataGenerationButton; private final JLabel _addFeatureDistributionLabel; @VisibleForTesting final JComboBox _addFeatureDistributionSelection; private final JLabel _featureNameLabel; @VisibleForTesting final JTextField _featureNameField; private final JLabel _gaussianMeanLabel; @VisibleForTesting final JTextField _gaussianMeanField; private final JLabel _gaussianSigmaLabel; @VisibleForTesting final JTextField _gaussianSigmaField; private final JLabel _bernoulliProbabilityLabel; @VisibleForTesting final JTextField _bernoulliProbabilityField; private final JLabel _uniformCategorialNumberOfStatesLabel; @VisibleForTesting final JTextField _uniformCategorialNumberOfStatesField; private final JLabel _numberOfInstancesLabel; @VisibleForTesting final JTextField _numberOfInstancesField; private final JLabel _exportFileLabel; @VisibleForTesting final JFileChooser _exportFileDialog; @VisibleForTesting final JButton _exportFileButton; @VisibleForTesting final JTextField _exportFileField; @VisibleForTesting final JCheckBox _exportInstanceIdsBox; @VisibleForTesting final JCheckBox _exportFeatureNamesBox; @VisibleForTesting static final FileFilter CSV_FILE_FILTER = new ExtensionFileFilter("Comma Separated Values (.csv)", "csv"); @VisibleForTesting static final FileFilter ALL_FILE_FILTER = new AllFileFilter(); @VisibleForTesting final DefaultListModel _featureListModel; @VisibleForTesting final JList _featureList; private final JScrollPane _featureListScroller; @VisibleForTesting final VariableColumnCountTableModel _previewTableModel; @VisibleForTesting final JTable _previewTable; @VisibleForTesting final JOptionPane _featureDefinitionPane; @VisibleForTesting final JDialog _featureDefinitionDialog; private final JPanel _cards; @VisibleForTesting final JProgressBar _progressBar; @VisibleForTesting final JEditorPane _logArea; private final JScrollPane _logAreaScroller; private final JMenuBar _menuBar; private final JMenu _helpMenu; private final JMenuItem _aboutMenuItem; private GenerateDataButtonWorker _generateDataButtonWorker; public SwingMenu() { // BEGIN frame initialization setTitle(ApplicationMetaData.getName()); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(true); // END frame initialization // BEGIN menu bar initialization _menuBar = new JMenuBar(); setJMenuBar(_menuBar); _helpMenu = new JMenu("Help"); _helpMenu.setMnemonic(KeyEvent.VK_O); _aboutMenuItem = new JMenuItem("About"); _aboutMenuItem.addActionListener(this); _helpMenu.add(_aboutMenuItem); _menuBar.add(_helpMenu); // END menu bar initialization // BEGIN component definition _addFeatureDistributionLabel = new JLabel("Distribution", JLabel.RIGHT); _addFeatureDistributionSelection = new JComboBox(new Object[] { SelectableDistribution.BERNOULLI, SelectableDistribution.UNIFORM_CATEGORIAL, SelectableDistribution.GAUSSIAN }); _addFeatureDistributionSelection.addActionListener(this); _featureNameLabel = new JLabel("Name", JLabel.RIGHT); _featureNameField = new JTextField(); _featureNameField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _gaussianMeanLabel = new JLabel("Mean", JLabel.RIGHT); _gaussianMeanField = new JTextField(); _gaussianMeanField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _gaussianSigmaLabel = new JLabel("Sigma", JLabel.RIGHT); _gaussianSigmaField = new JTextField(); _gaussianSigmaField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _bernoulliProbabilityLabel = new JLabel("P", JLabel.RIGHT); _bernoulliProbabilityField = new JTextField(); _bernoulliProbabilityField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _uniformCategorialNumberOfStatesLabel = new JLabel("#States", JLabel.RIGHT); _uniformCategorialNumberOfStatesField = new JTextField(); _uniformCategorialNumberOfStatesField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _addFeatureButton = new JButton("Add Feature"); _addFeatureButton.addActionListener(this); _featureDefinitionDialog = new JDialog(this, "Add Feature", true); _featureListModel = new DefaultListModel(); _featureList = new JList(_featureListModel); _featureList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); _featureList.setFocusable(true); _featureListScroller = new JScrollPane(_featureList); _featureListScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); _featureListScroller.setFocusable(false); _removeFeatureButton = new JButton("Remove Feature"); _removeFeatureButton.addActionListener(this); _numberOfInstancesLabel = new JLabel("#Instances", JLabel.RIGHT); _numberOfInstancesField = new JTextField(); _numberOfInstancesField.setPreferredSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _exportFileLabel = new JLabel("Export File", JLabel.RIGHT); _exportFileDialog = new ExportFileChooser(ALL_FILE_FILTER); _exportFileDialog.addChoosableFileFilter(CSV_FILE_FILTER); _exportFileDialog.setFileFilter(CSV_FILE_FILTER); _exportFileButton = new JButton("..."); _exportFileButton.addActionListener(this); _exportFileField = new JTextField(); _exportFileField.setEditable(false); _exportFileField.setPreferredSize(new Dimension(LINE_WIDTH - 25, LINE_HEIGHT)); _exportInstanceIdsBox = new JCheckBox("Instance IDs"); _exportFeatureNamesBox = new JCheckBox("Feature Names"); _progressBar = new JProgressBar(0, 100); ProgressBarManager.setProgressBar(_progressBar); _generateDataButton = new JButton("Generate Data"); _generateDataButton.addActionListener(this); _abortDataGenerationButton = new JButton("Abort Generation"); _abortDataGenerationButton.addActionListener(this); _abortDataGenerationButton.setEnabled(false); GenerationButtonsToggleManager.setButtons(_generateDataButton, _abortDataGenerationButton); _previewTableModel = new VariableColumnCountTableModel(8, 4); _previewTable = new JTable(_previewTableModel); _previewTable.setEnabled(false); PreviewTableManager.setPreviewTable(_previewTableModel); _logArea = new JEditorPane("text/html", null); _logArea.setPreferredSize(new Dimension(LINE_WIDTH, 70)); _logAreaScroller = new JScrollPane(_logArea); TextAreaLogManager.setLogArea(_logArea); _logArea.setBorder(new LineBorder(Color.gray, 1)); _logArea.setEditable(false); _logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); _logArea.setAutoscrolls(true); _logAreaScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); // END component definition // BEGIN main layout Container contentPane = getContentPane(); contentPane.setLayout(new SpringLayout()); JPanel topPanel = new JPanel(); topPanel.setLayout(new SpringLayout()); topPanel.setMaximumSize(new Dimension(0, 0)); // avoid resizing contentPane.add(topPanel); JPanel removeFeaturePanel = new JPanel(); removeFeaturePanel.setLayout(new SpringLayout()); topPanel.add(removeFeaturePanel); JPanel featureListPanel = new JPanel(); removeFeaturePanel.add(featureListPanel); featureListPanel.setLayout(new BorderLayout()); featureListPanel.add(_featureListScroller, BorderLayout.CENTER); featureListPanel.setPreferredSize(new Dimension(LINE_WIDTH, 5)); SpringUtilities.makeCompactGrid(removeFeaturePanel, 1, 1, 0, 0, PADDING, PADDING); JPanel generateDataPanel = new JPanel(); topPanel.add(generateDataPanel); generateDataPanel.setLayout(new SpringLayout()); generateDataPanel.add(_numberOfInstancesLabel); generateDataPanel.add(_numberOfInstancesField); generateDataPanel.add(_exportFileLabel); JPanel exportFileSubPanel = new JPanel(); generateDataPanel.add(exportFileSubPanel); exportFileSubPanel.setLayout(new SpringLayout()); exportFileSubPanel.add(_exportFileField); exportFileSubPanel.add(_exportFileButton); JPanel exportCheckBoxPanel = new JPanel(); generateDataPanel.add(new JLabel()); generateDataPanel.add(exportCheckBoxPanel); exportCheckBoxPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); exportCheckBoxPanel.add(_exportInstanceIdsBox); exportCheckBoxPanel.add(_exportFeatureNamesBox); SpringUtilities.makeCompactGrid(exportFileSubPanel, 1, 2, 0, 0, 0, 0); SpringUtilities.makeCompactGrid(generateDataPanel, 3, 2, 0, 0, PADDING, PADDING); JPanel featureButtonPanel = new JPanel(); featureButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); topPanel.add(featureButtonPanel); featureButtonPanel.add(new JLabel(" ")); featureButtonPanel.add(_removeFeatureButton, BorderLayout.EAST); featureButtonPanel.add(_addFeatureButton, BorderLayout.EAST); JPanel generateDataButtonPanel = new JPanel(); generateDataButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); topPanel.add(generateDataButtonPanel); generateDataButtonPanel.add(_generateDataButton, BorderLayout.EAST); SpringUtilities.makeCompactGrid(topPanel, 2, 2, 0, 0, 0, 0); contentPane.add(_previewTable); JPanel progressPanel = new JPanel(); contentPane.add(progressPanel); progressPanel.setLayout(new SpringLayout()); progressPanel.add(_progressBar); progressPanel.add(_abortDataGenerationButton); SpringUtilities.makeCompactGrid(progressPanel, 1, 2, 0, 0, 0, 0); contentPane.add(_logAreaScroller); SpringUtilities.makeCompactGrid(contentPane, 4, 1, 15, 15, 15, 15); // END main layout // BEGIN dialogs layout _cards = new JPanel(); _cards.setLayout(new CardLayout()); JPanel trashPanel = new JPanel(); // container for trash components JLabel trashLabel = new JLabel(""); // used as placeholder JTextField trashField = new JTextField("XXXXXXXXXXXXXXXXXXXXX"); // used as placeholder trashField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); JPanel bernoulliPanel = new JPanel(); _cards.add(bernoulliPanel, SelectableDistribution.BERNOULLI); bernoulliPanel.setLayout(new SpringLayout()); bernoulliPanel.add(_bernoulliProbabilityLabel); bernoulliPanel.add(_bernoulliProbabilityField); bernoulliPanel.add(trashLabel); bernoulliPanel.add(trashField); SpringUtilities.makeCompactGrid(bernoulliPanel, 2, 2, 0, 0, PADDING, PADDING); JPanel uniformCategorialPanel = new JPanel(); _cards.add(uniformCategorialPanel, SelectableDistribution.UNIFORM_CATEGORIAL); uniformCategorialPanel.setLayout(new SpringLayout()); uniformCategorialPanel.add(_uniformCategorialNumberOfStatesLabel); uniformCategorialPanel.add(_uniformCategorialNumberOfStatesField); JLabel filler = new JLabel(""); filler.setSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); uniformCategorialPanel.add(trashLabel); uniformCategorialPanel.add(trashField); SpringUtilities.makeCompactGrid(uniformCategorialPanel, 2, 2, 0, 0, PADDING, PADDING); JPanel gaussianPanel = new JPanel(); _cards.add(gaussianPanel, SelectableDistribution.GAUSSIAN); gaussianPanel.setLayout(new SpringLayout()); gaussianPanel.add(_gaussianMeanLabel); gaussianPanel.add(_gaussianMeanField); gaussianPanel.add(_gaussianSigmaLabel); gaussianPanel.add(_gaussianSigmaField); SpringUtilities.makeCompactGrid(gaussianPanel, 2, 2, 0, 0, PADDING, PADDING); JPanel featureDefinitionDialogPanel = new JPanel(); featureDefinitionDialogPanel.setLayout(new SpringLayout()); JPanel distributionSelectionPanel = new JPanel(); distributionSelectionPanel.setLayout(new SpringLayout()); featureDefinitionDialogPanel.add(distributionSelectionPanel); distributionSelectionPanel.add(_addFeatureDistributionLabel); distributionSelectionPanel.add(_addFeatureDistributionSelection); distributionSelectionPanel.add(_featureNameLabel); distributionSelectionPanel.add(_featureNameField); SpringUtilities.makeCompactGrid(distributionSelectionPanel, 2, 2, 0, 0, PADDING, PADDING); featureDefinitionDialogPanel.add(new JLabel(" ")); featureDefinitionDialogPanel.add(new JSeparator()); featureDefinitionDialogPanel.add(new JLabel(" ")); featureDefinitionDialogPanel.add(new JLabel("Distribution Parameters", JLabel.LEFT)); featureDefinitionDialogPanel.add(new JLabel(" ")); featureDefinitionDialogPanel.add(_cards); SpringUtilities.makeCompactGrid(featureDefinitionDialogPanel, 7, 1, 5, 0, 0, 0); trashPanel.add(trashLabel); // dispose label trashPanel.add(trashField); // dispose field _featureDefinitionPane = new JOptionPane(featureDefinitionDialogPanel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); _featureDefinitionDialog.setContentPane(_featureDefinitionPane); _featureDefinitionDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); _featureDefinitionPane.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (_featureDefinitionDialog.isVisible() && (e.getSource() == _featureDefinitionPane) && (prop.equals(JOptionPane.VALUE_PROPERTY))) { if (_featureDefinitionPane.getValue().equals(JOptionPane.OK_OPTION)) { if (verifyInputsAndAddFeatureDefinition()) { _featureDefinitionDialog.setVisible(false); _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } else { _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } } else if (_featureDefinitionPane.getValue().equals(JOptionPane.UNINITIALIZED_VALUE)) { // Do nothing as this happens when OK was clicked but inputs could not be verified } else { _featureDefinitionDialog.setVisible(false); + _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } } } }); _featureDefinitionDialog.pack(); _featureDefinitionDialog.setResizable(false); _featureDefinitionDialog.setLocation(getCenteredLocationOf(_featureDefinitionDialog)); // END dialog layouts // BEGIN define custom focus traversal List<Component> focusOrder = Lists.newArrayList(); focusOrder.add(_featureNameField); focusOrder.add(_gaussianMeanField); focusOrder.add(_gaussianSigmaField); focusOrder.add(_addFeatureButton); focusOrder.add(_featureList); focusOrder.add(_removeFeatureButton); focusOrder.add(_numberOfInstancesField); focusOrder.add(_exportFileButton); focusOrder.add(_exportInstanceIdsBox); focusOrder.add(_exportFeatureNamesBox); focusOrder.add(_generateDataButton); focusOrder.add(_abortDataGenerationButton); setFocusTraversalPolicy(new OrderedFocusTraversalPolicy(focusOrder)); // END define custom focus traversal // BEGIN finalize pack(); setLocation(getCenteredLocationOf(this)); setMinimumSize(getSize()); setVisible(true); // END finalize } public void detachGenerateDataButtonWorker() { _generateDataButtonWorker = null; } /** * @throws UnknownActionEventSourceException * if the performed {@linkplain ActionEvent} cannot be handled by the {@linkplain SwingMenu} */ @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source.equals(_addFeatureButton)) { _featureDefinitionDialog.setVisible(true); } else if (source.equals(_addFeatureDistributionSelection)) { ((CardLayout) _cards.getLayout()).show(_cards, (String) _addFeatureDistributionSelection.getSelectedItem()); } else if (source.equals(_removeFeatureButton)) { final int selected = _featureList.getSelectedIndex(); if (selected > -1) { new Thread(new Runnable() { @Override public void run() { DataGeneratorService.INSTANCE.removeFeatureDefinition(selected); } }).start(); _featureListModel.remove(selected); } } else if (source.equals(_exportFileButton)) { if (_exportFileDialog.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { _exportFileField.setText(_exportFileDialog.getSelectedFile().getPath()); verifyComponent(_exportFileField, isName(_exportFileField.getText()).isFileName().verify()); } } else if (e.getSource().equals(_generateDataButton)) { if (verifyComponent(_numberOfInstancesField, isInteger(_numberOfInstancesField.getText()).isPositive() .verify()) & verifyComponent(_featureList, _featureListModel.getSize() > 0) & verifyComponent(_exportFileField, isName(_exportFileField.getText()).isFileName().verify())) { final int numberOfInstances = Integer.parseInt(_numberOfInstancesField.getText()); final File exportFile = _exportFileDialog.getSelectedFile(); final boolean exportInstanceIds = _exportInstanceIdsBox.isSelected(); final boolean exportFeatureNames = _exportFeatureNamesBox.isSelected(); _generateDataButtonWorker = new GenerateDataButtonWorker(numberOfInstances, new CsvFileExportConfiguration(exportFile, exportInstanceIds, exportFeatureNames)); _generateDataButtonWorker.execute(); } } else if (source.equals(_abortDataGenerationButton)) { if (_generateDataButtonWorker != null) { _generateDataButtonWorker.cancel(true); } } else if (source.equals(_aboutMenuItem)) { JTextArea applicationMetaData = new JTextArea(ApplicationMetaData.getName() + "\nVersion: " + ApplicationMetaData.getVersion() + "\nRevision: " + ApplicationMetaData.getRevision() + "\nBuilt on: " + ApplicationMetaData.getTimestamp()); applicationMetaData.setEditable(false); JOptionPane dialog = new JOptionPane(applicationMetaData, JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION); dialog.createDialog("About").setVisible(true); } else { throw new UnknownActionEventSourceException(e.getSource()); } } private boolean verifyInputsAndAddFeatureDefinition() { String name = _featureNameField.getText(); if (!verifyComponent(_featureNameField, isName(_featureNameField.getText()).isNotLongerThan(30))) { return false; } Object selectedItem = _addFeatureDistributionSelection.getSelectedItem(); final FeatureDefinition featureDefinition; if (selectedItem.equals(SelectableDistribution.BERNOULLI)) { if (verifyComponent(_bernoulliProbabilityField, isDouble(_bernoulliProbabilityField.getText()) .isProbability())) { double p = Double.parseDouble(_bernoulliProbabilityField.getText()); featureDefinition = new FeatureDefinition(name, new BernoulliDistribution(p)); } else { return false; } } else if (selectedItem.equals(SelectableDistribution.UNIFORM_CATEGORIAL)) { if (verifyComponent(_uniformCategorialNumberOfStatesField, isInteger( _uniformCategorialNumberOfStatesField.getText()).isPositive().isInInterval(1, 1000))) { int numberOfStates = Integer.parseInt(_uniformCategorialNumberOfStatesField.getText()); List<Double> probabilities = Lists.newArrayList(); for (int i = 0; i < numberOfStates; i++) { probabilities.add(1D / numberOfStates); } featureDefinition = new FeatureDefinition(name, new CategorialDistribution(probabilities)); } else { return false; } } else if (selectedItem.equals(SelectableDistribution.GAUSSIAN)) { if (verifyComponent(_gaussianMeanField, isDouble(_gaussianMeanField.getText()).verify()) & verifyComponent(_gaussianSigmaField, isDouble(_gaussianSigmaField.getText()).isPositive())) { double mean = Double.parseDouble(_gaussianMeanField.getText()); double sigma = Double.parseDouble(_gaussianSigmaField.getText()); featureDefinition = new FeatureDefinition(name, new GaussianDistribution(mean, sigma)); } else { return false; } } else { throw new UnsupportedSelectionException(selectedItem); } new Thread(new Runnable() { @Override public void run() { DataGeneratorService.INSTANCE.addFeatureDefinition(featureDefinition); } }).start(); _featureListModel.addElement(featureDefinition.getName() + " (" + featureDefinition.getDistribution().getType() + ", " + featureDefinition.getDistribution().getParameterDescription() + ")"); verifyComponent(_featureList, _featureListModel.getSize() > 0); return true; } private static Point getCenteredLocationOf(Component component) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Point middle = new Point(screenSize.width / 2, screenSize.height / 2); Point newLocation = new Point(middle.x - (component.getWidth() / 2), middle.y - (component.getHeight() / 2)); return newLocation; } }
true
true
public SwingMenu() { // BEGIN frame initialization setTitle(ApplicationMetaData.getName()); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(true); // END frame initialization // BEGIN menu bar initialization _menuBar = new JMenuBar(); setJMenuBar(_menuBar); _helpMenu = new JMenu("Help"); _helpMenu.setMnemonic(KeyEvent.VK_O); _aboutMenuItem = new JMenuItem("About"); _aboutMenuItem.addActionListener(this); _helpMenu.add(_aboutMenuItem); _menuBar.add(_helpMenu); // END menu bar initialization // BEGIN component definition _addFeatureDistributionLabel = new JLabel("Distribution", JLabel.RIGHT); _addFeatureDistributionSelection = new JComboBox(new Object[] { SelectableDistribution.BERNOULLI, SelectableDistribution.UNIFORM_CATEGORIAL, SelectableDistribution.GAUSSIAN }); _addFeatureDistributionSelection.addActionListener(this); _featureNameLabel = new JLabel("Name", JLabel.RIGHT); _featureNameField = new JTextField(); _featureNameField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _gaussianMeanLabel = new JLabel("Mean", JLabel.RIGHT); _gaussianMeanField = new JTextField(); _gaussianMeanField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _gaussianSigmaLabel = new JLabel("Sigma", JLabel.RIGHT); _gaussianSigmaField = new JTextField(); _gaussianSigmaField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _bernoulliProbabilityLabel = new JLabel("P", JLabel.RIGHT); _bernoulliProbabilityField = new JTextField(); _bernoulliProbabilityField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _uniformCategorialNumberOfStatesLabel = new JLabel("#States", JLabel.RIGHT); _uniformCategorialNumberOfStatesField = new JTextField(); _uniformCategorialNumberOfStatesField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _addFeatureButton = new JButton("Add Feature"); _addFeatureButton.addActionListener(this); _featureDefinitionDialog = new JDialog(this, "Add Feature", true); _featureListModel = new DefaultListModel(); _featureList = new JList(_featureListModel); _featureList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); _featureList.setFocusable(true); _featureListScroller = new JScrollPane(_featureList); _featureListScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); _featureListScroller.setFocusable(false); _removeFeatureButton = new JButton("Remove Feature"); _removeFeatureButton.addActionListener(this); _numberOfInstancesLabel = new JLabel("#Instances", JLabel.RIGHT); _numberOfInstancesField = new JTextField(); _numberOfInstancesField.setPreferredSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _exportFileLabel = new JLabel("Export File", JLabel.RIGHT); _exportFileDialog = new ExportFileChooser(ALL_FILE_FILTER); _exportFileDialog.addChoosableFileFilter(CSV_FILE_FILTER); _exportFileDialog.setFileFilter(CSV_FILE_FILTER); _exportFileButton = new JButton("..."); _exportFileButton.addActionListener(this); _exportFileField = new JTextField(); _exportFileField.setEditable(false); _exportFileField.setPreferredSize(new Dimension(LINE_WIDTH - 25, LINE_HEIGHT)); _exportInstanceIdsBox = new JCheckBox("Instance IDs"); _exportFeatureNamesBox = new JCheckBox("Feature Names"); _progressBar = new JProgressBar(0, 100); ProgressBarManager.setProgressBar(_progressBar); _generateDataButton = new JButton("Generate Data"); _generateDataButton.addActionListener(this); _abortDataGenerationButton = new JButton("Abort Generation"); _abortDataGenerationButton.addActionListener(this); _abortDataGenerationButton.setEnabled(false); GenerationButtonsToggleManager.setButtons(_generateDataButton, _abortDataGenerationButton); _previewTableModel = new VariableColumnCountTableModel(8, 4); _previewTable = new JTable(_previewTableModel); _previewTable.setEnabled(false); PreviewTableManager.setPreviewTable(_previewTableModel); _logArea = new JEditorPane("text/html", null); _logArea.setPreferredSize(new Dimension(LINE_WIDTH, 70)); _logAreaScroller = new JScrollPane(_logArea); TextAreaLogManager.setLogArea(_logArea); _logArea.setBorder(new LineBorder(Color.gray, 1)); _logArea.setEditable(false); _logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); _logArea.setAutoscrolls(true); _logAreaScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); // END component definition // BEGIN main layout Container contentPane = getContentPane(); contentPane.setLayout(new SpringLayout()); JPanel topPanel = new JPanel(); topPanel.setLayout(new SpringLayout()); topPanel.setMaximumSize(new Dimension(0, 0)); // avoid resizing contentPane.add(topPanel); JPanel removeFeaturePanel = new JPanel(); removeFeaturePanel.setLayout(new SpringLayout()); topPanel.add(removeFeaturePanel); JPanel featureListPanel = new JPanel(); removeFeaturePanel.add(featureListPanel); featureListPanel.setLayout(new BorderLayout()); featureListPanel.add(_featureListScroller, BorderLayout.CENTER); featureListPanel.setPreferredSize(new Dimension(LINE_WIDTH, 5)); SpringUtilities.makeCompactGrid(removeFeaturePanel, 1, 1, 0, 0, PADDING, PADDING); JPanel generateDataPanel = new JPanel(); topPanel.add(generateDataPanel); generateDataPanel.setLayout(new SpringLayout()); generateDataPanel.add(_numberOfInstancesLabel); generateDataPanel.add(_numberOfInstancesField); generateDataPanel.add(_exportFileLabel); JPanel exportFileSubPanel = new JPanel(); generateDataPanel.add(exportFileSubPanel); exportFileSubPanel.setLayout(new SpringLayout()); exportFileSubPanel.add(_exportFileField); exportFileSubPanel.add(_exportFileButton); JPanel exportCheckBoxPanel = new JPanel(); generateDataPanel.add(new JLabel()); generateDataPanel.add(exportCheckBoxPanel); exportCheckBoxPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); exportCheckBoxPanel.add(_exportInstanceIdsBox); exportCheckBoxPanel.add(_exportFeatureNamesBox); SpringUtilities.makeCompactGrid(exportFileSubPanel, 1, 2, 0, 0, 0, 0); SpringUtilities.makeCompactGrid(generateDataPanel, 3, 2, 0, 0, PADDING, PADDING); JPanel featureButtonPanel = new JPanel(); featureButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); topPanel.add(featureButtonPanel); featureButtonPanel.add(new JLabel(" ")); featureButtonPanel.add(_removeFeatureButton, BorderLayout.EAST); featureButtonPanel.add(_addFeatureButton, BorderLayout.EAST); JPanel generateDataButtonPanel = new JPanel(); generateDataButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); topPanel.add(generateDataButtonPanel); generateDataButtonPanel.add(_generateDataButton, BorderLayout.EAST); SpringUtilities.makeCompactGrid(topPanel, 2, 2, 0, 0, 0, 0); contentPane.add(_previewTable); JPanel progressPanel = new JPanel(); contentPane.add(progressPanel); progressPanel.setLayout(new SpringLayout()); progressPanel.add(_progressBar); progressPanel.add(_abortDataGenerationButton); SpringUtilities.makeCompactGrid(progressPanel, 1, 2, 0, 0, 0, 0); contentPane.add(_logAreaScroller); SpringUtilities.makeCompactGrid(contentPane, 4, 1, 15, 15, 15, 15); // END main layout // BEGIN dialogs layout _cards = new JPanel(); _cards.setLayout(new CardLayout()); JPanel trashPanel = new JPanel(); // container for trash components JLabel trashLabel = new JLabel(""); // used as placeholder JTextField trashField = new JTextField("XXXXXXXXXXXXXXXXXXXXX"); // used as placeholder trashField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); JPanel bernoulliPanel = new JPanel(); _cards.add(bernoulliPanel, SelectableDistribution.BERNOULLI); bernoulliPanel.setLayout(new SpringLayout()); bernoulliPanel.add(_bernoulliProbabilityLabel); bernoulliPanel.add(_bernoulliProbabilityField); bernoulliPanel.add(trashLabel); bernoulliPanel.add(trashField); SpringUtilities.makeCompactGrid(bernoulliPanel, 2, 2, 0, 0, PADDING, PADDING); JPanel uniformCategorialPanel = new JPanel(); _cards.add(uniformCategorialPanel, SelectableDistribution.UNIFORM_CATEGORIAL); uniformCategorialPanel.setLayout(new SpringLayout()); uniformCategorialPanel.add(_uniformCategorialNumberOfStatesLabel); uniformCategorialPanel.add(_uniformCategorialNumberOfStatesField); JLabel filler = new JLabel(""); filler.setSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); uniformCategorialPanel.add(trashLabel); uniformCategorialPanel.add(trashField); SpringUtilities.makeCompactGrid(uniformCategorialPanel, 2, 2, 0, 0, PADDING, PADDING); JPanel gaussianPanel = new JPanel(); _cards.add(gaussianPanel, SelectableDistribution.GAUSSIAN); gaussianPanel.setLayout(new SpringLayout()); gaussianPanel.add(_gaussianMeanLabel); gaussianPanel.add(_gaussianMeanField); gaussianPanel.add(_gaussianSigmaLabel); gaussianPanel.add(_gaussianSigmaField); SpringUtilities.makeCompactGrid(gaussianPanel, 2, 2, 0, 0, PADDING, PADDING); JPanel featureDefinitionDialogPanel = new JPanel(); featureDefinitionDialogPanel.setLayout(new SpringLayout()); JPanel distributionSelectionPanel = new JPanel(); distributionSelectionPanel.setLayout(new SpringLayout()); featureDefinitionDialogPanel.add(distributionSelectionPanel); distributionSelectionPanel.add(_addFeatureDistributionLabel); distributionSelectionPanel.add(_addFeatureDistributionSelection); distributionSelectionPanel.add(_featureNameLabel); distributionSelectionPanel.add(_featureNameField); SpringUtilities.makeCompactGrid(distributionSelectionPanel, 2, 2, 0, 0, PADDING, PADDING); featureDefinitionDialogPanel.add(new JLabel(" ")); featureDefinitionDialogPanel.add(new JSeparator()); featureDefinitionDialogPanel.add(new JLabel(" ")); featureDefinitionDialogPanel.add(new JLabel("Distribution Parameters", JLabel.LEFT)); featureDefinitionDialogPanel.add(new JLabel(" ")); featureDefinitionDialogPanel.add(_cards); SpringUtilities.makeCompactGrid(featureDefinitionDialogPanel, 7, 1, 5, 0, 0, 0); trashPanel.add(trashLabel); // dispose label trashPanel.add(trashField); // dispose field _featureDefinitionPane = new JOptionPane(featureDefinitionDialogPanel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); _featureDefinitionDialog.setContentPane(_featureDefinitionPane); _featureDefinitionDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); _featureDefinitionPane.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (_featureDefinitionDialog.isVisible() && (e.getSource() == _featureDefinitionPane) && (prop.equals(JOptionPane.VALUE_PROPERTY))) { if (_featureDefinitionPane.getValue().equals(JOptionPane.OK_OPTION)) { if (verifyInputsAndAddFeatureDefinition()) { _featureDefinitionDialog.setVisible(false); _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } else { _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } } else if (_featureDefinitionPane.getValue().equals(JOptionPane.UNINITIALIZED_VALUE)) { // Do nothing as this happens when OK was clicked but inputs could not be verified } else { _featureDefinitionDialog.setVisible(false); } } } }); _featureDefinitionDialog.pack(); _featureDefinitionDialog.setResizable(false); _featureDefinitionDialog.setLocation(getCenteredLocationOf(_featureDefinitionDialog)); // END dialog layouts // BEGIN define custom focus traversal List<Component> focusOrder = Lists.newArrayList(); focusOrder.add(_featureNameField); focusOrder.add(_gaussianMeanField); focusOrder.add(_gaussianSigmaField); focusOrder.add(_addFeatureButton); focusOrder.add(_featureList); focusOrder.add(_removeFeatureButton); focusOrder.add(_numberOfInstancesField); focusOrder.add(_exportFileButton); focusOrder.add(_exportInstanceIdsBox); focusOrder.add(_exportFeatureNamesBox); focusOrder.add(_generateDataButton); focusOrder.add(_abortDataGenerationButton); setFocusTraversalPolicy(new OrderedFocusTraversalPolicy(focusOrder)); // END define custom focus traversal // BEGIN finalize pack(); setLocation(getCenteredLocationOf(this)); setMinimumSize(getSize()); setVisible(true); // END finalize }
public SwingMenu() { // BEGIN frame initialization setTitle(ApplicationMetaData.getName()); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(true); // END frame initialization // BEGIN menu bar initialization _menuBar = new JMenuBar(); setJMenuBar(_menuBar); _helpMenu = new JMenu("Help"); _helpMenu.setMnemonic(KeyEvent.VK_O); _aboutMenuItem = new JMenuItem("About"); _aboutMenuItem.addActionListener(this); _helpMenu.add(_aboutMenuItem); _menuBar.add(_helpMenu); // END menu bar initialization // BEGIN component definition _addFeatureDistributionLabel = new JLabel("Distribution", JLabel.RIGHT); _addFeatureDistributionSelection = new JComboBox(new Object[] { SelectableDistribution.BERNOULLI, SelectableDistribution.UNIFORM_CATEGORIAL, SelectableDistribution.GAUSSIAN }); _addFeatureDistributionSelection.addActionListener(this); _featureNameLabel = new JLabel("Name", JLabel.RIGHT); _featureNameField = new JTextField(); _featureNameField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _gaussianMeanLabel = new JLabel("Mean", JLabel.RIGHT); _gaussianMeanField = new JTextField(); _gaussianMeanField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _gaussianSigmaLabel = new JLabel("Sigma", JLabel.RIGHT); _gaussianSigmaField = new JTextField(); _gaussianSigmaField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _bernoulliProbabilityLabel = new JLabel("P", JLabel.RIGHT); _bernoulliProbabilityField = new JTextField(); _bernoulliProbabilityField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _uniformCategorialNumberOfStatesLabel = new JLabel("#States", JLabel.RIGHT); _uniformCategorialNumberOfStatesField = new JTextField(); _uniformCategorialNumberOfStatesField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _addFeatureButton = new JButton("Add Feature"); _addFeatureButton.addActionListener(this); _featureDefinitionDialog = new JDialog(this, "Add Feature", true); _featureListModel = new DefaultListModel(); _featureList = new JList(_featureListModel); _featureList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); _featureList.setFocusable(true); _featureListScroller = new JScrollPane(_featureList); _featureListScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); _featureListScroller.setFocusable(false); _removeFeatureButton = new JButton("Remove Feature"); _removeFeatureButton.addActionListener(this); _numberOfInstancesLabel = new JLabel("#Instances", JLabel.RIGHT); _numberOfInstancesField = new JTextField(); _numberOfInstancesField.setPreferredSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); _exportFileLabel = new JLabel("Export File", JLabel.RIGHT); _exportFileDialog = new ExportFileChooser(ALL_FILE_FILTER); _exportFileDialog.addChoosableFileFilter(CSV_FILE_FILTER); _exportFileDialog.setFileFilter(CSV_FILE_FILTER); _exportFileButton = new JButton("..."); _exportFileButton.addActionListener(this); _exportFileField = new JTextField(); _exportFileField.setEditable(false); _exportFileField.setPreferredSize(new Dimension(LINE_WIDTH - 25, LINE_HEIGHT)); _exportInstanceIdsBox = new JCheckBox("Instance IDs"); _exportFeatureNamesBox = new JCheckBox("Feature Names"); _progressBar = new JProgressBar(0, 100); ProgressBarManager.setProgressBar(_progressBar); _generateDataButton = new JButton("Generate Data"); _generateDataButton.addActionListener(this); _abortDataGenerationButton = new JButton("Abort Generation"); _abortDataGenerationButton.addActionListener(this); _abortDataGenerationButton.setEnabled(false); GenerationButtonsToggleManager.setButtons(_generateDataButton, _abortDataGenerationButton); _previewTableModel = new VariableColumnCountTableModel(8, 4); _previewTable = new JTable(_previewTableModel); _previewTable.setEnabled(false); PreviewTableManager.setPreviewTable(_previewTableModel); _logArea = new JEditorPane("text/html", null); _logArea.setPreferredSize(new Dimension(LINE_WIDTH, 70)); _logAreaScroller = new JScrollPane(_logArea); TextAreaLogManager.setLogArea(_logArea); _logArea.setBorder(new LineBorder(Color.gray, 1)); _logArea.setEditable(false); _logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); _logArea.setAutoscrolls(true); _logAreaScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); // END component definition // BEGIN main layout Container contentPane = getContentPane(); contentPane.setLayout(new SpringLayout()); JPanel topPanel = new JPanel(); topPanel.setLayout(new SpringLayout()); topPanel.setMaximumSize(new Dimension(0, 0)); // avoid resizing contentPane.add(topPanel); JPanel removeFeaturePanel = new JPanel(); removeFeaturePanel.setLayout(new SpringLayout()); topPanel.add(removeFeaturePanel); JPanel featureListPanel = new JPanel(); removeFeaturePanel.add(featureListPanel); featureListPanel.setLayout(new BorderLayout()); featureListPanel.add(_featureListScroller, BorderLayout.CENTER); featureListPanel.setPreferredSize(new Dimension(LINE_WIDTH, 5)); SpringUtilities.makeCompactGrid(removeFeaturePanel, 1, 1, 0, 0, PADDING, PADDING); JPanel generateDataPanel = new JPanel(); topPanel.add(generateDataPanel); generateDataPanel.setLayout(new SpringLayout()); generateDataPanel.add(_numberOfInstancesLabel); generateDataPanel.add(_numberOfInstancesField); generateDataPanel.add(_exportFileLabel); JPanel exportFileSubPanel = new JPanel(); generateDataPanel.add(exportFileSubPanel); exportFileSubPanel.setLayout(new SpringLayout()); exportFileSubPanel.add(_exportFileField); exportFileSubPanel.add(_exportFileButton); JPanel exportCheckBoxPanel = new JPanel(); generateDataPanel.add(new JLabel()); generateDataPanel.add(exportCheckBoxPanel); exportCheckBoxPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); exportCheckBoxPanel.add(_exportInstanceIdsBox); exportCheckBoxPanel.add(_exportFeatureNamesBox); SpringUtilities.makeCompactGrid(exportFileSubPanel, 1, 2, 0, 0, 0, 0); SpringUtilities.makeCompactGrid(generateDataPanel, 3, 2, 0, 0, PADDING, PADDING); JPanel featureButtonPanel = new JPanel(); featureButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); topPanel.add(featureButtonPanel); featureButtonPanel.add(new JLabel(" ")); featureButtonPanel.add(_removeFeatureButton, BorderLayout.EAST); featureButtonPanel.add(_addFeatureButton, BorderLayout.EAST); JPanel generateDataButtonPanel = new JPanel(); generateDataButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); topPanel.add(generateDataButtonPanel); generateDataButtonPanel.add(_generateDataButton, BorderLayout.EAST); SpringUtilities.makeCompactGrid(topPanel, 2, 2, 0, 0, 0, 0); contentPane.add(_previewTable); JPanel progressPanel = new JPanel(); contentPane.add(progressPanel); progressPanel.setLayout(new SpringLayout()); progressPanel.add(_progressBar); progressPanel.add(_abortDataGenerationButton); SpringUtilities.makeCompactGrid(progressPanel, 1, 2, 0, 0, 0, 0); contentPane.add(_logAreaScroller); SpringUtilities.makeCompactGrid(contentPane, 4, 1, 15, 15, 15, 15); // END main layout // BEGIN dialogs layout _cards = new JPanel(); _cards.setLayout(new CardLayout()); JPanel trashPanel = new JPanel(); // container for trash components JLabel trashLabel = new JLabel(""); // used as placeholder JTextField trashField = new JTextField("XXXXXXXXXXXXXXXXXXXXX"); // used as placeholder trashField.setMinimumSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); JPanel bernoulliPanel = new JPanel(); _cards.add(bernoulliPanel, SelectableDistribution.BERNOULLI); bernoulliPanel.setLayout(new SpringLayout()); bernoulliPanel.add(_bernoulliProbabilityLabel); bernoulliPanel.add(_bernoulliProbabilityField); bernoulliPanel.add(trashLabel); bernoulliPanel.add(trashField); SpringUtilities.makeCompactGrid(bernoulliPanel, 2, 2, 0, 0, PADDING, PADDING); JPanel uniformCategorialPanel = new JPanel(); _cards.add(uniformCategorialPanel, SelectableDistribution.UNIFORM_CATEGORIAL); uniformCategorialPanel.setLayout(new SpringLayout()); uniformCategorialPanel.add(_uniformCategorialNumberOfStatesLabel); uniformCategorialPanel.add(_uniformCategorialNumberOfStatesField); JLabel filler = new JLabel(""); filler.setSize(new Dimension(LINE_WIDTH, LINE_HEIGHT)); uniformCategorialPanel.add(trashLabel); uniformCategorialPanel.add(trashField); SpringUtilities.makeCompactGrid(uniformCategorialPanel, 2, 2, 0, 0, PADDING, PADDING); JPanel gaussianPanel = new JPanel(); _cards.add(gaussianPanel, SelectableDistribution.GAUSSIAN); gaussianPanel.setLayout(new SpringLayout()); gaussianPanel.add(_gaussianMeanLabel); gaussianPanel.add(_gaussianMeanField); gaussianPanel.add(_gaussianSigmaLabel); gaussianPanel.add(_gaussianSigmaField); SpringUtilities.makeCompactGrid(gaussianPanel, 2, 2, 0, 0, PADDING, PADDING); JPanel featureDefinitionDialogPanel = new JPanel(); featureDefinitionDialogPanel.setLayout(new SpringLayout()); JPanel distributionSelectionPanel = new JPanel(); distributionSelectionPanel.setLayout(new SpringLayout()); featureDefinitionDialogPanel.add(distributionSelectionPanel); distributionSelectionPanel.add(_addFeatureDistributionLabel); distributionSelectionPanel.add(_addFeatureDistributionSelection); distributionSelectionPanel.add(_featureNameLabel); distributionSelectionPanel.add(_featureNameField); SpringUtilities.makeCompactGrid(distributionSelectionPanel, 2, 2, 0, 0, PADDING, PADDING); featureDefinitionDialogPanel.add(new JLabel(" ")); featureDefinitionDialogPanel.add(new JSeparator()); featureDefinitionDialogPanel.add(new JLabel(" ")); featureDefinitionDialogPanel.add(new JLabel("Distribution Parameters", JLabel.LEFT)); featureDefinitionDialogPanel.add(new JLabel(" ")); featureDefinitionDialogPanel.add(_cards); SpringUtilities.makeCompactGrid(featureDefinitionDialogPanel, 7, 1, 5, 0, 0, 0); trashPanel.add(trashLabel); // dispose label trashPanel.add(trashField); // dispose field _featureDefinitionPane = new JOptionPane(featureDefinitionDialogPanel, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); _featureDefinitionDialog.setContentPane(_featureDefinitionPane); _featureDefinitionDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); _featureDefinitionPane.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (_featureDefinitionDialog.isVisible() && (e.getSource() == _featureDefinitionPane) && (prop.equals(JOptionPane.VALUE_PROPERTY))) { if (_featureDefinitionPane.getValue().equals(JOptionPane.OK_OPTION)) { if (verifyInputsAndAddFeatureDefinition()) { _featureDefinitionDialog.setVisible(false); _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } else { _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } } else if (_featureDefinitionPane.getValue().equals(JOptionPane.UNINITIALIZED_VALUE)) { // Do nothing as this happens when OK was clicked but inputs could not be verified } else { _featureDefinitionDialog.setVisible(false); _featureDefinitionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); } } } }); _featureDefinitionDialog.pack(); _featureDefinitionDialog.setResizable(false); _featureDefinitionDialog.setLocation(getCenteredLocationOf(_featureDefinitionDialog)); // END dialog layouts // BEGIN define custom focus traversal List<Component> focusOrder = Lists.newArrayList(); focusOrder.add(_featureNameField); focusOrder.add(_gaussianMeanField); focusOrder.add(_gaussianSigmaField); focusOrder.add(_addFeatureButton); focusOrder.add(_featureList); focusOrder.add(_removeFeatureButton); focusOrder.add(_numberOfInstancesField); focusOrder.add(_exportFileButton); focusOrder.add(_exportInstanceIdsBox); focusOrder.add(_exportFeatureNamesBox); focusOrder.add(_generateDataButton); focusOrder.add(_abortDataGenerationButton); setFocusTraversalPolicy(new OrderedFocusTraversalPolicy(focusOrder)); // END define custom focus traversal // BEGIN finalize pack(); setLocation(getCenteredLocationOf(this)); setMinimumSize(getSize()); setVisible(true); // END finalize }
diff --git a/bundles/extensions/event/src/test/java/org/apache/sling/event/it/ClassloadingTest.java b/bundles/extensions/event/src/test/java/org/apache/sling/event/it/ClassloadingTest.java index f016891d62..5bec425df8 100644 --- a/bundles/extensions/event/src/test/java/org/apache/sling/event/it/ClassloadingTest.java +++ b/bundles/extensions/event/src/test/java/org/apache/sling/event/it/ClassloadingTest.java @@ -1,195 +1,196 @@ /* * 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.sling.event.it; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.apache.sling.event.EventPropertiesMap; import org.apache.sling.event.impl.jobs.config.ConfigurationConstants; import org.apache.sling.event.jobs.Job; import org.apache.sling.event.jobs.JobManager; import org.apache.sling.event.jobs.JobUtil; import org.apache.sling.event.jobs.QueueConfiguration; import org.apache.sling.event.jobs.consumer.JobConsumer; import org.junit.Before; import org.junit.runner.RunWith; import org.ops4j.pax.exam.junit.ExamReactorStrategy; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory; import org.osgi.framework.ServiceRegistration; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; @RunWith(JUnit4TestRunner.class) @ExamReactorStrategy(AllConfinedStagedReactorFactory.class) public class ClassloadingTest extends AbstractJobHandlingTest { private static final String QUEUE_NAME = "cltest"; private static final String TOPIC = "sling/cltest"; private String queueConfPid; @Override @Before public void setup() throws IOException { super.setup(); // create ignore test queue final org.osgi.service.cm.Configuration orderedConfig = this.configAdmin.createFactoryConfiguration("org.apache.sling.event.jobs.QueueConfiguration", null); final Dictionary<String, Object> orderedProps = new Hashtable<String, Object>(); orderedProps.put(ConfigurationConstants.PROP_NAME, QUEUE_NAME); orderedProps.put(ConfigurationConstants.PROP_TYPE, QueueConfiguration.Type.UNORDERED.name()); orderedProps.put(ConfigurationConstants.PROP_TOPICS, TOPIC); orderedConfig.update(orderedProps); this.queueConfPid = orderedConfig.getPid(); this.sleep(1000L); } @org.junit.Test public void testSimpleClassloading() throws Exception { final AtomicInteger count = new AtomicInteger(0); final List<Event> finishedEvents = Collections.synchronizedList(new ArrayList<Event>()); final ServiceRegistration jcReg = this.registerJobConsumer(TOPIC, new JobConsumer() { @Override public JobResult process(Job job) { count.incrementAndGet(); return JobResult.OK; } }); final ServiceRegistration ehReg = this.registerEventHandler(JobUtil.TOPIC_JOB_FINISHED, new EventHandler() { @Override public void handleEvent(Event event) { finishedEvents.add(event); } }); try { final JobManager jobManager = this.getJobManager(); final List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); final EventPropertiesMap map = new EventPropertiesMap(); map.put("a", "a1"); map.put("b", "b2"); // we start a single job final Map<String, Object> props = new HashMap<String, Object>(); props.put("string", "Hello"); props.put("int", new Integer(5)); props.put("long", new Long(7)); props.put("list", list); props.put("map", map); jobManager.addJob(TOPIC, null, props); while ( finishedEvents.size() < 1 ) { // we wait a little bit Thread.sleep(100); } + Thread.sleep(100); // no jobs queued, none processed and no available assertEquals(0, jobManager.getStatistics().getNumberOfQueuedJobs()); assertEquals(1, count.get()); assertEquals(0, jobManager.findJobs(JobManager.QueryType.ALL, TOPIC, -1).size()); final String jobTopic = (String)finishedEvents.get(0).getProperty(JobUtil.NOTIFICATION_PROPERTY_JOB_TOPIC); assertNotNull(jobTopic); assertEquals("Hello", finishedEvents.get(0).getProperty("string")); assertEquals(new Integer(5), Integer.valueOf(finishedEvents.get(0).getProperty("int").toString())); assertEquals(new Long(7), Long.valueOf(finishedEvents.get(0).getProperty("long").toString())); assertEquals(list, finishedEvents.get(0).getProperty("list")); assertEquals(map, finishedEvents.get(0).getProperty("map")); } finally { jcReg.unregister(); ehReg.unregister(); } } @org.junit.Test public void testFailedClassloading() throws Exception { final AtomicInteger count = new AtomicInteger(0); final List<Event> finishedEvents = Collections.synchronizedList(new ArrayList<Event>()); final ServiceRegistration jcReg = this.registerJobConsumer(TOPIC + "/failed", new JobConsumer() { @Override public JobResult process(Job job) { count.incrementAndGet(); return JobResult.OK; } }); final ServiceRegistration ehReg = this.registerEventHandler(JobUtil.TOPIC_JOB_FINISHED, new EventHandler() { @Override public void handleEvent(Event event) { finishedEvents.add(event); } }); try { final JobManager jobManager = this.getJobManager(); // dao is an invisible class for the dynamic class loader as it is not public // therefore scheduling this job should fail! final DataObject dao = new DataObject(); dao.message = "Hello World"; // we start a single job final Map<String, Object> props = new HashMap<String, Object>(); props.put("dao", dao); jobManager.addJob(TOPIC + "/failed", null, props); // we simply wait a little bit sleep(2000); assertEquals(0, count.get()); assertEquals(0, finishedEvents.size()); assertEquals(1, jobManager.findJobs(JobManager.QueryType.ALL, TOPIC + "/failed", -1).size()); assertEquals(0, jobManager.getStatistics().getNumberOfQueuedJobs()); assertEquals(0, jobManager.getStatistics().getNumberOfActiveJobs()); } finally { jcReg.unregister(); ehReg.unregister(); } } private static final class DataObject implements Serializable { public String message; } }
true
true
@org.junit.Test public void testSimpleClassloading() throws Exception { final AtomicInteger count = new AtomicInteger(0); final List<Event> finishedEvents = Collections.synchronizedList(new ArrayList<Event>()); final ServiceRegistration jcReg = this.registerJobConsumer(TOPIC, new JobConsumer() { @Override public JobResult process(Job job) { count.incrementAndGet(); return JobResult.OK; } }); final ServiceRegistration ehReg = this.registerEventHandler(JobUtil.TOPIC_JOB_FINISHED, new EventHandler() { @Override public void handleEvent(Event event) { finishedEvents.add(event); } }); try { final JobManager jobManager = this.getJobManager(); final List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); final EventPropertiesMap map = new EventPropertiesMap(); map.put("a", "a1"); map.put("b", "b2"); // we start a single job final Map<String, Object> props = new HashMap<String, Object>(); props.put("string", "Hello"); props.put("int", new Integer(5)); props.put("long", new Long(7)); props.put("list", list); props.put("map", map); jobManager.addJob(TOPIC, null, props); while ( finishedEvents.size() < 1 ) { // we wait a little bit Thread.sleep(100); } // no jobs queued, none processed and no available assertEquals(0, jobManager.getStatistics().getNumberOfQueuedJobs()); assertEquals(1, count.get()); assertEquals(0, jobManager.findJobs(JobManager.QueryType.ALL, TOPIC, -1).size()); final String jobTopic = (String)finishedEvents.get(0).getProperty(JobUtil.NOTIFICATION_PROPERTY_JOB_TOPIC); assertNotNull(jobTopic); assertEquals("Hello", finishedEvents.get(0).getProperty("string")); assertEquals(new Integer(5), Integer.valueOf(finishedEvents.get(0).getProperty("int").toString())); assertEquals(new Long(7), Long.valueOf(finishedEvents.get(0).getProperty("long").toString())); assertEquals(list, finishedEvents.get(0).getProperty("list")); assertEquals(map, finishedEvents.get(0).getProperty("map")); } finally { jcReg.unregister(); ehReg.unregister(); } }
@org.junit.Test public void testSimpleClassloading() throws Exception { final AtomicInteger count = new AtomicInteger(0); final List<Event> finishedEvents = Collections.synchronizedList(new ArrayList<Event>()); final ServiceRegistration jcReg = this.registerJobConsumer(TOPIC, new JobConsumer() { @Override public JobResult process(Job job) { count.incrementAndGet(); return JobResult.OK; } }); final ServiceRegistration ehReg = this.registerEventHandler(JobUtil.TOPIC_JOB_FINISHED, new EventHandler() { @Override public void handleEvent(Event event) { finishedEvents.add(event); } }); try { final JobManager jobManager = this.getJobManager(); final List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); final EventPropertiesMap map = new EventPropertiesMap(); map.put("a", "a1"); map.put("b", "b2"); // we start a single job final Map<String, Object> props = new HashMap<String, Object>(); props.put("string", "Hello"); props.put("int", new Integer(5)); props.put("long", new Long(7)); props.put("list", list); props.put("map", map); jobManager.addJob(TOPIC, null, props); while ( finishedEvents.size() < 1 ) { // we wait a little bit Thread.sleep(100); } Thread.sleep(100); // no jobs queued, none processed and no available assertEquals(0, jobManager.getStatistics().getNumberOfQueuedJobs()); assertEquals(1, count.get()); assertEquals(0, jobManager.findJobs(JobManager.QueryType.ALL, TOPIC, -1).size()); final String jobTopic = (String)finishedEvents.get(0).getProperty(JobUtil.NOTIFICATION_PROPERTY_JOB_TOPIC); assertNotNull(jobTopic); assertEquals("Hello", finishedEvents.get(0).getProperty("string")); assertEquals(new Integer(5), Integer.valueOf(finishedEvents.get(0).getProperty("int").toString())); assertEquals(new Long(7), Long.valueOf(finishedEvents.get(0).getProperty("long").toString())); assertEquals(list, finishedEvents.get(0).getProperty("list")); assertEquals(map, finishedEvents.get(0).getProperty("map")); } finally { jcReg.unregister(); ehReg.unregister(); } }
diff --git a/jersey-server/src/main/java/com/sun/jersey/server/wadl/WadlGeneratorImpl.java b/jersey-server/src/main/java/com/sun/jersey/server/wadl/WadlGeneratorImpl.java index 452c1876..9c2ad540 100644 --- a/jersey-server/src/main/java/com/sun/jersey/server/wadl/WadlGeneratorImpl.java +++ b/jersey-server/src/main/java/com/sun/jersey/server/wadl/WadlGeneratorImpl.java @@ -1,192 +1,194 @@ /* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://jersey.dev.java.net/CDDL+GPL.html * or jersey/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at jersey/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.sun.jersey.server.wadl; import com.sun.jersey.api.model.AbstractMethod; import javax.ws.rs.FormParam; import javax.ws.rs.core.MediaType; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import com.sun.jersey.api.model.AbstractResource; import com.sun.jersey.api.model.AbstractResourceMethod; import com.sun.jersey.api.model.Parameter; import com.sun.research.ws.wadl.Application; import com.sun.research.ws.wadl.Param; import com.sun.research.ws.wadl.ParamStyle; import com.sun.research.ws.wadl.RepresentationType; import com.sun.research.ws.wadl.Request; import com.sun.research.ws.wadl.Resource; import com.sun.research.ws.wadl.Resources; import com.sun.research.ws.wadl.Response; /** * This WadlGenerator creates the basic wadl artifacts.<br> * Created on: Jun 16, 2008<br> * * @author <a href="mailto:[email protected]">Martin Grotzke</a> * @version $Id$ */ public class WadlGeneratorImpl implements WadlGenerator { public String getRequiredJaxbContextPath() { final String name = Application.class.getName(); return name.substring(0, name.lastIndexOf('.')); } public void init() throws Exception { } public void setWadlGeneratorDelegate( WadlGenerator delegate ) { throw new UnsupportedOperationException( "No delegate supported." ); } public Resources createResources() { return new Resources(); } public Application createApplication() { return new Application(); } public com.sun.research.ws.wadl.Method createMethod( AbstractResource r, final AbstractResourceMethod m ) { com.sun.research.ws.wadl.Method wadlMethod = new com.sun.research.ws.wadl.Method(); wadlMethod.setName(m.getHttpMethod()); wadlMethod.setId( m.getMethod().getName() ); return wadlMethod; } public RepresentationType createRequestRepresentation( AbstractResource r, AbstractResourceMethod m, MediaType mediaType ) { RepresentationType wadlRepresentation = new RepresentationType(); wadlRepresentation.setMediaType(mediaType.toString()); return wadlRepresentation; } public Request createRequest(AbstractResource r, AbstractResourceMethod m) { return new Request(); } public Param createParam( AbstractResource r, AbstractMethod m, final Parameter p ) { + if (p.getSource() == Parameter.Source.UNKNOWN) + return null; Param wadlParam = new Param(); wadlParam.setName(p.getSourceName()); /* the form param right now has no Parameter.Source representation * and requires some special handling */ if ( p.getAnnotation().annotationType() == FormParam.class ) { wadlParam.setStyle( ParamStyle.QUERY ); } else { switch (p.getSource()) { case QUERY: wadlParam.setStyle(ParamStyle.QUERY); break; case MATRIX: wadlParam.setStyle(ParamStyle.MATRIX); break; case PATH: wadlParam.setStyle(ParamStyle.TEMPLATE); break; case HEADER: wadlParam.setStyle(ParamStyle.HEADER); break; default: break; } } if (p.hasDefaultValue()) wadlParam.setDefault(p.getDefaultValue()); Class<?> pClass = p.getParameterClass(); if (pClass.isArray()) { wadlParam.setRepeating(true); pClass = pClass.getComponentType(); } if (pClass.equals(int.class) || pClass.equals(Integer.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "int", "xs")); else if (pClass.equals(boolean.class) || pClass.equals(Boolean.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "boolean", "xs")); else if (pClass.equals(long.class) || pClass.equals(Long.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "long", "xs")); else if (pClass.equals(short.class) || pClass.equals(Short.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "short", "xs")); else if (pClass.equals(byte.class) || pClass.equals(Byte.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "byte", "xs")); else if (pClass.equals(float.class) || pClass.equals(Float.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "float", "xs")); else if (pClass.equals(double.class) || pClass.equals(Double.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "double", "xs")); else wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "string", "xs")); return wadlParam; } public Resource createResource( AbstractResource r, String path ) { Resource wadlResource = new Resource(); if (path != null) wadlResource.setPath(path); else if (r.isRootResource()) wadlResource.setPath(r.getPath().getValue()); return wadlResource; } public Response createResponse( AbstractResource r, AbstractResourceMethod m ) { final Response response = new Response(); for (MediaType mediaType: m.getSupportedOutputTypes()) { RepresentationType wadlRepresentation = createResponseRepresentation( r, m, mediaType ); JAXBElement<RepresentationType> element = new JAXBElement<RepresentationType>( new QName("http://research.sun.com/wadl/2006/10","representation"), RepresentationType.class, wadlRepresentation); response.getRepresentationOrFault().add(element); } return response; } public RepresentationType createResponseRepresentation( AbstractResource r, AbstractResourceMethod m, MediaType mediaType ) { RepresentationType wadlRepresentation = new RepresentationType(); wadlRepresentation.setMediaType(mediaType.toString()); return wadlRepresentation; } }
true
true
public Param createParam( AbstractResource r, AbstractMethod m, final Parameter p ) { Param wadlParam = new Param(); wadlParam.setName(p.getSourceName()); /* the form param right now has no Parameter.Source representation * and requires some special handling */ if ( p.getAnnotation().annotationType() == FormParam.class ) { wadlParam.setStyle( ParamStyle.QUERY ); } else { switch (p.getSource()) { case QUERY: wadlParam.setStyle(ParamStyle.QUERY); break; case MATRIX: wadlParam.setStyle(ParamStyle.MATRIX); break; case PATH: wadlParam.setStyle(ParamStyle.TEMPLATE); break; case HEADER: wadlParam.setStyle(ParamStyle.HEADER); break; default: break; } } if (p.hasDefaultValue()) wadlParam.setDefault(p.getDefaultValue()); Class<?> pClass = p.getParameterClass(); if (pClass.isArray()) { wadlParam.setRepeating(true); pClass = pClass.getComponentType(); } if (pClass.equals(int.class) || pClass.equals(Integer.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "int", "xs")); else if (pClass.equals(boolean.class) || pClass.equals(Boolean.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "boolean", "xs")); else if (pClass.equals(long.class) || pClass.equals(Long.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "long", "xs")); else if (pClass.equals(short.class) || pClass.equals(Short.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "short", "xs")); else if (pClass.equals(byte.class) || pClass.equals(Byte.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "byte", "xs")); else if (pClass.equals(float.class) || pClass.equals(Float.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "float", "xs")); else if (pClass.equals(double.class) || pClass.equals(Double.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "double", "xs")); else wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "string", "xs")); return wadlParam; }
public Param createParam( AbstractResource r, AbstractMethod m, final Parameter p ) { if (p.getSource() == Parameter.Source.UNKNOWN) return null; Param wadlParam = new Param(); wadlParam.setName(p.getSourceName()); /* the form param right now has no Parameter.Source representation * and requires some special handling */ if ( p.getAnnotation().annotationType() == FormParam.class ) { wadlParam.setStyle( ParamStyle.QUERY ); } else { switch (p.getSource()) { case QUERY: wadlParam.setStyle(ParamStyle.QUERY); break; case MATRIX: wadlParam.setStyle(ParamStyle.MATRIX); break; case PATH: wadlParam.setStyle(ParamStyle.TEMPLATE); break; case HEADER: wadlParam.setStyle(ParamStyle.HEADER); break; default: break; } } if (p.hasDefaultValue()) wadlParam.setDefault(p.getDefaultValue()); Class<?> pClass = p.getParameterClass(); if (pClass.isArray()) { wadlParam.setRepeating(true); pClass = pClass.getComponentType(); } if (pClass.equals(int.class) || pClass.equals(Integer.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "int", "xs")); else if (pClass.equals(boolean.class) || pClass.equals(Boolean.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "boolean", "xs")); else if (pClass.equals(long.class) || pClass.equals(Long.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "long", "xs")); else if (pClass.equals(short.class) || pClass.equals(Short.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "short", "xs")); else if (pClass.equals(byte.class) || pClass.equals(Byte.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "byte", "xs")); else if (pClass.equals(float.class) || pClass.equals(Float.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "float", "xs")); else if (pClass.equals(double.class) || pClass.equals(Double.class)) wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "double", "xs")); else wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "string", "xs")); return wadlParam; }
diff --git a/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java b/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java index da3be0d65..899515e75 100644 --- a/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java +++ b/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java @@ -1,72 +1,72 @@ /* Copyright 2009 Meta Broadcast Ltd 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.atlasapi.remotesite.channel4; import org.atlasapi.media.entity.Brand; import org.atlasapi.media.entity.Publisher; import org.atlasapi.persistence.content.ContentWriter; import org.atlasapi.persistence.logging.NullAdapterLog; import org.atlasapi.persistence.system.RemoteSiteClient; import org.jmock.Expectations; import org.jmock.integration.junit3.MockObjectTestCase; import com.google.common.io.Resources; import com.sun.syndication.feed.atom.Feed; /** * Unit test for {@link C4AtoZAtomContentLoader}. * * @author Robert Chatley ([email protected]) */ public class C4AtoZAtomAdapterTest extends MockObjectTestCase { String uri = "http://www.channel4.com/programmes/atoz/a"; private C4BrandUpdater brandAdapter; private RemoteSiteClient<Feed> itemClient; private C4AtoZAtomContentLoader adapter; private ContentWriter writer; Brand brand101 = new Brand("http://www.channel4.com/programmes/a-bipolar-expedition", "curie:101", Publisher.C4); Brand brand202 = new Brand("http://www.channel4.com/programmes/a-bipolar-expedition-part-2", "curie:202", Publisher.C4); private final AtomFeedBuilder atoza = new AtomFeedBuilder(Resources.getResource(getClass(), "a.atom")); private final AtomFeedBuilder atoza2 = new AtomFeedBuilder(Resources.getResource(getClass(), "a2.atom")); @SuppressWarnings("unchecked") @Override protected void setUp() throws Exception { super.setUp(); brandAdapter = mock(C4BrandUpdater.class); itemClient = mock(RemoteSiteClient.class); writer = mock(ContentWriter.class); adapter = new C4AtoZAtomContentLoader(itemClient, brandAdapter, new NullAdapterLog()); } public void testPerformsGetCorrespondingGivenUriAndPassesResultToExtractor() throws Exception { checking(new Expectations() {{ - one(itemClient).get("http://api.channel4.com/programmes/atoz/a.atom"); will(returnValue(atoza.build())); + one(itemClient).get("http://api.channel4.com/pmlsd/atoz/a.atom"); will(returnValue(atoza.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition"); //will(returnValue(brand101)); - one(itemClient).get("http://api.channel4.com/programmes/atoz/a/page-2.atom"); will(returnValue(atoza2.build())); + one(itemClient).get("http://api.channel4.com/pmlsd/atoz/a/page-2.atom"); will(returnValue(atoza2.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); //will(returnValue(brand202)); }}); adapter.loadAndSaveByLetter("a"); } }
false
true
public void testPerformsGetCorrespondingGivenUriAndPassesResultToExtractor() throws Exception { checking(new Expectations() {{ one(itemClient).get("http://api.channel4.com/programmes/atoz/a.atom"); will(returnValue(atoza.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition"); //will(returnValue(brand101)); one(itemClient).get("http://api.channel4.com/programmes/atoz/a/page-2.atom"); will(returnValue(atoza2.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); //will(returnValue(brand202)); }}); adapter.loadAndSaveByLetter("a"); }
public void testPerformsGetCorrespondingGivenUriAndPassesResultToExtractor() throws Exception { checking(new Expectations() {{ one(itemClient).get("http://api.channel4.com/pmlsd/atoz/a.atom"); will(returnValue(atoza.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition"); //will(returnValue(brand101)); one(itemClient).get("http://api.channel4.com/pmlsd/atoz/a/page-2.atom"); will(returnValue(atoza2.build())); allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(true)); allowing(brandAdapter).createOrUpdateBrand("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); //will(returnValue(brand202)); }}); adapter.loadAndSaveByLetter("a"); }
diff --git a/src/net/sf/freecol/server/control/InGameController.java b/src/net/sf/freecol/server/control/InGameController.java index 50ee5b135..9a0599e1e 100644 --- a/src/net/sf/freecol/server/control/InGameController.java +++ b/src/net/sf/freecol/server/control/InGameController.java @@ -1,3898 +1,3897 @@ /** * Copyright (C) 2002-2012 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.server.control; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.freecol.FreeCol; import net.sf.freecol.client.gui.i18n.Messages; import net.sf.freecol.common.model.Ability; import net.sf.freecol.common.model.AbstractGoods; import net.sf.freecol.common.model.AbstractUnit; import net.sf.freecol.common.model.BuildableType; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.ColonyTile; import net.sf.freecol.common.model.CombatModel.CombatResult; import net.sf.freecol.common.model.DiplomaticTrade; import net.sf.freecol.common.model.DiplomaticTrade.TradeStatus; import net.sf.freecol.common.model.EquipmentType; import net.sf.freecol.common.model.Europe; import net.sf.freecol.common.model.Europe.MigrationType; import net.sf.freecol.common.model.ExportData; import net.sf.freecol.common.model.FoundingFather; import net.sf.freecol.common.model.FreeColGameObject; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.GameOptions; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.GoodsContainer; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.HighScore; import net.sf.freecol.common.model.HighSeas; import net.sf.freecol.common.model.HistoryEvent; import net.sf.freecol.common.model.IndianNationType; import net.sf.freecol.common.model.IndianSettlement; import net.sf.freecol.common.model.Location; import net.sf.freecol.common.model.Map; import net.sf.freecol.common.model.Market; import net.sf.freecol.common.model.Market.Access; import net.sf.freecol.common.model.ModelMessage; import net.sf.freecol.common.model.Monarch; import net.sf.freecol.common.model.Monarch.MonarchAction; import net.sf.freecol.common.model.Nameable; import net.sf.freecol.common.model.Nation; import net.sf.freecol.common.model.NationSummary; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Player.PlayerType; import net.sf.freecol.common.model.Player.Stance; import net.sf.freecol.common.model.RandomRange; import net.sf.freecol.common.model.Region; import net.sf.freecol.common.model.Settlement; import net.sf.freecol.common.model.Specification; import net.sf.freecol.common.model.StringTemplate; import net.sf.freecol.common.model.Tension; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.TileImprovement; import net.sf.freecol.common.model.TileImprovementType; import net.sf.freecol.common.model.TradeItem; import net.sf.freecol.common.model.TradeRoute; import net.sf.freecol.common.model.TradeRoute.Stop; import net.sf.freecol.common.model.Turn; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.Unit.Role; import net.sf.freecol.common.model.Unit.UnitState; import net.sf.freecol.common.model.UnitType; import net.sf.freecol.common.model.UnitTypeChange; import net.sf.freecol.common.model.UnitTypeChange.ChangeType; import net.sf.freecol.common.model.WorkLocation; import net.sf.freecol.common.networking.ChatMessage; import net.sf.freecol.common.networking.ChooseFoundingFatherMessage; import net.sf.freecol.common.networking.Connection; import net.sf.freecol.common.networking.DOMMessage; import net.sf.freecol.common.networking.DiplomacyMessage; import net.sf.freecol.common.networking.GoodsForSaleMessage; import net.sf.freecol.common.networking.IndianDemandMessage; import net.sf.freecol.common.networking.LootCargoMessage; import net.sf.freecol.common.networking.MonarchActionMessage; import net.sf.freecol.common.util.Introspector; import net.sf.freecol.common.util.RandomChoice; import net.sf.freecol.common.util.Utils; import net.sf.freecol.server.FreeColServer; import net.sf.freecol.server.ai.AIPlayer; import net.sf.freecol.server.ai.REFAIPlayer; import net.sf.freecol.server.control.ChangeSet.ChangePriority; import net.sf.freecol.server.control.ChangeSet.See; import net.sf.freecol.server.model.DiplomacySession; import net.sf.freecol.server.model.LootSession; import net.sf.freecol.server.model.ServerColony; import net.sf.freecol.server.model.ServerEurope; import net.sf.freecol.server.model.ServerGame; import net.sf.freecol.server.model.ServerIndianSettlement; import net.sf.freecol.server.model.ServerPlayer; import net.sf.freecol.server.model.ServerUnit; import net.sf.freecol.server.model.TradeSession; import net.sf.freecol.server.model.TransactionSession; import org.w3c.dom.Element; /** * The main server controller. */ public final class InGameController extends Controller { private static Logger logger = Logger.getLogger(InGameController.class.getName()); // TODO: options, spec? // Alarm adjustments. public static final int ALARM_NEW_MISSIONARY = -100; // Score bonus on declaration of independence. public static final int SCORE_INDEPENDENCE_DECLARED = 100; // Score bonus on achieving independence. public static final int SCORE_INDEPENDENCE_GRANTED = 1000; // The server random number source. private final Random random; // Debug helpers private int debugOnlyAITurns = 0; private MonarchAction debugMonarchAction = null; private ServerPlayer debugMonarchPlayer = null; /** * The constructor to use. * * @param freeColServer The main server object. * @param random The pseudo-random number source to use. */ public InGameController(FreeColServer freeColServer, Random random) { super(freeColServer); this.random = random; } /** * Gets the number of AI turns to skip through. * * @return The number of terms to skip. */ public int getSkippedTurns() { return (FreeCol.isInDebugMode()) ? debugOnlyAITurns : -1; } /** * Sets the number of AI turns to skip through as a debug helper. * * @param turns The number of turns to skip through. */ public void setSkippedTurns(int turns) { if (FreeCol.isInDebugMode()) { debugOnlyAITurns = turns; } } /** * Sets a monarch action to debug/test. * * @param player The <code>Player</code> whose monarch should act. * @param action The <code>MonarchAction</code> to be taken. */ public void setMonarchAction(Player player, MonarchAction action) { if (FreeCol.isInDebugMode()) { debugMonarchPlayer = (ServerPlayer) player; debugMonarchAction = action; } } /** * Debug convenience to step the random number generator. * * @return The next random number in series, in the range 0-99. */ public int stepRandom() { return Utils.randomInt(logger, "step random", random, 100); } /** * Public version of the yearly goods adjust (public so it can be * use in the Market test code). Sends the market and change * messages to the player. * * @param serverPlayer The <code>ServerPlayer</code> whose market * is to be updated. */ public void yearlyGoodsAdjust(ServerPlayer serverPlayer) { ChangeSet cs = new ChangeSet(); serverPlayer.csYearlyGoodsAdjust(random, cs); sendElement(serverPlayer, cs); } /** * Public version of csAddFoundingFather so it can be used in the * test code and DebugMenu. * * @param serverPlayer The <code>ServerPlayer</code> who gains a father. * @param father The <code>FoundingFather</code> to add. */ public void addFoundingFather(ServerPlayer serverPlayer, FoundingFather father) { ChangeSet cs = new ChangeSet(); serverPlayer.csAddFoundingFather(father, random, cs); sendElement(serverPlayer, cs); } /** * Public change stance and inform all routine. Mostly used in the * test suite, but the AIs also call it. * * @param player The originating <code>Player</code>. * @param stance The new <code>Stance</code>. * @param otherPlayer The <code>Player</code> wrt which the stance changes. * @param symmetric If true, change the otherPlayer stance as well. */ public void changeStance(Player player, Stance stance, Player otherPlayer, boolean symmetric) { ChangeSet cs = new ChangeSet(); ServerPlayer serverPlayer = (ServerPlayer) player; if (serverPlayer.csChangeStance(stance, otherPlayer, symmetric, cs)) { sendToAll(cs); } } /** * Gets a nation summary. * * @param serverPlayer The <code>ServerPlayer</code> that is querying. * @param player The <code>Player</code> to summarize. * @return An <code>Element</code> encapsulating this action. */ public NationSummary getNationSummary(ServerPlayer serverPlayer, Player player) { return new NationSummary(player, serverPlayer); } /** * Move goods from current location to another. * * @param goods The <code>Goods</code> to move. * @param loc The new <code>Location</code>. */ public void moveGoods(Goods goods, Location loc) throws IllegalStateException { Location oldLoc = goods.getLocation(); if (oldLoc == null) { throw new IllegalStateException("Goods in null location."); } else if (loc == null) { ; // Dumping is allowed } else if (loc instanceof Unit) { if (((Unit) loc).isInEurope()) { if (!(oldLoc instanceof Unit && ((Unit) oldLoc).isInEurope())) { throw new IllegalStateException("Goods and carrier not both in Europe."); } } else if (loc.getTile() == null) { throw new IllegalStateException("Carrier not on the map."); } else if (oldLoc instanceof Settlement) { // Can not be co-located when buying from natives, or // when natives are demanding goods from a colony. } else if (loc.getTile() != oldLoc.getTile()) { throw new IllegalStateException("Goods and carrier not co-located."); } } else if (loc instanceof IndianSettlement) { // Can not be co-located when selling to natives. } else if (loc instanceof Colony) { if (oldLoc instanceof Unit && ((Unit) oldLoc).getOwner() != ((Colony) loc).getOwner()) { // Gift delivery } else if (loc.getTile() != oldLoc.getTile()) { throw new IllegalStateException("Goods and carrier not both in Colony."); } } else if (loc.getGoodsContainer() == null) { throw new IllegalStateException("New location with null GoodsContainer."); } // Save state of the goods container/s, allowing simpler updates. oldLoc.getGoodsContainer().saveState(); if (loc != null) loc.getGoodsContainer().saveState(); oldLoc.remove(goods); goods.setLocation(null); if (loc != null) { loc.add(goods); goods.setLocation(loc); } } /** * Create the Royal Expeditionary Force player corresponding to * a given player that is about to rebel. * Public for the test suite. * * @param serverPlayer The <code>ServerPlayer</code> about to rebel. * @return The REF player. */ public ServerPlayer createREFPlayer(ServerPlayer serverPlayer) { Nation refNation = serverPlayer.getNation().getRefNation(); Monarch monarch = serverPlayer.getMonarch(); ServerPlayer refPlayer = getFreeColServer().addAIPlayer(refNation); refPlayer.setEntryLocation(null); // Trigger initial placement routine Player.makeContact(serverPlayer, refPlayer); // Will change, setup only // Instantiate the REF in Europe List<Unit> landUnits = refPlayer.createUnits(monarch.getExpeditionaryForce().getLandUnits(), serverPlayer.getEurope()); List<Unit> navalUnits = refPlayer.createUnits(monarch.getExpeditionaryForce().getNavalUnits(), serverPlayer.getEurope()); refPlayer.loadShips(landUnits, navalUnits, random); // Send the navy on its way for (Unit u : navalUnits) { u.setWorkLeft(1); u.setDestination(getGame().getMap()); u.setLocation(u.getOwner().getHighSeas()); } return refPlayer; } // Client-server communication utilities // A handler interface to pass to askFuture(). // This will change from DOMMessage to Message when DOM goes away. private interface DOMMessageHandler { public DOMMessage handle(DOMMessage message); }; private class DOMMessageCallable implements Callable<DOMMessage> { private Connection connection; private Game game; private DOMMessage message; private DOMMessageHandler handler; public DOMMessageCallable(Connection connection, Game game, DOMMessage message, DOMMessageHandler handler) { this.connection = connection; this.game = game; this.message = message; this.handler = handler; } public DOMMessage call() { Element reply; try { reply = connection.askDumping(message.toXMLElement()); } catch (IOException e) { return null; } if (reply == null) return null; String tag = reply.getTagName(); tag = "net.sf.freecol.common.networking." + tag.substring(0, 1).toUpperCase() + tag.substring(1) + "Message"; Class[] types = new Class[] { Game.class, Element.class }; Object[] params = new Object[] { game, reply }; DOMMessage message; try { message = (DOMMessage)Introspector.instantiate(tag, types, params); } catch (IllegalArgumentException e) { logger.log(Level.WARNING, "Instantiation fail", e); message = null; } return (message == null) ? null : handler.handle(message); } }; // A service to run the futures. private final ExecutorService executor = Executors.newCachedThreadPool(); /** * Asks a question of a player in a Future. * * @param serverPlayer The <code>ServerPlayer</code> to ask. * @param question The <code>DOMMessage</code> question. * @param handler The <code>DOMMessageHandler</code> handler to process * the reply with. * @return A future encapsulating the result. */ private Future<DOMMessage> askFuture(ServerPlayer serverPlayer, DOMMessage question, DOMMessageHandler handler) { Callable<DOMMessage> callable = new DOMMessageCallable(serverPlayer.getConnection(), getGame(), question, handler); return executor.submit(callable); } // A place to stash queries that need to be resolved at some point. private static final List<FutureQuery> outstandingQueries = new ArrayList<FutureQuery>(); // Trivial way to associate a future with a runnable to resolve it. private class FutureQuery { public Future<DOMMessage> future; public Runnable runnable; public FutureQuery(Future<DOMMessage> future, Runnable runnable) { this.future = future; this.runnable = runnable; outstandingQueries.add(this); } }; /** * Resolves and clears any outstanding queries. */ public void resolveOutstandingQueries() { FutureQuery fq; while (!outstandingQueries.isEmpty()) { fq = outstandingQueries.remove(0); if (!fq.future.isDone()) { if (fq.runnable != null) fq.runnable.run(); fq.future.cancel(true); } } } /** * Asks a question that must be answered this turn. * * @param serverPlayer The <code>ServerPlayer</code> to ask. * @param message The <code>DOMMessage</code> question. * @param handler The <code>DOMMessageHandler</code> handler to process * the reply with. * @param runnable An optional <code>Runnable</code> to run if the * question was not answered. */ private void askThisTurn(ServerPlayer serverPlayer, DOMMessage message, DOMMessageHandler handler, Runnable runnable) { new FutureQuery(askFuture(serverPlayer, message, handler), runnable); } /** * Asks a question of a player with a timeout. * * @param serverPlayer The <code>ServerPlayer</code> to ask. * @param request The <code>DOMMessage</code> question. * @return The response to the question, or null if none. */ private DOMMessage askTimeout(ServerPlayer serverPlayer, DOMMessage request) { Future<DOMMessage> future = askFuture(serverPlayer, request, new DOMMessageHandler() { public DOMMessage handle(DOMMessage message) { return message; } }); DOMMessage reply; try { boolean single = getFreeColServer().isSingleplayer(); reply = future.get(FreeCol.getFreeColTimeout(single), TimeUnit.SECONDS); } catch (TimeoutException te) { sendElement(serverPlayer, new ChangeSet().addTrivial(See.only(serverPlayer), "closeMenus", ChangePriority.CHANGE_NORMAL)); reply = null; } catch (Exception e) { reply = null; logger.log(Level.WARNING, "Exception completing future", e); } return reply; } /** * Get a list of all server players, optionally excluding supplied ones. * * @param serverPlayers The <code>ServerPlayer</code>s to exclude. * @return A list of all connected server players, with exclusions. */ private List<ServerPlayer> getOtherPlayers(ServerPlayer... serverPlayers) { List<ServerPlayer> result = new ArrayList<ServerPlayer>(); outer: for (Player otherPlayer : getGame().getPlayers()) { ServerPlayer enemyPlayer = (ServerPlayer) otherPlayer; if (!enemyPlayer.isConnected()) continue; for (ServerPlayer exclude : serverPlayers) { if (enemyPlayer == exclude) continue outer; } result.add(enemyPlayer); } return result; } /** * Send a set of changes to all players. * * @param cs The <code>ChangeSet</code> to send. */ private void sendToAll(ChangeSet cs) { sendToList(getOtherPlayers(), cs); } /** * Send an update to all players except one. * * @param serverPlayer A <code>ServerPlayer</code> to exclude. * @param cs The <code>ChangeSet</code> encapsulating the update. */ private void sendToOthers(ServerPlayer serverPlayer, ChangeSet cs) { sendToList(getOtherPlayers(serverPlayer), cs); } /** * Send an element to all players except one. * Deprecated, please avoid if possible. * * @param serverPlayer A <code>ServerPlayer</code> to exclude. * @param element An <code>Element</code> to send. */ private void sendToOthers(ServerPlayer serverPlayer, Element element) { sendToList(getOtherPlayers(serverPlayer), element); } /** * Send an update to a list of players. * * @param serverPlayers The <code>ServerPlayer</code>s to send to. * @param cs The <code>ChangeSet</code> encapsulating the update. */ private void sendToList(List<ServerPlayer> serverPlayers, ChangeSet cs) { for (ServerPlayer s : serverPlayers) sendElement(s, cs); } /** * Send an element to a list of players. * Deprecated, please avoid if possible. * * @param serverPlayers The <code>ServerPlayer</code>s to send to. * @param element An <code>Element</code> to send. */ private void sendToList(List<ServerPlayer> serverPlayers, Element element) { if (element != null) { for (ServerPlayer s : serverPlayers) { askElement(s, element); } } } /** * Send an element to a specific player. * * @param serverPlayer The <code>ServerPlayer</code> to update. * @param cs A <code>ChangeSet</code> to build an <code>Element</code> with. */ private void sendElement(ServerPlayer serverPlayer, ChangeSet cs) { askElement(serverPlayer, cs.build(serverPlayer)); } /** * Send an element to a specific player. * Deprecated, please avoid if possible. * * @param serverPlayer The <code>ServerPlayer</code> to update. * @param request An <code>Element</code> containing the update. */ private Element askElement(ServerPlayer serverPlayer, Element request) { Connection connection = serverPlayer.getConnection(); if (request == null || connection == null) return null; Element reply; try { reply = connection.askDumping(request); } catch (IOException e) { logger.log(Level.WARNING, "Could not send \"" + request.getTagName() + "\"-message.", e); reply = null; } return reply; } /** * Speaks to a chief in a native settlement, but only if it is as * a result of a scout actually asking to speak to the chief, or * for other settlement-contacting events such as missionary * actions, demanding tribute, learning skills and trading if the * settlementActionsContactChief game option is enabled. * It is still unclear what Col1 did here. * * @param serverPlayer The <code>ServerPlayer</code> that is contacting * the settlement. * @param is The <code>IndianSettlement</code> to contact. * @param scout True if this contact is due to a scout asking to * speak to the chief. * @param cs A <code>ChangeSet</code> to update. */ private void csSpeakToChief(ServerPlayer serverPlayer, IndianSettlement is, boolean scout, ChangeSet cs) { serverPlayer.csContact((ServerPlayer) is.getOwner(), null, cs); is.makeContactSettlement(serverPlayer); if (scout || getGame().getSpecification() .getBooleanOption("model.option.settlementActionsContactChief") .getValue()) { is.setSpokenToChief(serverPlayer); } } // Routines that follow implement the controller response to // messages. // The convention is to return an element to be passed back to the // client by the invoking message handler. /** * Ends the turn of the given player. * * @param serverPlayer The <code>ServerPlayer</code> to end the turn of. * @return Null. */ public Element endTurn(ServerPlayer serverPlayer) { FreeColServer freeColServer = getFreeColServer(); ServerGame game = getGame(); ServerPlayer player = (ServerPlayer) game.getCurrentPlayer(); if (serverPlayer != player) { throw new IllegalArgumentException("It is not " + serverPlayer.getName() + "'s turn, it is " + ((player == null) ? "noone" : player.getName()) + "'s!"); } for (;;) { logger.finest("Ending turn for " + player.getName()); player.clearModelMessages(); // Has anyone won? // Do not end single player games where an AI has won, // that would stop revenge mode. Player winner = game.checkForWinner(); if (winner != null && !(freeColServer.isSingleplayer() && winner.isAI())) { ChangeSet cs = new ChangeSet(); cs.addTrivial(See.all(), "gameEnded", ChangePriority.CHANGE_NORMAL, "winner", winner.getId()); sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } // Are there humans left? // TODO: see if this can be relaxed so we can run large // AI-only simulations. boolean human = false; for (Player p : game.getPlayers()) { if (!p.isDead() && !p.isAI() && ((ServerPlayer) p).isConnected()) { human = true; break; } } if (!human) { game.setCurrentPlayer(null); return null; } // ATM AI player colony-rearrangements do not use the standard // c-s model but exploit the fact that the AIs and the server // are still in the same memory space. This means that // the colony sizes will be wrongly reported unless we take // the following explicit action. ChangeSet cs = new ChangeSet(); if (player.isAI() && player.isEuropean()) { for (Colony c : player.getColonies()) { cs.add(See.perhaps().except(player), c); } } // Clean up futures from the current player. resolveOutstandingQueries(); // Check for new turn if (game.isNextPlayerInNewTurn()) { game.csNewTurn(random, cs); if (debugOnlyAITurns > 0) { if (--debugOnlyAITurns <= 0) { // If this was a debug run, complete it. This will // possibly signal the client to save and quit. if (FreeCol.getDebugRunTurns() > 0) { FreeCol.completeDebugRun(); } } } } if ((player = (ServerPlayer) game.getNextPlayer()) == null) { // "can not happen" return DOMMessage.clientError("Can not get next player"); } if (player.checkForDeath()) { // Remove dead players and retry player.csWithdraw(cs); sendToAll(cs); logger.info(player.getNation() + " is dead."); continue; } else if (player.isREF() && player.checkForREFDefeat()) { for (Player p : player.getRebels()) { csGiveIndependence(player, (ServerPlayer) p, cs); } player.csWithdraw(cs); sendToAll(cs); logger.info(player.getNation() + " is defeated."); continue; } // Do "new turn"-like actions that need to wait until right // before the player is about to move. game.setCurrentPlayer(player); if (player.isREF() && player.getEntryLocation() == null) { // Initialize this newly created REF, determining its // entry location. // If the teleportREF option is enabled, teleport it in. REFAIPlayer refAIPlayer = (REFAIPlayer) freeColServer .getAIPlayer(player); boolean teleport = getGame().getSpecification() .getBoolean(GameOptions.TELEPORT_REF); Tile entry = refAIPlayer.initialize(teleport); if (entry == null) { for (Player p : player.getRebels()) { entry = p.getEntryLocation().getTile(); break; } } player.setEntryLocation(entry); logger.info(player.getName() + " will appear at " + entry); if (teleport) { for (Unit u : player.getUnits()) { if (u.isNaval()) { u.setLocation(entry); u.setWorkLeft(-1); u.setState(Unit.UnitState.ACTIVE); } } cs.add(See.perhaps(), entry); } } player.csStartTurn(random, cs); nextFoundingFather(player); cs.addTrivial(See.all(), "setCurrentPlayer", ChangePriority.CHANGE_LATE, "player", player.getId()); if (player.getPlayerType() == PlayerType.COLONIAL) { Monarch monarch = player.getMonarch(); MonarchAction action = null; if (debugMonarchAction != null && player == debugMonarchPlayer) { action = debugMonarchAction; debugMonarchAction = null; debugMonarchPlayer = null; logger.finest("Debug monarch action: " + action); } else { action = RandomChoice.getWeightedRandom(logger, "Choose monarch action", random, monarch.getActionChoices()); } if (action != null) { if (monarch.actionIsValid(action)) { logger.finest("Monarch action: " + action); csMonarchAction(player, action, cs); } else { logger.finest("Skipping invalid monarch action: " + action); } } } // Flush accumulated changes and return. // Send to all players, taking care that the new player is - // last, then return null to the old player who requested + // last, then return to the old player who requested // the end-of-turn. sendToList(getOtherPlayers(serverPlayer, (ServerPlayer)player), cs); - sendElement(serverPlayer, cs); sendElement((ServerPlayer)player, cs); - return null; + return cs.build(serverPlayer); } } /** * Queries a player to choose their next founding father in a future. * * @param serverPlayer The <code>ServerPlayer</code> to ask. */ private void nextFoundingFather(final ServerPlayer serverPlayer) { if (!serverPlayer.canRecruitFoundingFather()) return; if (serverPlayer.getOfferedFathers().isEmpty()) { serverPlayer.setOfferedFathers(serverPlayer .getRandomFoundingFathers(random)); } final List<FoundingFather> ffs = serverPlayer.getOfferedFathers(); if (ffs.isEmpty()) return; askThisTurn(serverPlayer, new ChooseFoundingFatherMessage(ffs), new DOMMessageHandler() { public DOMMessage handle(DOMMessage request) { ChooseFoundingFatherMessage message = (ChooseFoundingFatherMessage)request; FoundingFather ff = message.getResult(); if (ff == null) { logger.warning("No founding father selected"); } else if (!ffs.contains(ff)) { logger.warning("Invalid founding father: " + ff.getId()); } else { serverPlayer.setCurrentFather(ff); serverPlayer.clearOfferedFathers(); logger.info("Selected founding father: " + ff); } return null; } }, null); } /** * Give independence. Note that the REF player is granting, but * most of the changes happen to the newly independent player. * hence the special handling. * * @param serverPlayer The REF <code>ServerPlayer</code> that is granting. * @param independent The newly independent <code>ServerPlayer</code>. * @param cs A <code>ChangeSet</code> to update. */ private void csGiveIndependence(ServerPlayer serverPlayer, ServerPlayer independent, ChangeSet cs) { serverPlayer.csChangeStance(Stance.PEACE, independent, true, cs); independent.setPlayerType(PlayerType.INDEPENDENT); Game game = getGame(); Turn turn = game.getTurn(); independent.modifyScore(SCORE_INDEPENDENCE_GRANTED - turn.getNumber()); independent.setTax(0); independent.reinitialiseMarket(); cs.addGlobalHistory(game, new HistoryEvent(turn, HistoryEvent.EventType.INDEPENDENCE)); cs.addMessage(See.only(independent), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "model.player.independence", independent) .addStringTemplate("%ref%", serverPlayer.getNationName())); // Who surrenders? List<Unit> surrenderUnits = new ArrayList<Unit>(); for (Unit u : serverPlayer.getUnits()) { if (!u.isNaval()) surrenderUnits.add(u); } if (surrenderUnits.size() > 0) { for (Unit u : surrenderUnits) { UnitType downgrade = u.getTypeChange(ChangeType.CAPTURE, independent); if (downgrade != null) u.setType(downgrade); u.setOwner(independent); // Make sure the former owner is notified! cs.add(See.perhaps().always(serverPlayer), u); } cs.addMessage(See.only(independent), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "model.player.independence.unitsAcquired", independent) .addStringTemplate("%units%", unitTemplate(", ", surrenderUnits))); } // Update player type. Again, a pity to have to do a whole // player update, but a partial update works for other players. cs.addPartial(See.all().except(independent), independent, "playerType"); cs.addMessage(See.all().except(independent), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "model.player.independence.announce", independent) .addStringTemplate("%nation%", independent.getNationName()) .addStringTemplate("%ref%", serverPlayer.getNationName())); cs.add(See.only(independent), independent); } private StringTemplate unitTemplate(String base, List<Unit> units) { StringTemplate template = StringTemplate.label(base); for (Unit u : units) { template.addStringTemplate(u.getLabel()); } return template; } private StringTemplate abstractUnitTemplate(String base, List<AbstractUnit> units) { StringTemplate template = StringTemplate.label(base); Specification spec = getGame().getSpecification(); for (AbstractUnit au : units) { template.addStringTemplate(au.getLabel(spec)); } return template; } private String getNonPlayerNation() { int nations = Nation.EUROPEAN_NATIONS.length; int start = Utils.randomInt(logger, "Random nation", random, nations); for (int index = 0; index < nations; index++) { String nationId = "model.nation." + Nation.EUROPEAN_NATIONS[(start + index) % nations]; if (getGame().getPlayer(nationId) == null) { return nationId + ".name"; } } // this should never happen return ""; } /** * Resolves a tax raise. * * @param serverPlayer The <code>ServerPlayer</code> whose tax is rising. * @param taxRaise The amount of tax raise. * @param goods The <code>Goods</code> for a goods party. * @param result Whether the tax was accepted or not. */ private void raiseTax(ServerPlayer serverPlayer, int taxRaise, Goods goods, boolean result) { ChangeSet cs = new ChangeSet(); serverPlayer.csRaiseTax(taxRaise, goods, result, cs); sendElement(serverPlayer, cs); } /** * Performs a monarch action. * * Note that CHANGE_LATE is used so that these actions follow * setting the current player, so that it is the players turn when * they respond to a monarch action. * * @param serverPlayer The <code>ServerPlayer</code> being acted upon. * @param action The monarch action. * @param cs A <code>ChangeSet</code> to update. */ private void csMonarchAction(final ServerPlayer serverPlayer, MonarchAction action, ChangeSet cs) { final Monarch monarch = serverPlayer.getMonarch(); boolean valid = monarch.actionIsValid(action); if (!valid) return; String messageId = "model.monarch.action." + action.toString(); StringTemplate template; MonarchActionMessage message; switch (action) { case NO_ACTION: break; case RAISE_TAX_WAR: case RAISE_TAX_ACT: final int taxRaise = monarch.raiseTax(random); final Goods goods = serverPlayer.getMostValuableGoods(); if (goods == null) { logger.finest("Ignoring tax raise, no goods to boycott."); break; } template = StringTemplate.template("model.monarch.action." + action.toString()) .addStringTemplate("%goods%", goods.getType().getLabel(true)) .addAmount("%amount%", taxRaise); if (action == MonarchAction.RAISE_TAX_WAR) { template = template.add("%nation%", getNonPlayerNation()); } else if (action == MonarchAction.RAISE_TAX_ACT) { template = template.addAmount("%number%", Utils.randomInt(logger, "Tax act goods", random, 6)) .addName("%newWorld%", serverPlayer.getNewLandName()); } message = new MonarchActionMessage(action, template); message.setTax(taxRaise); askThisTurn(serverPlayer, message, new DOMMessageHandler() { public DOMMessage handle(DOMMessage message) { boolean result = (message instanceof MonarchActionMessage) ? ((MonarchActionMessage)message).getResult() : false; raiseTax(serverPlayer, taxRaise, goods, result); return null; } }, new Runnable() { public void run() { raiseTax(serverPlayer, taxRaise, goods, false); } }); break; case LOWER_TAX_WAR: case LOWER_TAX_OTHER: int oldTax = serverPlayer.getTax(); int taxLower = monarch.lowerTax(random); serverPlayer.csSetTax(taxLower, cs); template = StringTemplate.template(messageId) .addAmount("%difference%", oldTax - taxLower) .addAmount("%newTax%", taxLower); if (action == MonarchAction.LOWER_TAX_WAR) { template = template.add("%nation%", getNonPlayerNation()); } else { template = template.addAmount("%number%", Utils.randomInt(logger, "Lower tax reason", random, 5)); } cs.add(See.only(serverPlayer), ChangePriority.CHANGE_LATE, new MonarchActionMessage(action, template)); break; case WAIVE_TAX: cs.add(See.only(serverPlayer), ChangePriority.CHANGE_NORMAL, new MonarchActionMessage(action, StringTemplate.template(messageId))); break; case ADD_TO_REF: AbstractUnit refAdditions = monarch.chooseForREF(random); if (refAdditions == null) break; monarch.getExpeditionaryForce().add(refAdditions); template = StringTemplate.template(messageId) .addAmount("%number%", refAdditions.getNumber()) .add("%unit%", refAdditions.getUnitType(getGame().getSpecification()) .getNameKey()); cs.add(See.only(serverPlayer), monarch); cs.add(See.only(serverPlayer), ChangePriority.CHANGE_LATE, new MonarchActionMessage(action, template)); break; case DECLARE_WAR: List<Player> enemies = monarch.collectPotentialEnemies(); if (enemies.isEmpty()) break; Player enemy = Utils.getRandomMember(logger, "Choose enemy", enemies, random); serverPlayer.csChangeStance(Stance.WAR, enemy, true, cs); cs.add(See.only(serverPlayer), ChangePriority.CHANGE_LATE, new MonarchActionMessage(action, StringTemplate.template(messageId) .addStringTemplate("%nation%", enemy.getNationName()))); break; case SUPPORT_LAND: case SUPPORT_SEA: boolean sea = action == MonarchAction.SUPPORT_SEA; List<AbstractUnit> support = monarch.getSupport(random, sea); if (support.isEmpty()) break; serverPlayer.createUnits(support, serverPlayer.getEurope()); cs.add(See.only(serverPlayer), serverPlayer.getEurope()); cs.add(See.only(serverPlayer), ChangePriority.CHANGE_LATE, new MonarchActionMessage(action, StringTemplate.template(messageId) .addStringTemplate("%addition%", abstractUnitTemplate(", ", support)))); break; case OFFER_MERCENARIES: final List<AbstractUnit> mercenaries = monarch.getMercenaries(random); if (mercenaries.isEmpty()) break; final int mercPrice = serverPlayer.priceMercenaries(mercenaries); message = new MonarchActionMessage(MonarchAction.OFFER_MERCENARIES, StringTemplate.template("model.monarch.action.OFFER_MERCENARIES") .addAmount("%gold%", mercPrice) .addStringTemplate("%mercenaries%", abstractUnitTemplate(", ", mercenaries))); askThisTurn(serverPlayer, message, new DOMMessageHandler() { public DOMMessage handle(DOMMessage message) { boolean result = (message instanceof MonarchActionMessage) ? ((MonarchActionMessage)message).getResult() : false; if (result) { ChangeSet cs = new ChangeSet(); serverPlayer.csAddMercenaries(mercenaries, mercPrice, cs); sendElement(serverPlayer, cs); } return null; } }, null); break; case DISPLEASURE: default: logger.warning("Bogus action: " + action); break; } } /** * Check the high scores. * * @param serverPlayer The <code>ServerPlayer</code> that is retiring. * @return An element indicating the players high score state. */ public Element checkHighScore(ServerPlayer serverPlayer) { FreeColServer freeColServer = getFreeColServer(); boolean highScore = freeColServer.newHighScore(serverPlayer); if (highScore) { try { freeColServer.saveHighScores(); } catch (Exception e) { logger.log(Level.WARNING, "Failed to save high scores", e); highScore = false; } } ChangeSet cs = new ChangeSet(); cs.addAttribute(See.only(serverPlayer), "highScore", Boolean.toString(highScore)); return cs.build(serverPlayer); } /** * Handle a player retiring. * * @param serverPlayer The <code>ServerPlayer</code> that is retiring. * @return An element cleaning up the player. */ public Element retire(ServerPlayer serverPlayer) { ChangeSet cs = new ChangeSet(); serverPlayer.csWithdraw(cs); // Clean up the player. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Continue playing after winning. * * @param serverPlayer The <code>ServerPlayer</code> that plays on. * @return Null. */ public Element continuePlaying(ServerPlayer serverPlayer) { ServerGame game = (ServerGame) getGame(); Element reply = null; if (!getFreeColServer().isSingleplayer()) { logger.warning("Can not continue playing in multiplayer!"); } else if (serverPlayer != game.checkForWinner()) { logger.warning("Can not continue playing, as " + serverPlayer.getName() + " has not won the game!"); } else { Specification spec = game.getSpecification(); spec.getBooleanOption(GameOptions.VICTORY_DEFEAT_REF) .setValue(false); spec.getBooleanOption(GameOptions.VICTORY_DEFEAT_EUROPEANS) .setValue(false); spec.getBooleanOption(GameOptions.VICTORY_DEFEAT_HUMANS) .setValue(false); // The victory panel is shown after end turn, end turn again // to start turn of next player. reply = endTurn((ServerPlayer) game.getCurrentPlayer()); } return reply; } /** * Cash in a treasure train. * * @param serverPlayer The <code>ServerPlayer</code> that is cashing in. * @param unit The treasure train <code>Unit</code> to cash in. * @return An <code>Element</code> encapsulating this action. */ public Element cashInTreasureTrain(ServerPlayer serverPlayer, Unit unit) { ChangeSet cs = new ChangeSet(); // Work out the cash in amount and the message to send. int fullAmount = unit.getTreasureAmount(); int cashInAmount; String messageId; if (serverPlayer.getPlayerType() == PlayerType.COLONIAL) { // Charge transport fee and apply tax cashInAmount = (fullAmount - unit.getTransportFee()) * (100 - serverPlayer.getTax()) / 100; messageId = "model.unit.cashInTreasureTrain.colonial"; } else { // No fee possible, no tax applies. cashInAmount = fullAmount; messageId = "model.unit.cashInTreasureTrain.independent"; } serverPlayer.modifyGold(cashInAmount); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold", "score"); cs.addMessage(See.only(serverPlayer), new ModelMessage(messageId, serverPlayer, unit) .addAmount("%amount%", fullAmount) .addAmount("%cashInAmount%", cashInAmount)); messageId = (serverPlayer.getPlayerType() == PlayerType.REBEL || serverPlayer.getPlayerType() == PlayerType.INDEPENDENT) ? "model.unit.cashInTreasureTrain.other.independent" : "model.unit.cashInTreasureTrain.other.colonial"; cs.addMessage(See.all().except(serverPlayer), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, messageId, serverPlayer) .addAmount("%amount%", fullAmount) .addStringTemplate("%nation%", serverPlayer.getNationName())); // Dispose of the unit, only visible to the owner. cs.add(See.only(serverPlayer), (FreeColGameObject) unit.getLocation()); cs.addDispose(See.only(serverPlayer), null, unit); // Others can see the cash in message. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Declare independence. * * @param serverPlayer The <code>ServerPlayer</code> that is naming. * @param nationName The new name for the independent nation. * @param countryName The new name for its residents. * @return An <code>Element</code> encapsulating this action. */ public Element declareIndependence(ServerPlayer serverPlayer, String nationName, String countryName) { ChangeSet cs = new ChangeSet(); // Cross the Rubicon StringTemplate oldNation = serverPlayer.getNationName(); serverPlayer.setIndependentNationName(nationName); serverPlayer.setNewLandName(countryName); serverPlayer.setPlayerType(PlayerType.REBEL); serverPlayer.addAbility(new Ability("model.ability.independenceDeclared")); serverPlayer.modifyScore(SCORE_INDEPENDENCE_DECLARED); // Do not add history event to cs as we are going to update the // entire player. Likewise clear model messages. Turn turn = getGame().getTurn(); cs.addGlobalHistory(getGame(), new HistoryEvent(turn, HistoryEvent.EventType.DECLARE_INDEPENDENCE)); serverPlayer.clearModelMessages(); cs.addMessage(See.only(serverPlayer), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "warOfIndependence.independenceDeclared", serverPlayer)); // Dispose of units in Europe. Europe europe = serverPlayer.getEurope(); StringTemplate seized = StringTemplate.label(", "); for (Unit u : europe.getUnitList()) { seized.addStringTemplate(u.getLabel()); } if (!seized.getReplacements().isEmpty()) { cs.addMessage(See.only(serverPlayer), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.player.independence.unitsSeized", serverPlayer) .addStringTemplate("%units%", seized)); } // Generalized continental army muster java.util.Map<UnitType, UnitType> upgrades = new HashMap<UnitType, UnitType>(); Specification spec = getGame().getSpecification(); for (UnitType unitType : spec.getUnitTypeList()) { UnitType upgrade = unitType.getTargetType(ChangeType.INDEPENDENCE, serverPlayer); if (upgrade != null) { upgrades.put(unitType, upgrade); } } for (Colony colony : serverPlayer.getColonies()) { int sol = colony.getSoL(); if (sol > 50) { java.util.Map<UnitType, List<Unit>> unitMap = new HashMap<UnitType, List<Unit>>(); List<Unit> allUnits = colony.getTile().getUnitList(); allUnits.addAll(colony.getUnitList()); for (Unit unit : allUnits) { if (upgrades.containsKey(unit.getType())) { List<Unit> unitList = unitMap.get(unit.getType()); if (unitList == null) { unitList = new ArrayList<Unit>(); unitMap.put(unit.getType(), unitList); } unitList.add(unit); } } for (Entry<UnitType, List<Unit>> entry : unitMap.entrySet()) { int limit = (entry.getValue().size() + 2) * (sol - 50) / 100; if (limit > 0) { for (int index = 0; index < limit; index++) { Unit unit = entry.getValue().get(index); if (unit == null) break; unit.setType(upgrades.get(entry.getKey())); cs.add(See.only(serverPlayer), unit); } cs.addMessage(See.only(serverPlayer), new ModelMessage(ModelMessage.MessageType.UNIT_IMPROVED, "model.player.continentalArmyMuster", serverPlayer, colony) .addName("%colony%", colony.getName()) .addAmount("%number%", limit) .add("%oldUnit%", entry.getKey().getNameKey()) .add("%unit%", upgrades.get(entry.getKey()).getNameKey())); } } } } // Create the REF. ServerPlayer refPlayer = createREFPlayer(serverPlayer); // Update the intervention force serverPlayer.getMonarch().updateInterventionForce(); cs.addMessage(See.only(serverPlayer), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "declareIndependence.interventionForce", serverPlayer) .add("%nation%", getNonPlayerNation()) .addAmount("%number%", spec.getInteger("model.option.interventionBells"))); // Now the REF is ready, we can dispose of the European connection. serverPlayer.getHighSeas().removeDestination(europe); cs.addDispose(See.only(serverPlayer), null, europe); serverPlayer.setEurope(null); //serverPlayer.setMonarch(null); // Pity to have to update such a heavy object as the player, // but we do this, at most, once per player. Other players // only need a partial player update and the stance change. // Put the stance change after the name change so that the // other players see the new nation name declaring war. The // REF is hardwired to declare war on rebels so there is no // need to adjust its stance or tension. cs.addPartial(See.all().except(serverPlayer), serverPlayer, "playerType", "independentNationName", "newLandName"); cs.addMessage(See.all().except(serverPlayer), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "declareIndependence.announce", serverPlayer) .addStringTemplate("%oldNation%", oldNation) .addStringTemplate("%newNation%", serverPlayer.getNationName()) .add("%ruler%", serverPlayer.getRulerNameKey())); cs.add(See.only(serverPlayer), serverPlayer); serverPlayer.csChangeStance(Stance.WAR, refPlayer, true, cs); sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Rename an object. * * @param serverPlayer The <code>ServerPlayer</code> that is naming. * @param object The <code>Nameable</code> to rename. * @param newName The new name. * @return An <code>Element</code> encapsulating this action. */ public Element renameObject(ServerPlayer serverPlayer, Nameable object, String newName) { ChangeSet cs = new ChangeSet(); object.setName(newName); FreeColGameObject fcgo = (FreeColGameObject) object; cs.addPartial(See.all(), fcgo, "name"); // Others may be able to see the name change. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Gets a settlement transaction session, either existing or * newly opened. * * @param serverPlayer The <code>ServerPlayer</code> that is trading. * @param unit The <code>Unit</code> that is trading. * @param settlement The <code>Settlement</code> that is trading. * @return An <code>Element</code> encapsulating this action. */ public Element getTransaction(ServerPlayer serverPlayer, Unit unit, Settlement settlement) { ChangeSet cs = new ChangeSet(); TradeSession session = TransactionSession.lookup(TradeSession.class, unit, settlement); if (session == null) { if (unit.getMovesLeft() <= 0) { return DOMMessage.clientError("Unit " + unit.getId() + " has no moves left."); } session = new TradeSession(unit, settlement); // Sets unit moves to zero to avoid cheating. If no // action is taken, the moves will be restored when // closing the session unit.setMovesLeft(0); cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); } // Add just the attributes the client needs. cs.addAttribute(See.only(serverPlayer), "canBuy", Boolean.toString(session.getBuy())); cs.addAttribute(See.only(serverPlayer), "canSell", Boolean.toString(session.getSell())); cs.addAttribute(See.only(serverPlayer), "canGift", Boolean.toString(session.getGift())); // Others can not see transactions. return cs.build(serverPlayer); } /** * Close a transaction. * * @param serverPlayer The <code>ServerPlayer</code> that is trading. * @param unit The <code>Unit</code> that is trading. * @param settlement The <code>Settlement</code> that is trading. * @return An <code>Element</code> encapsulating this action. */ public Element closeTransaction(ServerPlayer serverPlayer, Unit unit, Settlement settlement) { TradeSession session = TradeSession.lookup(TradeSession.class, unit, settlement); if (session == null) { return DOMMessage.clientError("No such transaction session."); } ChangeSet cs = new ChangeSet(); // Restore unit movement if no action taken. if (!session.getActionTaken()) { unit.setMovesLeft(session.getMovesLeft()); cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); } session.complete(cs); // Others can not see end of transaction. return cs.build(serverPlayer); } /** * Get the goods for sale in a settlement. * * @param serverPlayer The <code>ServerPlayer</code> that is enquiring. * @param unit The <code>Unit</code> that is trading. * @param settlement The <code>Settlement</code> that is trading. * @return An <code>Element</code> encapsulating this action. */ public Element getGoodsForSale(ServerPlayer serverPlayer, Unit unit, Settlement settlement) { List<Goods> sellGoods = null; if (settlement instanceof IndianSettlement) { IndianSettlement indianSettlement = (IndianSettlement) settlement; AIPlayer aiPlayer = getFreeColServer() .getAIPlayer(indianSettlement.getOwner()); sellGoods = indianSettlement.getSellGoods(3, unit); for (Goods goods : sellGoods) { aiPlayer.registerSellGoods(goods); } } else { // Colony might be supported one day? return DOMMessage.clientError("Bogus settlement"); } return new GoodsForSaleMessage(unit, settlement, sellGoods) .toXMLElement(); } /** * Price some goods for sale from a settlement. * * @param serverPlayer The <code>ServerPlayer</code> that is buying. * @param unit The <code>Unit</code> that is trading. * @param settlement The <code>Settlement</code> that is trading. * @param goods The <code>Goods</code> to buy. * @param price The buyers proposed price for the goods. * @return An <code>Element</code> encapsulating this action. */ public Element buyProposition(ServerPlayer serverPlayer, Unit unit, Settlement settlement, Goods goods, int price) { TradeSession session = TradeSession.lookup(TradeSession.class, unit, settlement); if (session == null) { return DOMMessage.clientError("Proposing to buy without opening a transaction session?!"); } if (!session.getBuy()) { return DOMMessage.clientError("Proposing to buy in a session where buying is not allowed."); } ChangeSet cs = new ChangeSet(); if (settlement instanceof IndianSettlement) { csSpeakToChief(serverPlayer, (IndianSettlement)settlement, false, cs); } // AI considers the proposition, return with a gold value AIPlayer ai = getFreeColServer().getAIPlayer(settlement.getOwner()); int gold = ai.buyProposition(unit, settlement, goods, price); // Others can not see proposals. cs.addAttribute(See.only(serverPlayer), "gold", Integer.toString(gold)); return cs.build(serverPlayer); } /** * Price some goods for sale to a settlement. * * @param serverPlayer The <code>ServerPlayer</code> that is buying. * @param unit The <code>Unit</code> that is trading. * @param settlement The <code>Settlement</code> that is trading. * @param goods The <code>Goods</code> to sell. * @param price The sellers proposed price for the goods. * @return An <code>Element</code> encapsulating this action. */ public Element sellProposition(ServerPlayer serverPlayer, Unit unit, Settlement settlement, Goods goods, int price) { TradeSession session = TradeSession.lookup(TradeSession.class, unit, settlement); if (session == null) { return DOMMessage.clientError("Proposing to sell without opening a transaction session"); } if (!session.getSell()) { return DOMMessage.clientError("Proposing to sell in a session where selling is not allowed."); } ChangeSet cs = new ChangeSet(); if (settlement instanceof IndianSettlement) { csSpeakToChief(serverPlayer, (IndianSettlement)settlement, false, cs); } // AI considers the proposition, return with a gold value AIPlayer ai = getFreeColServer().getAIPlayer(settlement.getOwner()); int gold = ai.sellProposition(unit, settlement, goods, price); // Others can not see proposals. cs.addAttribute(See.only(serverPlayer), "gold", Integer.toString(gold)); return cs.build(serverPlayer); } /** * Buy goods in Europe. * * @param serverPlayer The <code>ServerPlayer</code> that is buying. * @param unit The <code>Unit</code> to carry the goods. * @param type The <code>GoodsType</code> to buy. * @param amount The amount of goods to buy. * @return An <code>Element</code> encapsulating this action. */ public Element buyGoods(ServerPlayer serverPlayer, Unit unit, GoodsType type, int amount) { if (!serverPlayer.canTrade(type, Access.EUROPE)) { return DOMMessage.clientError("Can not trade boycotted goods"); } ChangeSet cs = new ChangeSet(); GoodsContainer container = unit.getGoodsContainer(); container.saveState(); serverPlayer.buy(container, type, amount, random); serverPlayer.csFlushMarket(type, cs); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); cs.add(See.only(serverPlayer), container); // Action occurs in Europe, nothing is visible to other players. return cs.build(serverPlayer); } /** * Sell goods in Europe. * * @param serverPlayer The <code>ServerPlayer</code> that is selling. * @param unit The <code>Unit</code> carrying the goods. * @param type The <code>GoodsType</code> to sell. * @param amount The amount of goods to sell. * @return An <code>Element</code> encapsulating this action. */ public Element sellGoods(ServerPlayer serverPlayer, Unit unit, GoodsType type, int amount) { if (!serverPlayer.canTrade(type, Access.EUROPE)) { return DOMMessage.clientError("Can not trade boycotted goods"); } ChangeSet cs = new ChangeSet(); GoodsContainer container = unit.getGoodsContainer(); container.saveState(); serverPlayer.sell(container, type, amount, random); serverPlayer.csFlushMarket(type, cs); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); cs.add(See.only(serverPlayer), container); // Action occurs in Europe, nothing is visible to other players. return cs.build(serverPlayer); } /** * A unit migrates from Europe. * * @param serverPlayer The <code>ServerPlayer</code> whose unit it will be. * @param slot The slot within <code>Europe</code> to select the unit from. * @param type The type of migration occurring. * @return An <code>Element</code> encapsulating this action. */ public Element emigrate(ServerPlayer serverPlayer, int slot, MigrationType type) { ChangeSet cs = new ChangeSet(); serverPlayer.csEmigrate(slot, type, random, cs); // Do not update others, emigration is private. return cs.build(serverPlayer); } /** * Move a unit. * * @param serverPlayer The <code>ServerPlayer</code> that is moving. * @param unit The <code>Unit</code> to move. * @param newTile The <code>Tile</code> to move to. * @return An <code>Element</code> encapsulating this action. */ public Element move(ServerPlayer serverPlayer, Unit unit, Tile newTile) { ChangeSet cs = new ChangeSet(); ((ServerUnit) unit).csMove(newTile, random, cs); sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Decline to investigate strange mounds. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param tile The <code>Tile</code> where the mounds are. * @return An <code>Element</code> encapsulating this action. */ public Element declineMounds(ServerPlayer serverPlayer, Tile tile) { tile.removeLostCityRumour(); // Others might see rumour disappear ChangeSet cs = new ChangeSet(); cs.add(See.perhaps(), tile); sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Set land name. * * @param serverPlayer The <code>ServerPlayer</code> who landed. * @param unit The <code>Unit</code> that has come ashore. * @param name The new land name. * @param welcomer An optional <code>ServerPlayer</code> that has offered * a treaty. * @param camps An optional number of camps for the welcome message. * @param accept True if the treaty has been accepted. * @return An <code>Element</code> encapsulating this action. */ public Element setNewLandName(ServerPlayer serverPlayer, Unit unit, String name, ServerPlayer welcomer, int camps, boolean accept) { ChangeSet cs = new ChangeSet(); // Special case of a welcome from an adjacent native unit, // offering the land the landing unit is on if a peace treaty // is accepted. serverPlayer.setNewLandName(name); if (welcomer != null) { if (accept) { // Claim land Tile tile = unit.getTile(); tile.changeOwnership(serverPlayer, null); cs.add(See.perhaps(), tile); } else { // Consider not accepting the treaty to be an insult. cs.add(See.only(null).perhaps(serverPlayer), welcomer.modifyTension(serverPlayer, Tension.TENSION_ADD_MAJOR)); } } // Update the name and note the history. cs.addPartial(See.only(serverPlayer), serverPlayer, "newLandName"); Turn turn = serverPlayer.getGame().getTurn(); cs.addHistory(serverPlayer, new HistoryEvent(turn, HistoryEvent.EventType.DISCOVER_NEW_WORLD) .addName("%name%", name)); // Only the tile change is not private. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Set region name. * * @param serverPlayer The <code>ServerPlayer</code> discovering. * @param region The <code>Region</code> to discover. * @param name The new region name. * @return An <code>Element</code> encapsulating this action. */ public Element setNewRegionName(ServerPlayer serverPlayer, Region region, String name) { ChangeSet cs = new ChangeSet(); cs.addRegion(serverPlayer, region, name); // Others do find out about region name changes. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Move a unit across the high seas. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The <code>Unit</code> to move. * @param destination The <code>Location</code> to move to. * @return An <code>Element</code> encapsulating this action. */ public Element moveTo(ServerPlayer serverPlayer, Unit unit, Location destination) { ChangeSet cs = new ChangeSet(); HighSeas highSeas = serverPlayer.getHighSeas(); Location current = unit.getDestination(); boolean others = false; // Notify others? boolean invalid = false; // Not a highSeas move? if (destination instanceof Europe) { if (!highSeas.getDestinations().contains(destination)) { return DOMMessage.clientError("HighSeas does not connect to: " + ((FreeColGameObject) destination).getId()); } else if (unit.getLocation() == highSeas) { if (!(current instanceof Europe)) { // Changed direction unit.setWorkLeft(unit.getSailTurns() - unit.getWorkLeft() + 1); } unit.setDestination(destination); cs.add(See.only(serverPlayer), unit, highSeas); } else if (unit.getTile() != null) { Tile tile = unit.getTile(); unit.setEntryLocation(tile); unit.setWorkLeft(unit.getSailTurns()); unit.setDestination(destination); unit.setMovesLeft(0); unit.setLocation(highSeas); cs.addDisappear(serverPlayer, tile, unit); cs.add(See.only(serverPlayer), tile, highSeas); others = true; } else { invalid = true; } } else if (destination instanceof Map) { if (!highSeas.getDestinations().contains(destination)) { return DOMMessage.clientError("HighSeas does not connect to: " + ((FreeColGameObject) destination).getId()); } else if (unit.getLocation() == highSeas) { if (current != destination && (current == null || current.getTile() == null || current.getTile().getMap() != destination)) { // Changed direction unit.setWorkLeft(unit.getSailTurns() - unit.getWorkLeft() + 1); } unit.setDestination(destination); cs.add(See.only(serverPlayer), highSeas); } else if (unit.getLocation() instanceof Europe) { Europe europe = (Europe) unit.getLocation(); unit.setWorkLeft(unit.getSailTurns()); unit.setDestination(destination); unit.setMovesLeft(0); unit.setLocation(highSeas); cs.add(See.only(serverPlayer), europe, highSeas); } else { invalid = true; } } else if (destination instanceof Settlement) { Tile tile = destination.getTile(); if (!highSeas.getDestinations().contains(tile.getMap())) { return DOMMessage.clientError("HighSeas does not connect to: " + ((FreeColGameObject) destination).getId()); } else if (unit.getLocation() == highSeas) { // Direction is somewhat moot, so just reset. unit.setWorkLeft(unit.getSailTurns()); unit.setDestination(destination); cs.add(See.only(serverPlayer), highSeas); } else if (unit.getLocation() instanceof Europe) { Europe europe = (Europe) unit.getLocation(); unit.setWorkLeft(unit.getSailTurns()); unit.setDestination(destination); unit.setMovesLeft(0); unit.setLocation(highSeas); cs.add(See.only(serverPlayer), europe, highSeas); } else { invalid = true; } } else { return DOMMessage.clientError("Bogus moveTo destination: " + ((FreeColGameObject) destination).getId()); } if (invalid) { return DOMMessage.clientError("Invalid moveTo: unit=" + unit.getId() + " from=" + ((FreeColGameObject) unit.getLocation()).getId() + " to=" + ((FreeColGameObject) destination).getId()); } if (others) sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Embark a unit onto a carrier. * Checking that the locations are appropriate is not done here. * * @param serverPlayer The <code>ServerPlayer</code> embarking. * @param unit The <code>Unit</code> that is embarking. * @param carrier The <code>Unit</code> to embark onto. * @return An <code>Element</code> encapsulating this action. */ public Element embarkUnit(ServerPlayer serverPlayer, Unit unit, Unit carrier) { if (unit.isNaval()) { return DOMMessage.clientError("Naval unit " + unit.getId() + " can not embark."); } if (carrier.getSpaceLeft() < unit.getSpaceTaken()) { return DOMMessage.clientError("No space available for unit " + unit.getId() + " to embark."); } ChangeSet cs = new ChangeSet(); Location oldLocation = unit.getLocation(); unit.setLocation(carrier); unit.setMovesLeft(0); cs.add(See.only(serverPlayer), (FreeColGameObject) oldLocation); if (carrier.getLocation() != oldLocation) { cs.add(See.only(serverPlayer), carrier); } if (oldLocation instanceof Tile) { cs.addMove(See.only(serverPlayer), unit, (Tile) oldLocation, carrier.getTile()); cs.addDisappear(serverPlayer, (Tile) oldLocation, unit); } // Others might see the unit disappear, or the carrier capacity. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Disembark unit from a carrier. * * @param serverPlayer The <code>ServerPlayer</code> whose unit is * embarking. * @param unit The <code>Unit</code> that is disembarking. * @return An <code>Element</code> encapsulating this action. */ public Element disembarkUnit(ServerPlayer serverPlayer, Unit unit) { if (unit.isNaval()) { return DOMMessage.clientError("Naval unit " + unit.getId() + " can not disembark."); } Unit carrier = unit.getCarrier(); if (carrier == null) { return DOMMessage.clientError("Unit " + unit.getId() + " is not embarked."); } ChangeSet cs = new ChangeSet(); Location newLocation = carrier.getLocation(); List<Tile> newTiles = (newLocation.getTile() == null) ? null : ((ServerUnit) unit).collectNewTiles(newLocation.getTile()); unit.setLocation(newLocation); unit.setMovesLeft(0); // In Col1 disembark consumes whole move. cs.add(See.perhaps(), (FreeColGameObject) newLocation); if (newTiles != null) { serverPlayer.csSeeNewTiles(newTiles, cs); } // Others can (potentially) see the location. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Combat. * * @param attackerPlayer The <code>ServerPlayer</code> who is attacking. * @param attacker The <code>FreeColGameObject</code> that is attacking. * @param defender The <code>FreeColGameObject</code> that is defending. * @param crs A list of <code>CombatResult</code>s defining the result. * @return An <code>Element</code> encapsulating this action. */ public Element combat(ServerPlayer attackerPlayer, FreeColGameObject attacker, FreeColGameObject defender, List<CombatResult> crs) { ChangeSet cs = new ChangeSet(); try { attackerPlayer.csCombat(attacker, defender, crs, random, cs); } catch (Exception e) { logger.log(Level.WARNING, "Combat FAIL", e); return DOMMessage.clientError(e.getMessage()); } sendToOthers(attackerPlayer, cs); return cs.build(attackerPlayer); } /** * Ask about learning a skill at an IndianSettlement. * * @param serverPlayer The <code>ServerPlayer</code> that is learning. * @param unit The <code>Unit</code> that is learning. * @param settlement The <code>Settlement</code> to learn from. * @return An <code>Element</code> encapsulating this action. */ public Element askLearnSkill(ServerPlayer serverPlayer, Unit unit, IndianSettlement settlement) { ChangeSet cs = new ChangeSet(); csSpeakToChief(serverPlayer, settlement, false, cs); Tile tile = settlement.getTile(); tile.updatePlayerExploredTile(serverPlayer, true); cs.add(See.only(serverPlayer), tile); unit.setMovesLeft(0); cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); // Do not update others, nothing to see yet. return cs.build(serverPlayer); } /** * Learn a skill at an IndianSettlement. * * @param serverPlayer The <code>ServerPlayer</code> that is learning. * @param unit The <code>Unit</code> that is learning. * @param settlement The <code>Settlement</code> to learn from. * @return An <code>Element</code> encapsulating this action. */ public Element learnFromIndianSettlement(ServerPlayer serverPlayer, Unit unit, IndianSettlement settlement) { // Sanity checks. UnitType skill = settlement.getLearnableSkill(); if (skill == null) { return DOMMessage.clientError("No skill to learn at " + settlement.getName()); } if (!unit.getType().canBeUpgraded(skill, ChangeType.NATIVES)) { return DOMMessage.clientError("Unit " + unit.toString() + " can not learn skill " + skill + " at " + settlement.getName()); } // Try to learn ChangeSet cs = new ChangeSet(); unit.setMovesLeft(0); csSpeakToChief(serverPlayer, settlement, false, cs); switch (settlement.getAlarm(serverPlayer).getLevel()) { case HATEFUL: // Killed, might be visible to other players. cs.add(See.perhaps().always(serverPlayer), (FreeColGameObject) unit.getLocation()); cs.addDispose(See.perhaps().always(serverPlayer), unit.getLocation(), unit); break; case ANGRY: // Learn nothing, not even a pet update cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); break; default: // Teach the unit, and expend the skill if necessary. // Do a full information update as the unit is in the settlement. unit.setType(skill); if (!settlement.isCapital() && !(settlement.getMissionary(serverPlayer) != null && getGame().getSpecification() .getBoolean("model.option.enhancedMissionaries"))) { settlement.setLearnableSkill(null); } break; } Tile tile = settlement.getTile(); tile.updatePlayerExploredTile(serverPlayer, true); cs.add(See.only(serverPlayer), unit, tile); // Others always see the unit, it may have died or been taught. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Demand a tribute from a native settlement. * * @param serverPlayer The <code>ServerPlayer</code> demanding the tribute. * @param unit The <code>Unit</code> that is demanding the tribute. * @param settlement The <code>IndianSettlement</code> demanded of. * @return An <code>Element</code> encapsulating this action. * TODO: Move TURNS_PER_TRIBUTE magic number to the spec. */ public Element demandTribute(ServerPlayer serverPlayer, Unit unit, IndianSettlement settlement) { ChangeSet cs = new ChangeSet(); final int TURNS_PER_TRIBUTE = 5; csSpeakToChief(serverPlayer, settlement, false, cs); Player indianPlayer = settlement.getOwner(); int gold = 0; int year = getGame().getTurn().getNumber(); RandomRange gifts = settlement.getType().getGifts(unit); if (settlement.getLastTribute() + TURNS_PER_TRIBUTE < year && gifts != null) { switch (indianPlayer.getTension(serverPlayer).getLevel()) { case HAPPY: case CONTENT: gold = Math.min(gifts.getAmount("Tribute", random, true) / 10, 100); break; case DISPLEASED: gold = Math.min(gifts.getAmount("Tribute", random, true) / 20, 100); break; case ANGRY: case HATEFUL: default: gold = 0; // No tribute for you. break; } } // Increase tension whether we paid or not. Apply tension // directly to the settlement and let propagation work. cs.add(See.only(serverPlayer), ((ServerIndianSettlement)settlement).modifyAlarm(serverPlayer, Tension.TENSION_ADD_NORMAL)); settlement.setLastTribute(year); ModelMessage m; if (gold > 0) { indianPlayer.modifyGold(-gold); serverPlayer.modifyGold(gold); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold", "score"); m = new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "scoutSettlement.tributeAgree", unit, settlement) .addAmount("%amount%", gold); } else { m = new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "scoutSettlement.tributeDisagree", unit, settlement); } cs.addMessage(See.only(serverPlayer), m); Tile tile = settlement.getTile(); tile.updatePlayerExploredTile(serverPlayer, true); cs.add(See.only(serverPlayer), tile); unit.setMovesLeft(0); cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); // Do not update others, this is all private. return cs.build(serverPlayer); } /** * Scout a native settlement. * * @param serverPlayer The <code>ServerPlayer</code> that is scouting. * @param unit The scout <code>Unit</code>. * @param settlement The <code>IndianSettlement</code> to scout. * @return An <code>Element</code> encapsulating this action. */ public Element scoutIndianSettlement(ServerPlayer serverPlayer, Unit unit, IndianSettlement settlement) { ChangeSet cs = new ChangeSet(); Tile tile = settlement.getTile(); boolean tileDirty = settlement.makeContactSettlement(serverPlayer); String result; // Hateful natives kill the scout right away. Tension tension = settlement.getAlarm(serverPlayer); if (tension.getLevel() == Tension.Level.HATEFUL) { cs.add(See.perhaps().always(serverPlayer), (FreeColGameObject) unit.getLocation()); cs.addDispose(See.perhaps().always(serverPlayer), unit.getLocation(), unit); result = "die"; } else { // Otherwise player gets to visit, and learn about the settlement. List<UnitType> scoutTypes = getGame().getSpecification() .getUnitTypesWithAbility(Ability.EXPERT_SCOUT); UnitType scoutSkill = (scoutTypes.isEmpty()) ? null : scoutTypes.get(0); int radius = unit.getLineOfSight(); UnitType skill = settlement.getLearnableSkill(); int rnd = Utils.randomInt(logger, "scouting", random, 10); if (settlement.hasSpokenToChief()) { // Do nothing if already spoken to. result = "nothing"; } else if (scoutSkill != null && unit.getType().canBeUpgraded(scoutSkill, ChangeType.NATIVES) && ((skill != null && skill.hasAbility(Ability.EXPERT_SCOUT)) || rnd == 0)) { // If the scout can be taught to be an expert it will be. // TODO: in the old code the settlement retains the // teaching ability. WWC1D? unit.setType(scoutSkill); result = "expert"; } else { // Choose tales 1/3 of the time, or if there are no beads. RandomRange gifts = settlement.getType().getGifts(unit); int gold = (gifts == null) ? 0 : gifts.getAmount("Base beads amount", random, true); if (gold <= 0 || rnd <= 3) { radius = Math.max(radius, IndianSettlement.TALES_RADIUS); result = "tales"; } else { if (unit.hasAbility(Ability.EXPERT_SCOUT)) { gold = (gold * 11) / 10; // TODO: magic number } serverPlayer.modifyGold(gold); settlement.getOwner().modifyGold(-gold); result = "beads"; } } // Have now spoken to the chief. csSpeakToChief(serverPlayer, settlement, true, cs); tileDirty = true; // Update settlement tile with new information, and any // newly visible tiles, possibly with enhanced radius. for (Tile t : tile.getSurroundingTiles(radius)) { if (!serverPlayer.canSee(t) && (t.isLand() || t.isCoast())) { serverPlayer.setExplored(t); cs.add(See.only(serverPlayer), t); } } // If the unit was promoted, update it completely, otherwise just // update moves and possibly gold+score. unit.setMovesLeft(0); if ("expert".equals(result)) { cs.add(See.perhaps(), unit); } else { cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); if ("beads".equals(result)) { cs.addPartial(See.only(serverPlayer), serverPlayer, "gold", "score"); } } } if (tileDirty) { tile.updatePlayerExploredTile(serverPlayer, true); cs.add(See.only(serverPlayer), tile); } // Always add result. cs.addAttribute(See.only(serverPlayer), "result", result); // Other players may be able to see unit disappearing, or // learning. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Denounce an existing mission. * * @param serverPlayer The <code>ServerPlayer</code> that is denouncing. * @param unit The <code>Unit</code> denouncing. * @param settlement The <code>IndianSettlement</code> containing the * mission to denounce. * @return An <code>Element</code> encapsulating this action. */ public Element denounceMission(ServerPlayer serverPlayer, Unit unit, IndianSettlement settlement) { ChangeSet cs = new ChangeSet(); csSpeakToChief(serverPlayer, settlement, false, cs); // Determine result Unit missionary = settlement.getMissionary(); if (missionary == null) { return DOMMessage.clientError("Denouncing null missionary"); } ServerPlayer enemy = (ServerPlayer) missionary.getOwner(); double denounce = Utils.randomDouble(logger, "Denounce base", random) * enemy.getImmigration() / (serverPlayer.getImmigration() + 1); if (missionary.hasAbility("model.ability.expertMissionary")) { denounce += 0.2; } if (unit.hasAbility("model.ability.expertMissionary")) { denounce -= 0.2; } if (denounce < 0.5) { // Success, remove old mission and establish ours return establishMission(serverPlayer, unit, settlement); } // Denounce failed Player owner = settlement.getOwner(); cs.add(See.only(serverPlayer), settlement); cs.addMessage(See.only(serverPlayer), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "indianSettlement.mission.noDenounce", serverPlayer, unit) .addStringTemplate("%nation%", owner.getNationName())); cs.addMessage(See.only(enemy), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "indianSettlement.mission.enemyDenounce", enemy, settlement) .addStringTemplate("%enemy%", serverPlayer.getNationName()) .addName("%settlement%", settlement.getNameFor(enemy)) .addStringTemplate("%nation%", owner.getNationName())); cs.add(See.perhaps().always(serverPlayer), (FreeColGameObject) unit.getLocation()); cs.addDispose(See.perhaps().always(serverPlayer), unit.getLocation(), unit); // Others can see missionary disappear sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Establish a new mission. * * @param serverPlayer The <code>ServerPlayer</code> that is establishing. * @param unit The missionary <code>Unit</code>. * @param settlement The <code>IndianSettlement</code> to establish at. * @return An <code>Element</code> encapsulating this action. */ public Element establishMission(ServerPlayer serverPlayer, Unit unit, IndianSettlement settlement) { ChangeSet cs = new ChangeSet(); csSpeakToChief(serverPlayer, settlement, false, cs); Unit missionary = settlement.getMissionary(); if (missionary != null) { ServerPlayer enemy = (ServerPlayer) missionary.getOwner(); enemy.csKillMissionary(settlement, cs); } // Result depends on tension wrt this settlement. // Establish if at least not angry. switch (settlement.getAlarm(serverPlayer).getLevel()) { case HATEFUL: case ANGRY: cs.add(See.perhaps().always(serverPlayer), (FreeColGameObject) unit.getLocation()); cs.addDispose(See.perhaps().always(serverPlayer), unit.getLocation(), unit); break; case HAPPY: case CONTENT: case DISPLEASED: cs.add(See.perhaps().always(serverPlayer), unit.getTile()); unit.setLocation(null); unit.setMovesLeft(0); cs.add(See.only(serverPlayer), unit); settlement.changeMissionary(unit); settlement.setConvertProgress(0); List<FreeColGameObject> modifiedSettlements = ((ServerIndianSettlement)settlement).modifyAlarm(serverPlayer, ALARM_NEW_MISSIONARY); modifiedSettlements.remove(settlement); if (!modifiedSettlements.isEmpty()) { cs.add(See.only(serverPlayer), modifiedSettlements); } break; } Tile tile = settlement.getTile(); tile.updatePlayerExploredTile(serverPlayer, true); cs.add(See.perhaps().always(serverPlayer), tile); String messageId = "indianSettlement.mission." + settlement.getAlarm(serverPlayer).getKey(); cs.addMessage(See.only(serverPlayer), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, messageId, serverPlayer, unit) .addStringTemplate("%nation%", settlement.getOwner().getNationName())); // Others can see missionary disappear and settlement acquire // mission. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Incite a settlement against an enemy. * * @param serverPlayer The <code>ServerPlayer</code> that is inciting. * @param unit The missionary <code>Unit</code> inciting. * @param settlement The <code>IndianSettlement</code> to incite. * @param enemy The <code>Player</code> to be incited against. * @param gold The amount of gold in the bribe. * @return An <code>Element</code> encapsulating this action. */ public Element incite(ServerPlayer serverPlayer, Unit unit, IndianSettlement settlement, Player enemy, int gold) { ChangeSet cs = new ChangeSet(); Tile tile = settlement.getTile(); csSpeakToChief(serverPlayer, settlement, false, cs); tile.updatePlayerExploredTile(serverPlayer, true); cs.add(See.only(serverPlayer), tile); // How much gold will be needed? ServerPlayer enemyPlayer = (ServerPlayer) enemy; Player nativePlayer = settlement.getOwner(); int payingValue = nativePlayer.getTension(serverPlayer).getValue(); int targetValue = nativePlayer.getTension(enemyPlayer).getValue(); int goldToPay = (payingValue > targetValue) ? 10000 : 5000; goldToPay += 20 * (payingValue - targetValue); goldToPay = Math.max(goldToPay, 650); // Try to incite? if (gold < 0) { // Initial enquiry. cs.addAttribute(See.only(serverPlayer), "gold", Integer.toString(goldToPay)); } else if (gold < goldToPay || !serverPlayer.checkGold(gold)) { cs.addMessage(See.only(serverPlayer), new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY, "indianSettlement.inciteGoldFail", serverPlayer, settlement) .addStringTemplate("%player%", enemyPlayer.getNationName()) .addAmount("%amount%", goldToPay)); cs.addAttribute(See.only(serverPlayer), "gold", "0"); unit.setMovesLeft(0); cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); } else { // Success. Raise the tension for the native player with respect // to the European player. Let resulting stance changes happen // naturally in the AI player turn/s. cs.add(See.only(null).perhaps(enemyPlayer), nativePlayer.modifyTension(enemyPlayer, Tension.WAR_MODIFIER)); cs.add(See.only(null).perhaps(serverPlayer), enemyPlayer.modifyTension(serverPlayer, Tension.TENSION_ADD_WAR_INCITER)); cs.addAttribute(See.only(serverPlayer), "gold", Integer.toString(gold)); serverPlayer.modifyGold(-gold); nativePlayer.modifyGold(gold); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); unit.setMovesLeft(0); cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); } // Others might include enemy. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Set a unit destination. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The <code>Unit</code> to set the destination for. * @param destination The <code>Location</code> to set as destination. * @return An <code>Element</code> encapsulating this action. */ public Element setDestination(ServerPlayer serverPlayer, Unit unit, Location destination) { if (unit.getTradeRoute() != null) unit.setTradeRoute(null); unit.setDestination(destination); // Others can not see a destination change. return new ChangeSet().add(See.only(serverPlayer), unit) .build(serverPlayer); } /** * Set current stop of a unit to the next valid stop if any. * * @param serverPlayer The <code>ServerPlayer</code> the unit belongs to. * @param unit The <code>Unit</code> to update. * @return An <code>Element</code> encapsulating this action. */ public Element updateCurrentStop(ServerPlayer serverPlayer, Unit unit) { // Check if there is a valid current stop? int current = unit.validateCurrentStop(); if (current < 0) { // No valid stop unit.setTradeRoute(null); return new ChangeSet().add(See.only(serverPlayer), unit) .build(serverPlayer); } List<Stop> stops = unit.getTradeRoute().getStops(); int next = current; for (;;) { if (++next >= stops.size()) next = 0; if (next == current) return null; // No work at any stop, stay put. Stop nextStop = stops.get(next); if (((ServerUnit) unit).hasWorkAtStop(nextStop)) break; logger.finest("Unit " + unit + " in trade route " + unit.getTradeRoute().getName() + " found no work at stop: " + (FreeColGameObject) nextStop.getLocation()); } // Next is the updated stop. // Could do just a partial update of currentStop if we did not // also need to set the unit destination. unit.setCurrentStop(next); // Others can not see a stop change. return new ChangeSet().add(See.only(serverPlayer), unit) .build(serverPlayer); } /** * Buy from a settlement. * * @param serverPlayer The <code>ServerPlayer</code> that is buying. * @param unit The <code>Unit</code> that will carry the goods. * @param settlement The <code>IndianSettlement</code> to buy from. * @param goods The <code>Goods</code> to buy. * @param amount How much gold to pay. * @return An <code>Element</code> encapsulating this action. */ public Element buyFromSettlement(ServerPlayer serverPlayer, Unit unit, IndianSettlement settlement, Goods goods, int amount) { ChangeSet cs = new ChangeSet(); csSpeakToChief(serverPlayer, settlement, false, cs); TradeSession session = TradeSession.lookup(TradeSession.class, unit, settlement); if (session == null) { return DOMMessage.clientError("Trying to buy without opening a transaction session"); } if (!session.getBuy()) { return DOMMessage.clientError("Trying to buy in a session where buying is not allowed."); } if (unit.getSpaceLeft() <= 0) { return DOMMessage.clientError("Unit is full, unable to buy."); } // Check that this is the agreement that was made AIPlayer ai = getFreeColServer().getAIPlayer(settlement.getOwner()); int returnGold = ai.buyProposition(unit, settlement, goods, amount); if (returnGold != amount) { return DOMMessage.clientError("This was not the price we agreed upon! Cheater?"); } if (!serverPlayer.checkGold(amount)) { // Check this is funded. return DOMMessage.clientError("Insufficient gold to buy."); } // Valid, make the trade. moveGoods(goods, unit); cs.add(See.perhaps(), unit); Player settlementPlayer = settlement.getOwner(); Tile tile = settlement.getTile(); settlement.updateWantedGoods(); settlementPlayer.modifyGold(amount); serverPlayer.modifyGold(-amount); cs.add(See.only(serverPlayer), ((ServerIndianSettlement)settlement).modifyAlarm(serverPlayer, -amount / 50)); tile.updatePlayerExploredTile(serverPlayer, true); cs.add(See.only(serverPlayer), tile); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); session.setBuy(); logger.finest(serverPlayer.getName() + " " + unit + " buys " + goods + " at " + settlement.getName() + " for " + amount); // Others can see the unit capacity. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Sell to a settlement. * * @param serverPlayer The <code>ServerPlayer</code> that is selling. * @param unit The <code>Unit</code> carrying the goods. * @param settlement The <code>IndianSettlement</code> to sell to. * @param goods The <code>Goods</code> to sell. * @param amount How much gold to expect. * @return An <code>Element</code> encapsulating this action. */ public Element sellToSettlement(ServerPlayer serverPlayer, Unit unit, IndianSettlement settlement, Goods goods, int amount) { ChangeSet cs = new ChangeSet(); csSpeakToChief(serverPlayer, settlement, false, cs); TradeSession session = TransactionSession.lookup(TradeSession.class, unit, settlement); if (session == null) { return DOMMessage.clientError("Trying to sell without opening a transaction session"); } if (!session.getSell()) { return DOMMessage.clientError("Trying to sell in a session where selling is not allowed."); } // Check that the gold is the agreed amount AIPlayer ai = getFreeColServer().getAIPlayer(settlement.getOwner()); int returnGold = ai.sellProposition(unit, settlement, goods, amount); if (returnGold != amount) { return DOMMessage.clientError("This was not the price we agreed upon! Cheater?"); } // Valid, make the trade. moveGoods(goods, settlement); cs.add(See.perhaps(), unit); Player settlementPlayer = settlement.getOwner(); settlementPlayer.modifyGold(-amount); serverPlayer.modifyGold(amount); cs.add(See.only(serverPlayer), ((ServerIndianSettlement)settlement).modifyAlarm(serverPlayer, -amount / 500)); Tile tile = settlement.getTile(); settlement.updateWantedGoods(); tile.updatePlayerExploredTile(serverPlayer, true); cs.add(See.only(serverPlayer), tile); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); session.setSell(); cs.addSale(serverPlayer, settlement, goods.getType(), (int) Math.round((float) amount / goods.getAmount())); logger.finest(serverPlayer.getName() + " " + unit + " sells " + goods + " at " + settlement.getName() + " for " + amount); // Others can see the unit capacity. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Deliver gift to settlement. * Note that this includes both European and native gifts. * * @param serverPlayer The <code>ServerPlayer</code> that is delivering. * @param unit The <code>Unit</code> that is delivering. * @param goods The <code>Goods</code> to deliver. * @return An <code>Element</code> encapsulating this action. */ public Element deliverGiftToSettlement(ServerPlayer serverPlayer, Unit unit, Settlement settlement, Goods goods) { TradeSession session = TransactionSession.lookup(TradeSession.class, unit, settlement); if (session == null) { return DOMMessage.clientError("Trying to deliver gift without opening a session"); } if (!session.getGift()) { return DOMMessage.clientError("Trying to deliver gift in a session where gift giving is not allowed: " + unit + " " + settlement + " " + session); } ChangeSet cs = new ChangeSet(); Tile tile = settlement.getTile(); moveGoods(goods, settlement); cs.add(See.perhaps(), unit); if (settlement instanceof IndianSettlement) { IndianSettlement is = (IndianSettlement) settlement; csSpeakToChief(serverPlayer, is, false, cs); cs.add(See.only(serverPlayer), ((ServerIndianSettlement)is).modifyAlarm(serverPlayer, -is.getPriceToBuy(goods) / 50)); is.updateWantedGoods(); tile.updatePlayerExploredTile(serverPlayer, true); cs.add(See.only(serverPlayer), tile); } session.setGift(); // Inform the receiver of the gift. ModelMessage m = new ModelMessage(ModelMessage.MessageType.GIFT_GOODS, "model.unit.gift", settlement, goods.getType()) .addStringTemplate("%player%", serverPlayer.getNationName()) .add("%type%", goods.getNameKey()) .addAmount("%amount%", goods.getAmount()) .addName("%settlement%", settlement.getName()); cs.addMessage(See.only(serverPlayer), m); ServerPlayer receiver = (ServerPlayer) settlement.getOwner(); if (receiver.isConnected() && settlement instanceof Colony) { cs.add(See.only(receiver), unit); cs.add(See.only(receiver), settlement); cs.addMessage(See.only(receiver), m); } logger.info("Gift delivered by unit: " + unit.getId() + " to settlement: " + settlement.getName()); // Others can see unit capacity, receiver gets it own items. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Load cargo. * * @param serverPlayer The <code>ServerPlayer</code> that is loading. * @param unit The <code>Unit</code> to load. * @param goods The <code>Goods</code> to load. * @return An <code>Element</code> encapsulating this action. */ public Element loadCargo(ServerPlayer serverPlayer, Unit unit, Goods goods) { ChangeSet cs = new ChangeSet(); Location oldLocation = goods.getLocation(); goods.adjustAmount(); moveGoods(goods, unit); boolean moved = false; if (unit.getInitialMovesLeft() != unit.getMovesLeft()) { unit.setMovesLeft(0); moved = true; } Unit oldUnit = null; if (oldLocation instanceof Unit) { oldUnit = (Unit) oldLocation; if (oldUnit.getInitialMovesLeft() != oldUnit.getMovesLeft()) { oldUnit.setMovesLeft(0); } else { oldUnit = null; } } // Update the goodsContainers only if within a settlement, // otherwise update the shared location so that others can // see capacity changes. if (unit.getSettlement() != null) { cs.add(See.only(serverPlayer), oldLocation.getGoodsContainer()); cs.add(See.only(serverPlayer), unit.getGoodsContainer()); if (moved) { cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); } if (oldUnit != null) { cs.addPartial(See.only(serverPlayer), oldUnit, "movesLeft"); } } else { cs.add(See.perhaps(), (FreeColGameObject) unit.getLocation()); } // Others might see capacity change. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Unload cargo. * * @param serverPlayer The <code>ServerPlayer</code> that is unloading. * @param unit The <code>Unit</code> to unload. * @param goods The <code>Goods</code> to unload. * @return An <code>Element</code> encapsulating this action. */ public Element unloadCargo(ServerPlayer serverPlayer, Unit unit, Goods goods) { ChangeSet cs = new ChangeSet(); Location loc; Settlement settlement = null; if (unit.isInEurope()) { // Must be a dump of boycotted goods loc = null; } else if (unit.getTile() == null) { return DOMMessage.clientError("Unit not on the map."); } else if (unit.getSettlement() != null) { settlement = unit.getTile().getSettlement(); loc = settlement; } else { // Dump of goods onto a tile loc = null; } goods.adjustAmount(); moveGoods(goods, loc); boolean moved = false; if (unit.getInitialMovesLeft() != unit.getMovesLeft()) { unit.setMovesLeft(0); moved = true; } if (settlement != null) { cs.add(See.only(serverPlayer), settlement.getGoodsContainer()); cs.add(See.only(serverPlayer), unit.getGoodsContainer()); if (moved) cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); } else { cs.add(See.perhaps(), (FreeColGameObject) unit.getLocation()); } // Others might see a capacity change. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Clear the specialty of a unit. * * @param serverPlayer The owner of the unit. * @param unit The <code>Unit</code> to clear the speciality of. * @return An <code>Element</code> encapsulating this action. */ public Element clearSpeciality(ServerPlayer serverPlayer, Unit unit) { UnitType newType = unit.getTypeChange(ChangeType.CLEAR_SKILL, serverPlayer); if (newType == null) { return DOMMessage.clientError("Can not clear unit speciality: " + unit.getId()); } // There can be some restrictions that may prevent the // clearing of the speciality. AFAICT the only ATM is that a // teacher can not lose its speciality, but this will need to // be revisited if we invent a work location that requires a // particular unit type. if (unit.getStudent() != null) { return DOMMessage.clientError("Can not clear speciality of a teacher."); } // Valid, change type. unit.setType(newType); // Update just the unit, others can not see it as this only happens // in-colony. TODO: why not clear speciality in the open, // you can disband... return new ChangeSet().add(See.only(serverPlayer), unit) .build(serverPlayer); } /** * Disband a unit. * * @param serverPlayer The owner of the unit. * @param unit The <code>Unit</code> to disband. * @return An <code>Element</code> encapsulating this action. */ public Element disbandUnit(ServerPlayer serverPlayer, Unit unit) { ChangeSet cs = new ChangeSet(); // Dispose of the unit. cs.add(See.perhaps().always(serverPlayer), (FreeColGameObject) unit.getLocation()); cs.addDispose(See.perhaps().always(serverPlayer), unit.getLocation(), unit); // Others can see the unit removal and the space it leaves. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Build a settlement. * * @param serverPlayer The <code>ServerPlayer</code> that is building. * @param unit The <code>Unit</code> that is building. * @param name The new settlement name. * @return An <code>Element</code> encapsulating this action. */ public Element buildSettlement(ServerPlayer serverPlayer, Unit unit, String name) { ChangeSet cs = new ChangeSet(); Game game = serverPlayer.getGame(); // Build settlement Tile tile = unit.getTile(); Settlement settlement; if (Player.ASSIGN_SETTLEMENT_NAME.equals(name)) { name = serverPlayer.getSettlementName(); if (Player.ASSIGN_SETTLEMENT_NAME.equals(name)) { // Load settlement names on demand. serverPlayer.installSettlementNames(Messages .getSettlementNames(serverPlayer), random); name = serverPlayer.getSettlementName(); } } if (serverPlayer.isEuropean()) { settlement = new ServerColony(game, serverPlayer, name, tile); serverPlayer.addSettlement(settlement); settlement.placeSettlement(serverPlayer.isAI()); } else { IndianNationType nationType = (IndianNationType) serverPlayer.getNationType(); UnitType skill = RandomChoice.getWeightedRandom(logger, "Choose skill", random, nationType.generateSkillsForTile(tile)); if (skill == null) { // Seasoned Scout List<UnitType> scouts = getGame().getSpecification() .getUnitTypesWithAbility(Ability.EXPERT_SCOUT); skill = Utils.getRandomMember(logger, "Choose scout", scouts, random); } settlement = new ServerIndianSettlement(game, serverPlayer, name, tile, false, skill, new HashSet<Player>(), null); serverPlayer.addSettlement(settlement); settlement.placeSettlement(true); // TODO: its lame that the settlement starts with no contacts } // Join. Remove equipment first in case role confuses placement. ((ServerUnit)unit).csRemoveEquipment(settlement, new HashSet<EquipmentType>(unit.getEquipment().keySet()), 0, random, cs); unit.setLocation(settlement); unit.setMovesLeft(0); // Update with settlement tile, and newly owned tiles. List<FreeColGameObject> tiles = new ArrayList<FreeColGameObject>(); tiles.addAll(settlement.getOwnedTiles()); cs.add(See.perhaps(), tiles); cs.addHistory(serverPlayer, new HistoryEvent(game.getTurn(), HistoryEvent.EventType.FOUND_COLONY) .addName("%colony%", settlement.getName())); // Also send any tiles that can now be seen because the colony // can perhaps see further than the founding unit. if (settlement.getLineOfSight() > unit.getLineOfSight()) { tiles.clear(); for (Tile t : tile.getSurroundingTiles(unit.getLineOfSight()+1, settlement.getLineOfSight())) { if (!tiles.contains(t)) tiles.add(t); } cs.add(See.only(serverPlayer), tiles); } // Others can see tile changes. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Join a colony. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The <code>Unit</code> that is joining. * @param colony The <code>Colony</code> to join. * @return An <code>Element</code> encapsulating this action. */ public Element joinColony(ServerPlayer serverPlayer, Unit unit, Colony colony) { ChangeSet cs = new ChangeSet(); List<Tile> ownedTiles = colony.getOwnedTiles(); Tile tile = colony.getTile(); // Join. unit.setLocation(colony); unit.setMovesLeft(0); ((ServerUnit)unit).csRemoveEquipment(colony, new HashSet<EquipmentType>(unit.getEquipment().keySet()), 0, random, cs); // Update with colony tile, and tiles now owned. cs.add(See.only(serverPlayer), tile); for (Tile t : tile.getSurroundingTiles(colony.getRadius())) { if (t.getOwningSettlement() == colony && !ownedTiles.contains(t)) { cs.add(See.perhaps(), t); } } // Others might see a tile ownership change. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Abandon a settlement. * * @param serverPlayer The <code>ServerPlayer</code> that is abandoning. * @param settlement The <code>Settlement</code> to abandon. * @return An <code>Element</code> encapsulating this action. */ public Element abandonSettlement(ServerPlayer serverPlayer, Settlement settlement) { ChangeSet cs = new ChangeSet(); // Collect the tiles the settlement owns before disposing, // except the center tile as that is in the dispose below. for (Tile t : settlement.getOwnedTiles()) { if (t != settlement.getTile()) cs.add(See.perhaps(), t); } // Create history event before disposing. if (settlement instanceof Colony) { cs.addHistory(serverPlayer, new HistoryEvent(getGame().getTurn(), HistoryEvent.EventType.ABANDON_COLONY) .addName("%colony%", settlement.getName())); } // Now do the dispose. cs.add(See.perhaps().always(serverPlayer), settlement.getTile()); cs.addDispose(See.perhaps().always(serverPlayer), settlement.getTile(), settlement); // TODO: Player.settlements is still being fixed on the client side. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Claim land. * * @param serverPlayer The <code>ServerPlayer</code> claiming. * @param tile The <code>Tile</code> to claim. * @param settlement The <code>Settlement</code> to claim for. * @param price The price to pay for the land, which must agree * with the owner valuation, unless negative which denotes stealing. * @return An <code>Element</code> encapsulating this action. */ public Element claimLand(ServerPlayer serverPlayer, Tile tile, Settlement settlement, int price) { ChangeSet cs = new ChangeSet(); serverPlayer.csClaimLand(tile, settlement, price, cs); // Others can see the tile. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Accept a diplomatic trade. Handles the transfers of TradeItems. * * @param unit The <code>Unit</code> that is trading. * @param settlement The <code>Settlement</code> to trade with. * @param agreement The <code>DiplomacyTrade</code> agreement. * @param cs A <code>ChangeSet</code> to update. */ private void csAcceptTrade(Unit unit, Settlement settlement, DiplomaticTrade agreement, ChangeSet cs) { ServerPlayer srcPlayer = (ServerPlayer) agreement.getSender(); ServerPlayer dstPlayer = (ServerPlayer) agreement.getRecipient(); for (TradeItem tradeItem : agreement.getTradeItems()) { // Check trade carefully before committing. if (!tradeItem.isValid()) { logger.warning("Trade with invalid tradeItem: " + tradeItem.toString()); continue; } ServerPlayer source = (ServerPlayer) tradeItem.getSource(); if (source != srcPlayer && source != dstPlayer) { logger.warning("Trade with invalid source: " + ((source == null) ? "null" : source.getId())); continue; } ServerPlayer dest = (ServerPlayer) tradeItem.getDestination(); if (dest != srcPlayer && dest != dstPlayer) { logger.warning("Trade with invalid destination: " + ((dest == null) ? "null" : dest.getId())); continue; } // Collect changes for updating. Not very OO but // TradeItem should not know about server internals. // Take care to show items that change hands to the *old* // owner too. Stance stance = tradeItem.getStance(); if (stance != null && !source.csChangeStance(stance, dest, true, cs)) { logger.warning("Stance trade failure"); } Colony colony = tradeItem.getColony(); if (colony != null) { ServerPlayer former = (ServerPlayer) colony.getOwner(); colony.changeOwner(dest); List<FreeColGameObject> tiles = new ArrayList<FreeColGameObject>(); tiles.addAll(colony.getOwnedTiles()); cs.add(See.perhaps().always(former), tiles); } int gold = tradeItem.getGold(); if (gold > 0) { source.modifyGold(-gold); dest.modifyGold(gold); cs.addPartial(See.only(source), source, "gold", "score"); cs.addPartial(See.only(dest), dest, "gold", "score"); } Goods goods = tradeItem.getGoods(); if (goods != null) { moveGoods(goods, settlement); cs.add(See.only(source), unit); cs.add(See.only(dest), settlement.getGoodsContainer()); } Unit newUnit = tradeItem.getUnit(); if (newUnit != null) { ServerPlayer former = (ServerPlayer) newUnit.getOwner(); unit.setOwner(dest); cs.add(See.perhaps().always(former), newUnit); } } } /** * Diplomatic trades. * Note that when an agreement is accepted we always process the * agreement that was sent, not what was returned, cutting off a * possibility for cheating. * * @param serverPlayer The <code>ServerPlayer</code> that is trading. * @param unit The <code>Unit</code> that is trading. * @param settlement The <code>Settlement</code> to trade with. * @param agreement The <code>DiplomaticTrade</code> to consider. * @return An <code>Element</code> encapsulating this action. */ public Element diplomaticTrade(ServerPlayer serverPlayer, Unit unit, Settlement settlement, DiplomaticTrade agreement) { ChangeSet cs = new ChangeSet(); ServerPlayer otherPlayer = (ServerPlayer) settlement.getOwner(); DiplomacySession session = TransactionSession.lookup(DiplomacySession.class, unit, settlement); TradeStatus status; Player.makeContact(serverPlayer, otherPlayer); switch (status = agreement.getStatus()) { case PROPOSE_TRADE: if (session == null) { Unit.MoveType type = unit.getMoveType(settlement.getTile()); if (type != Unit.MoveType.ENTER_FOREIGN_COLONY_WITH_SCOUT) { return DOMMessage.clientError("Unable to enter " + settlement.getId() + ": " + type.whyIllegal()); } session = new DiplomacySession(unit, settlement); unit.setMovesLeft(0); cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); } session.setAgreement(agreement); break; case ACCEPT_TRADE: if (session == null) { return DOMMessage.clientError("Accept-trade with no session"); } agreement = session.getAgreement(); agreement.setStatus(status); csAcceptTrade(unit, settlement, agreement, cs); break; case REJECT_TRADE: if (session == null) { return DOMMessage.clientError("Reject-trade with no session"); } agreement = session.getAgreement(); agreement.setStatus(status); break; default: return DOMMessage.clientError("Bogus trade status: " + status); } DOMMessage reply = askTimeout(otherPlayer, new DiplomacyMessage(unit, settlement, agreement)); DiplomaticTrade theirAgreement = (reply instanceof DiplomacyMessage) ? ((DiplomacyMessage)reply).getAgreement() : null; if (status != TradeStatus.PROPOSE_TRADE) { session.complete(cs); sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } status = (theirAgreement == null) ? TradeStatus.REJECT_TRADE : theirAgreement.getStatus(); switch (status) { case PROPOSE_TRADE: session.setAgreement(agreement = theirAgreement); break; case ACCEPT_TRADE: agreement.setStatus(status); csAcceptTrade(unit, settlement, agreement, cs); session.complete(cs); break; case REJECT_TRADE: agreement.setStatus(status); session.complete(cs); break; default: logger.warning("Bogus trade status: " + status); break; } // Update *everyone* with the result, *and* return a // DiplomacyMessage to the originating player because that is // what ServerAPI.askDiplomacy is expecting. sendToAll(cs); return new ChangeSet() .add(See.only(serverPlayer), ChangePriority.CHANGE_LATE, new DiplomacyMessage(unit, settlement, agreement)) .build(serverPlayer); } /** * Spy on a settlement. * * @param serverPlayer The <code>ServerPlayer</code> that is spying. * @param unit The <code>Unit</code> that is spying. * @param settlement The <code>Settlement</code> to spy on. * @return An <code>Element</code> encapsulating this action. */ public Element spySettlement(ServerPlayer serverPlayer, Unit unit, Settlement settlement) { ChangeSet cs = new ChangeSet(); cs.addSpy(See.only(serverPlayer), settlement); unit.setMovesLeft(0); cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); return cs.build(serverPlayer); } /** * Change work location. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The <code>Unit</code> to change the work location of. * @param workLocation The <code>WorkLocation</code> to change to. * @return An <code>Element</code> encapsulating this action. */ public Element work(ServerPlayer serverPlayer, Unit unit, WorkLocation workLocation) { ChangeSet cs = new ChangeSet(); Colony colony = workLocation.getColony(); colony.getGoodsContainer().saveState(); if (workLocation instanceof ColonyTile) { Tile tile = ((ColonyTile) workLocation).getWorkTile(); if (tile.getOwningSettlement() != colony) { // Claim known free land (because canAdd() succeeded). serverPlayer.csClaimLand(tile, colony, 0, cs); } } // Remove any unit equipment if (!unit.getEquipment().isEmpty()) { ((ServerUnit)unit).csRemoveEquipment(colony, new HashSet<EquipmentType>(unit.getEquipment().keySet()), 0, random, cs); } // Check for upgrade. UnitType oldType = unit.getType(); UnitTypeChange change = oldType .getUnitTypeChange(ChangeType.ENTER_COLONY, unit.getOwner()); if (change != null) { unit.setType(change.getNewUnitType()); } // Change the location. // We could avoid updating the whole tile if we knew that this // was definitely a move between locations and no student/teacher // interaction occurred. unit.setLocation(workLocation); cs.add(See.perhaps(), colony.getTile()); // Others can see colony change size sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Loot cargo. * * Note loser is passed by id, as by the time we get here the unit * may have been sunk. * * @param serverPlayer The <code>ServerPlayer</code> that owns the winner. * @param winner The <code>Unit</code> that looting. * @param loserId The id of the <code>Unit</code> that is looted. * @param loot The <code>Goods</code> to loot. * @return An <code>Element</code> encapsulating this action. */ public Element lootCargo(ServerPlayer serverPlayer, Unit winner, String loserId, List<Goods> loot) { LootSession session = TransactionSession.lookup(LootSession.class, winner.getId(), loserId); if (session == null) { return DOMMessage.clientError("Bogus looting!"); } if (winner.getSpaceLeft() == 0) { return DOMMessage.clientError("No space to loot to: " + winner.getId()); } ChangeSet cs = new ChangeSet(); List<Goods> available = session.getCapture(); if (loot == null) { // Initial inquiry cs.add(See.only(serverPlayer), ChangePriority.CHANGE_LATE, new LootCargoMessage(winner, loserId, available)); } else { for (Goods g : loot) { if (!available.contains(g)) { return DOMMessage.clientError("Invalid loot: " + g.toString()); } available.remove(g); if (!winner.canAdd(g)) { return DOMMessage.clientError("Loot failed: " + g.toString()); } winner.add(g); } // Others can see cargo capacity change. session.complete(cs); cs.add(See.perhaps(), winner); sendToOthers(serverPlayer, cs); } return cs.build(serverPlayer); } /** * Pay arrears. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param type The <code>GoodsType</code> to pay the arrears for. * @return An <code>Element</code> encapsulating this action. */ public Element payArrears(ServerPlayer serverPlayer, GoodsType type) { int arrears = serverPlayer.getArrears(type); if (arrears <= 0) { return DOMMessage.clientError("No arrears for pay for: " + type.getId()); } else if (!serverPlayer.checkGold(arrears)) { return DOMMessage.clientError("Not enough gold to pay arrears for: " + type.getId()); } ChangeSet cs = new ChangeSet(); Market market = serverPlayer.getMarket(); serverPlayer.modifyGold(-arrears); market.setArrears(type, 0); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); cs.add(See.only(serverPlayer), market.getMarketData(type)); // Arrears payment is private. return cs.build(serverPlayer); } /** * Equip a unit. * Currently the unit is either in Europe or in a settlement. * Might one day allow the unit to be on a tile co-located with * an equipment-bearing wagon. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The <code>Unit</code> to equip. * @param type The <code>EquipmentType</code> to equip with. * @param amount The change in the amount of equipment. * @return An <code>Element</code> encapsulating this action. */ public Element equipUnit(ServerPlayer serverPlayer, Unit unit, EquipmentType type, int amount) { Settlement settlement = (unit.getTile() == null) ? null : unit.getSettlement(); GoodsContainer container = null; boolean tileDirty = false; if (unit.isInEurope()) { // Refuse to trade in boycotted goods for (AbstractGoods goods : type.getGoodsRequired()) { GoodsType goodsType = goods.getType(); if (!serverPlayer.canTrade(goodsType)) { return DOMMessage.clientError("No equip of " + type.getId() + " due to boycott of " + goodsType.getId()); } } // Will need a fake container to contain the goods to buy // in Europe. Units may not necessarily have one. container = new GoodsContainer(getGame(), serverPlayer.getEurope()); } else if (settlement != null) { // Equipping a unit at work in a colony should remove the unit // from the work location. if (unit.getLocation() instanceof WorkLocation) { unit.setLocation(settlement.getTile()); tileDirty = true; } settlement.getGoodsContainer().saveState(); } ChangeSet cs = new ChangeSet(); List<EquipmentType> remove = null; // Process adding equipment first, so as to settle what has to // be removed. if (amount > 0) { for (AbstractGoods goods : type.getGoodsRequired()) { GoodsType goodsType = goods.getType(); int n = amount * goods.getAmount(); if (unit.isInEurope()) { try { serverPlayer.buy(container, goodsType, n, random); serverPlayer.csFlushMarket(goodsType, cs); } catch (IllegalStateException e) { return DOMMessage.clientError(e.getMessage()); } } else if (settlement != null) { if (settlement.getGoodsCount(goodsType) < n) { return DOMMessage.clientError("Failed to equip: " + unit.getId() + " not enough " + goodsType + " in settlement " + settlement.getId()); } settlement.removeGoods(goodsType, n); } } remove = unit.changeEquipment(type, amount); amount = 0; // 0 => all, now } else if (amount < 0) { remove = new ArrayList<EquipmentType>(); remove.add(type); amount = -amount; } else { return null; // Nothing to do. } // Now do removal of equipment. ((ServerUnit)unit).csRemoveEquipment(settlement, remove, amount, random, cs); // Nothing for others to see except if the settlement population // changes. // If in Europe, we can get away with just updating the unit // as sell() will have added sales changes. In a settlement, // the goods container will always be dirty, but the whole tile // will only need to be updated if the unit moved into it. if (unit.getInitialMovesLeft() != unit.getMovesLeft()) { unit.setMovesLeft(0); } if (unit.isInEurope()) { cs.add(See.only(serverPlayer), unit); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); } else if (settlement != null) { Unit carrier = unit.getCarrier(); if (carrier != null && carrier.getInitialMovesLeft() != carrier.getMovesLeft() && carrier.getMovesLeft() != 0) { carrier.setMovesLeft(0); cs.add(See.only(serverPlayer), carrier); } if (tileDirty) { cs.add(See.perhaps(), settlement.getTile()); } else { cs.add(See.only(serverPlayer), unit, settlement.getGoodsContainer()); } } return cs.build(serverPlayer); } /** * Pay for a building. * * @param serverPlayer The <code>ServerPlayer</code> that owns the colony. * @param colony The <code>Colony</code> that is building. * @return An <code>Element</code> encapsulating this action. */ public Element payForBuilding(ServerPlayer serverPlayer, Colony colony) { BuildableType build = colony.getCurrentlyBuilding(); if (build == null) { return DOMMessage.clientError("Colony " + colony.getId() + " is not building anything!"); } HashMap<GoodsType, Integer> required = colony.getGoodsForBuilding(build); int price = colony.priceGoodsForBuilding(required); if (!serverPlayer.checkGold(price)) { return DOMMessage.clientError("Insufficient funds to pay for build."); } // Save the correct final gold for the player, as we are going to // use buy() below, but it deducts the normal uninflated price for // the goods being bought. We restore this correct amount later. int savedGold = serverPlayer.modifyGold(-price); serverPlayer.modifyGold(price); ChangeSet cs = new ChangeSet(); GoodsContainer container = colony.getGoodsContainer(); container.saveState(); for (GoodsType type : required.keySet()) { int amount = required.get(type); if (type.isStorable()) { // TODO: should also check canTrade(type, Access.?) serverPlayer.buy(container, type, amount, random); serverPlayer.csFlushMarket(type, cs); } else { container.addGoods(type, amount); } } colony.invalidateCache(); // Nothing to see for others, colony internal. serverPlayer.setGold(savedGold); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); cs.add(See.only(serverPlayer), container); return cs.build(serverPlayer); } /** * Indians making demands of a colony. * * @param serverPlayer The <code>ServerPlayer</code> that is demanding. * @param unit The <code>Unit</code> making the demands. * @param colony The <code>Colony</code> that is demanded of. * @param goods The <code>Goods</code> being demanded. * @param gold The amount of gold being demanded. * @return An <code>Element</code> encapsulating this action. */ public Element indianDemand(final ServerPlayer serverPlayer, Unit unit, Colony colony, Goods goods, int gold) { ServerPlayer victim = (ServerPlayer) colony.getOwner(); int difficulty = getGame().getSpecification() .getIntegerOption("model.option.nativeDemands").getValue(); ChangeSet cs = new ChangeSet(); DOMMessage reply = askTimeout(victim, new IndianDemandMessage(unit, colony, goods, gold)); boolean result = (reply instanceof IndianDemandMessage) ? ((IndianDemandMessage)reply).getResult() : false; logger.info(serverPlayer.getName() + " unit " + unit + " demands " + goods + " goods and " + gold + " gold " + " from " + colony.getName() + " accepted: " + result); IndianDemandMessage message = new IndianDemandMessage(unit, colony, goods, gold); message.setResult(result); cs.add(See.only(serverPlayer), ChangePriority.CHANGE_NORMAL, message); if (result) { if (goods != null) { GoodsContainer colonyContainer = colony.getGoodsContainer(); colonyContainer.saveState(); GoodsContainer unitContainer = unit.getGoodsContainer(); unitContainer.saveState(); moveGoods(goods, unit); cs.add(See.only(victim), colonyContainer); //cs.add(See.only(serverPlayer), unitContainer); } if (gold > 0) { victim.modifyGold(-gold); serverPlayer.modifyGold(gold); cs.addPartial(See.only(victim), victim, "gold"); //cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); } cs.add(See.only(null).perhaps(victim), serverPlayer.modifyTension(victim, -(5 - difficulty) * 50)); } sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Train a unit in Europe. * * @param serverPlayer The <code>ServerPlayer</code> that is demanding. * @param type The <code>UnitType</code> to train. * @return An <code>Element</code> encapsulating this action. */ public Element trainUnitInEurope(ServerPlayer serverPlayer, UnitType type) { Europe europe = serverPlayer.getEurope(); if (europe == null) { return DOMMessage.clientError("No Europe to train in."); } int price = europe.getUnitPrice(type); if (price <= 0) { return DOMMessage.clientError("Bogus price: " + price); } else if (!serverPlayer.checkGold(price)) { return DOMMessage.clientError("Not enough gold to train " + type); } new ServerUnit(getGame(), europe, serverPlayer, type); serverPlayer.modifyGold(-price); ((ServerEurope) europe).increasePrice(type, price); // Only visible in Europe ChangeSet cs = new ChangeSet(); cs.addPartial(See.only(serverPlayer), serverPlayer, "gold"); cs.add(See.only(serverPlayer), europe); return cs.build(serverPlayer); } /** * Set build queue. * * @param serverPlayer The <code>ServerPlayer</code> that owns the colony. * @param colony The <code>Colony</code> to set the queue of. * @param queue The new build queue. * @return An <code>Element</code> encapsulating this action. */ public Element setBuildQueue(ServerPlayer serverPlayer, Colony colony, List<BuildableType> queue) { colony.setBuildQueue(queue); // Only visible to player. ChangeSet cs = new ChangeSet(); cs.add(See.only(serverPlayer), colony); return cs.build(serverPlayer); } /** * Set goods levels. * * @param serverPlayer The <code>ServerPlayer</code> that owns the colony. * @param colony The <code>Colony</code> to set the goods levels in. * @param exportData The new <code>ExportData</code>. * @return An <code>Element</code> encapsulating this action. */ public Element setGoodsLevels(ServerPlayer serverPlayer, Colony colony, ExportData exportData) { colony.setExportData(exportData); return new ChangeSet().add(See.only(serverPlayer), colony) .build(serverPlayer); } /** * Put outside colony. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The <code>Unit</code> to be put out. * @return An <code>Element</code> encapsulating this action. */ public Element putOutsideColony(ServerPlayer serverPlayer, Unit unit) { Tile tile = unit.getTile(); Colony colony = unit.getColony(); unit.setLocation(tile); // Full tile update for the player, the rest get their limited // view of the colony so that population changes. ChangeSet cs = new ChangeSet(); cs.add(See.only(serverPlayer), tile); cs.add(See.perhaps().except(serverPlayer), colony); return cs.build(serverPlayer); } /** * Change work type. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The <code>Unit</code> to change the work type of. * @param type The new <code>GoodsType</code> to produce. * @return An <code>Element</code> encapsulating this action. */ public Element changeWorkType(ServerPlayer serverPlayer, Unit unit, GoodsType type) { if (unit.getWorkType() != type) { unit.setExperience(0); unit.setWorkType(type); } // Private update of the unit. return new ChangeSet().add(See.only(serverPlayer), unit) .build(serverPlayer); } /** * Change improvement work type. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The <code>Unit</code> to change the work type of. * @param type The new <code>TileImprovementType</code> to produce. * @return An <code>Element</code> encapsulating this action. */ public Element changeWorkImprovementType(ServerPlayer serverPlayer, Unit unit, TileImprovementType type) { Tile tile = unit.getTile(); TileImprovement improvement = tile.findTileImprovementType(type); if (improvement == null) { // Create the new improvement. improvement = new TileImprovement(getGame(), tile, type); tile.add(improvement); } unit.setWorkImprovement(improvement); unit.setState(UnitState.IMPROVING); // Private update of the tile. return new ChangeSet().add(See.only(serverPlayer), tile) .build(serverPlayer); } /** * Change a units state. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The <code>Unit</code> to change the state of. * @param state The new <code>UnitState</code>. * @return An <code>Element</code> encapsulating this action. */ public Element changeState(ServerPlayer serverPlayer, Unit unit, UnitState state) { ChangeSet cs = new ChangeSet(); if (state == UnitState.FORTIFYING) { Tile tile = unit.getTile(); ServerColony colony = (tile.getOwningSettlement() instanceof Colony) ? (ServerColony) tile.getOwningSettlement() : null; if (colony != null && colony.getOwner() != unit.getOwner() && colony.isTileInUse(tile)) { colony.csEvictUser(unit, cs); } } unit.setState(state); cs.add(See.perhaps(), unit.getTile()); // Others might be able to see the unit. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } /** * Assign a student to a teacher. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param student The student <code>Unit</code>. * @param teacher The teacher <code>Unit</code>. * @return An <code>Element</code> encapsulating this action. */ public Element assignTeacher(ServerPlayer serverPlayer, Unit student, Unit teacher) { Unit oldStudent = teacher.getStudent(); Unit oldTeacher = student.getTeacher(); // Only update units that changed their teaching situation. ChangeSet cs = new ChangeSet(); if (oldTeacher != null) { oldTeacher.setStudent(null); cs.add(See.only(serverPlayer), oldTeacher); } if (oldStudent != null) { oldStudent.setTeacher(null); cs.add(See.only(serverPlayer), oldStudent); } teacher.setStudent(student); teacher.setWorkType(null); student.setTeacher(teacher); cs.add(See.only(serverPlayer), student, teacher); return cs.build(serverPlayer); } /** * Assign a trade route to a unit. * * @param serverPlayer The <code>ServerPlayer</code> that owns the unit. * @param unit The unit <code>Unit</code> to assign to. * @param tradeRoute The <code>TradeRoute</code> to assign. * @return An <code>Element</code> encapsulating this action. */ public Element assignTradeRoute(ServerPlayer serverPlayer, Unit unit, TradeRoute tradeRoute) { unit.setTradeRoute(tradeRoute); unit.setDestination(null); if (tradeRoute != null) { List<Stop> stops = tradeRoute.getStops(); int found = -1; for (int i = 0; i < stops.size(); i++) { if (unit.getLocation() == stops.get(i).getLocation()) { found = i; break; } } if (found < 0) found = 0; unit.setCurrentStop(found); } // Only visible to the player return new ChangeSet().add(See.only(serverPlayer), unit) .build(serverPlayer); } /** * Set trade routes for a player. * * @param serverPlayer The <code>ServerPlayer</code> to set trade * routes for. * @param routes The new list of <code>TradeRoute</code>s. * @return An <code>Element</code> encapsulating this action. */ public Element setTradeRoutes(ServerPlayer serverPlayer, List<TradeRoute> routes) { serverPlayer.setTradeRoutes(routes); // Have to update the whole player alas. return new ChangeSet().add(See.only(serverPlayer), serverPlayer) .build(serverPlayer); } /** * Get a new trade route for a player. * * @param serverPlayer The <code>ServerPlayer</code> to get a trade * route for. * @return An <code>Element</code> encapsulating this action. */ public Element getNewTradeRoute(ServerPlayer serverPlayer) { List<TradeRoute> routes = new ArrayList<TradeRoute>(serverPlayer.getTradeRoutes()); TradeRoute route = new TradeRoute(getGame(), "", serverPlayer); routes.add(route); serverPlayer.setTradeRoutes(routes); return new ChangeSet().addTradeRoute(serverPlayer, route) .build(serverPlayer); } /** * Get a list of abstract REF units for a player. * * @param serverPlayer The <code>ServerPlayer</code> to query the REF of. * @return An <code>Element</code> encapsulating this action. */ public Element getREFUnits(ServerPlayer serverPlayer) { Game game = getGame(); Specification spec = game.getSpecification(); List<AbstractUnit> units = new ArrayList<AbstractUnit>(); final UnitType defaultType = spec.getDefaultUnitType(); if (serverPlayer.getPlayerType() == PlayerType.COLONIAL) { units = serverPlayer.getMonarch().getExpeditionaryForce().getUnits(); } else { ServerPlayer REFPlayer = (ServerPlayer) serverPlayer.getREFPlayer(); java.util.Map<UnitType, EnumMap<Role, Integer>> unitHash = new HashMap<UnitType, EnumMap<Role, Integer>>(); for (Unit unit : REFPlayer.getUnits()) { if (unit.isOffensiveUnit()) { UnitType unitType = defaultType; if (unit.getType().getOffence() > 0 || unit.hasAbility(Ability.EXPERT_SOLDIER)) { unitType = unit.getType(); } EnumMap<Role, Integer> roleMap = unitHash.get(unitType); if (roleMap == null) { roleMap = new EnumMap<Role, Integer>(Role.class); } Role role = unit.getRole(); Integer count = roleMap.get(role); if (count == null) { roleMap.put(role, new Integer(1)); } else { roleMap.put(role, new Integer(count.intValue() + 1)); } unitHash.put(unitType, roleMap); } } for (java.util.Map.Entry<UnitType, EnumMap<Role, Integer>> typeEntry : unitHash.entrySet()) { for (java.util.Map.Entry<Role, Integer> roleEntry : typeEntry.getValue().entrySet()) { units.add(new AbstractUnit(typeEntry.getKey(), roleEntry.getKey(), roleEntry.getValue())); } } } ChangeSet cs = new ChangeSet(); cs.addTrivial(See.only(serverPlayer), "getREFUnits", ChangePriority.CHANGE_NORMAL); Element reply = cs.build(serverPlayer); // TODO: eliminate explicit Element hackery for (AbstractUnit unit : units) { reply.appendChild(unit.toXMLElement(serverPlayer, reply.getOwnerDocument())); } return reply; } /** * Gets the list of high scores. * * @param serverPlayer The <code>ServerPlayer</code> that is querying. * @return An <code>Element</code> encapsulating this action. */ public Element getHighScores(ServerPlayer serverPlayer) { ChangeSet cs = new ChangeSet(); cs.addTrivial(See.only(serverPlayer), "getHighScores", ChangePriority.CHANGE_NORMAL); Element reply = cs.build(serverPlayer); for (HighScore score : getFreeColServer().getHighScores()) { reply.appendChild(score.toXMLElement(serverPlayer, reply.getOwnerDocument())); } return reply; } /** * Chat. * * @param serverPlayer The <code>ServerPlayer</code> that is chatting. * @param message The chat message. * @param pri A privacy setting, currently a noop. * @return An <code>Element</code> encapsulating this action. */ public Element chat(ServerPlayer serverPlayer, String message, boolean pri) { sendToOthers(serverPlayer, new ChatMessage(serverPlayer, message, false) .toXMLElement()); return null; } /** * Get the current game statistics. * * @return An <code>Element</code> encapsulating this action. */ public Element getStatistics(ServerPlayer serverPlayer) { // Convert statistics map to a list. java.util.Map<String, String> stats = getGame() .getStatistics(); stats.putAll(getFreeColServer().getAIMain().getAIStatistics()); List<String> all = new ArrayList<String>(); List<String> keys = new ArrayList<String>(stats.keySet()); Collections.sort(keys); for (String k : keys) { all.add(k); all.add(stats.get(k)); } // Return as statistics element. ChangeSet cs = new ChangeSet(); cs.addTrivial(See.only(serverPlayer), "statistics", ChangePriority.CHANGE_NORMAL, all.toArray(new String[0])); return cs.build(serverPlayer); } /** * Enters revenge mode against those evil AIs. * * @param serverPlayer The <code>ServerPlayer</code> entering revenge mode. * @return An <code>Element</code> encapsulating this action. */ public Element enterRevengeMode(ServerPlayer serverPlayer) { if (!getFreeColServer().isSingleplayer()) { return DOMMessage.clientError("Can not enter revenge mode," + " as this is not a single player game."); } Game game = getGame(); List<UnitType> undeads = game.getSpecification() .getUnitTypesWithAbility("model.ability.undead"); List<UnitType> navalUnits = new ArrayList<UnitType>(); List<UnitType> landUnits = new ArrayList<UnitType>(); for (UnitType undead : undeads) { if (undead.hasAbility(Ability.NAVAL_UNIT)) { navalUnits.add(undead); } else if (undead.hasAbility("model.ability.multipleAttacks")) { landUnits.add(undead); } } if (navalUnits.size() == 0 || landUnits.size() == 0) { return DOMMessage.clientError("Can not enter revenge mode," + " because we can not find the undead units."); } ChangeSet cs = new ChangeSet(); UnitType navalType = navalUnits.get(Utils.randomInt(logger, "Choose undead navy", random, navalUnits.size())); Tile start = ((Tile) serverPlayer.getEntryLocation()) .getSafeTile(serverPlayer, random); Unit theFlyingDutchman = new ServerUnit(game, start, serverPlayer, navalType); UnitType landType = landUnits.get(Utils.randomInt(logger, "Choose undead army", random, landUnits.size())); new ServerUnit(game, theFlyingDutchman, serverPlayer, landType); serverPlayer.setDead(false); serverPlayer.setPlayerType(PlayerType.UNDEAD); // No one likes the undead. for (Player p : game.getPlayers()) { if (serverPlayer != (ServerPlayer) p && serverPlayer.hasContacted(p)) { serverPlayer.csChangeStance(Stance.WAR, p, true, cs); } } // Others can tell something has happened to the player, // and possibly see the units. cs.add(See.all(), serverPlayer); cs.add(See.perhaps(), start); sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } }
false
true
public Element endTurn(ServerPlayer serverPlayer) { FreeColServer freeColServer = getFreeColServer(); ServerGame game = getGame(); ServerPlayer player = (ServerPlayer) game.getCurrentPlayer(); if (serverPlayer != player) { throw new IllegalArgumentException("It is not " + serverPlayer.getName() + "'s turn, it is " + ((player == null) ? "noone" : player.getName()) + "'s!"); } for (;;) { logger.finest("Ending turn for " + player.getName()); player.clearModelMessages(); // Has anyone won? // Do not end single player games where an AI has won, // that would stop revenge mode. Player winner = game.checkForWinner(); if (winner != null && !(freeColServer.isSingleplayer() && winner.isAI())) { ChangeSet cs = new ChangeSet(); cs.addTrivial(See.all(), "gameEnded", ChangePriority.CHANGE_NORMAL, "winner", winner.getId()); sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } // Are there humans left? // TODO: see if this can be relaxed so we can run large // AI-only simulations. boolean human = false; for (Player p : game.getPlayers()) { if (!p.isDead() && !p.isAI() && ((ServerPlayer) p).isConnected()) { human = true; break; } } if (!human) { game.setCurrentPlayer(null); return null; } // ATM AI player colony-rearrangements do not use the standard // c-s model but exploit the fact that the AIs and the server // are still in the same memory space. This means that // the colony sizes will be wrongly reported unless we take // the following explicit action. ChangeSet cs = new ChangeSet(); if (player.isAI() && player.isEuropean()) { for (Colony c : player.getColonies()) { cs.add(See.perhaps().except(player), c); } } // Clean up futures from the current player. resolveOutstandingQueries(); // Check for new turn if (game.isNextPlayerInNewTurn()) { game.csNewTurn(random, cs); if (debugOnlyAITurns > 0) { if (--debugOnlyAITurns <= 0) { // If this was a debug run, complete it. This will // possibly signal the client to save and quit. if (FreeCol.getDebugRunTurns() > 0) { FreeCol.completeDebugRun(); } } } } if ((player = (ServerPlayer) game.getNextPlayer()) == null) { // "can not happen" return DOMMessage.clientError("Can not get next player"); } if (player.checkForDeath()) { // Remove dead players and retry player.csWithdraw(cs); sendToAll(cs); logger.info(player.getNation() + " is dead."); continue; } else if (player.isREF() && player.checkForREFDefeat()) { for (Player p : player.getRebels()) { csGiveIndependence(player, (ServerPlayer) p, cs); } player.csWithdraw(cs); sendToAll(cs); logger.info(player.getNation() + " is defeated."); continue; } // Do "new turn"-like actions that need to wait until right // before the player is about to move. game.setCurrentPlayer(player); if (player.isREF() && player.getEntryLocation() == null) { // Initialize this newly created REF, determining its // entry location. // If the teleportREF option is enabled, teleport it in. REFAIPlayer refAIPlayer = (REFAIPlayer) freeColServer .getAIPlayer(player); boolean teleport = getGame().getSpecification() .getBoolean(GameOptions.TELEPORT_REF); Tile entry = refAIPlayer.initialize(teleport); if (entry == null) { for (Player p : player.getRebels()) { entry = p.getEntryLocation().getTile(); break; } } player.setEntryLocation(entry); logger.info(player.getName() + " will appear at " + entry); if (teleport) { for (Unit u : player.getUnits()) { if (u.isNaval()) { u.setLocation(entry); u.setWorkLeft(-1); u.setState(Unit.UnitState.ACTIVE); } } cs.add(See.perhaps(), entry); } } player.csStartTurn(random, cs); nextFoundingFather(player); cs.addTrivial(See.all(), "setCurrentPlayer", ChangePriority.CHANGE_LATE, "player", player.getId()); if (player.getPlayerType() == PlayerType.COLONIAL) { Monarch monarch = player.getMonarch(); MonarchAction action = null; if (debugMonarchAction != null && player == debugMonarchPlayer) { action = debugMonarchAction; debugMonarchAction = null; debugMonarchPlayer = null; logger.finest("Debug monarch action: " + action); } else { action = RandomChoice.getWeightedRandom(logger, "Choose monarch action", random, monarch.getActionChoices()); } if (action != null) { if (monarch.actionIsValid(action)) { logger.finest("Monarch action: " + action); csMonarchAction(player, action, cs); } else { logger.finest("Skipping invalid monarch action: " + action); } } } // Flush accumulated changes and return. // Send to all players, taking care that the new player is // last, then return null to the old player who requested // the end-of-turn. sendToList(getOtherPlayers(serverPlayer, (ServerPlayer)player), cs); sendElement(serverPlayer, cs); sendElement((ServerPlayer)player, cs); return null; } }
public Element endTurn(ServerPlayer serverPlayer) { FreeColServer freeColServer = getFreeColServer(); ServerGame game = getGame(); ServerPlayer player = (ServerPlayer) game.getCurrentPlayer(); if (serverPlayer != player) { throw new IllegalArgumentException("It is not " + serverPlayer.getName() + "'s turn, it is " + ((player == null) ? "noone" : player.getName()) + "'s!"); } for (;;) { logger.finest("Ending turn for " + player.getName()); player.clearModelMessages(); // Has anyone won? // Do not end single player games where an AI has won, // that would stop revenge mode. Player winner = game.checkForWinner(); if (winner != null && !(freeColServer.isSingleplayer() && winner.isAI())) { ChangeSet cs = new ChangeSet(); cs.addTrivial(See.all(), "gameEnded", ChangePriority.CHANGE_NORMAL, "winner", winner.getId()); sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); } // Are there humans left? // TODO: see if this can be relaxed so we can run large // AI-only simulations. boolean human = false; for (Player p : game.getPlayers()) { if (!p.isDead() && !p.isAI() && ((ServerPlayer) p).isConnected()) { human = true; break; } } if (!human) { game.setCurrentPlayer(null); return null; } // ATM AI player colony-rearrangements do not use the standard // c-s model but exploit the fact that the AIs and the server // are still in the same memory space. This means that // the colony sizes will be wrongly reported unless we take // the following explicit action. ChangeSet cs = new ChangeSet(); if (player.isAI() && player.isEuropean()) { for (Colony c : player.getColonies()) { cs.add(See.perhaps().except(player), c); } } // Clean up futures from the current player. resolveOutstandingQueries(); // Check for new turn if (game.isNextPlayerInNewTurn()) { game.csNewTurn(random, cs); if (debugOnlyAITurns > 0) { if (--debugOnlyAITurns <= 0) { // If this was a debug run, complete it. This will // possibly signal the client to save and quit. if (FreeCol.getDebugRunTurns() > 0) { FreeCol.completeDebugRun(); } } } } if ((player = (ServerPlayer) game.getNextPlayer()) == null) { // "can not happen" return DOMMessage.clientError("Can not get next player"); } if (player.checkForDeath()) { // Remove dead players and retry player.csWithdraw(cs); sendToAll(cs); logger.info(player.getNation() + " is dead."); continue; } else if (player.isREF() && player.checkForREFDefeat()) { for (Player p : player.getRebels()) { csGiveIndependence(player, (ServerPlayer) p, cs); } player.csWithdraw(cs); sendToAll(cs); logger.info(player.getNation() + " is defeated."); continue; } // Do "new turn"-like actions that need to wait until right // before the player is about to move. game.setCurrentPlayer(player); if (player.isREF() && player.getEntryLocation() == null) { // Initialize this newly created REF, determining its // entry location. // If the teleportREF option is enabled, teleport it in. REFAIPlayer refAIPlayer = (REFAIPlayer) freeColServer .getAIPlayer(player); boolean teleport = getGame().getSpecification() .getBoolean(GameOptions.TELEPORT_REF); Tile entry = refAIPlayer.initialize(teleport); if (entry == null) { for (Player p : player.getRebels()) { entry = p.getEntryLocation().getTile(); break; } } player.setEntryLocation(entry); logger.info(player.getName() + " will appear at " + entry); if (teleport) { for (Unit u : player.getUnits()) { if (u.isNaval()) { u.setLocation(entry); u.setWorkLeft(-1); u.setState(Unit.UnitState.ACTIVE); } } cs.add(See.perhaps(), entry); } } player.csStartTurn(random, cs); nextFoundingFather(player); cs.addTrivial(See.all(), "setCurrentPlayer", ChangePriority.CHANGE_LATE, "player", player.getId()); if (player.getPlayerType() == PlayerType.COLONIAL) { Monarch monarch = player.getMonarch(); MonarchAction action = null; if (debugMonarchAction != null && player == debugMonarchPlayer) { action = debugMonarchAction; debugMonarchAction = null; debugMonarchPlayer = null; logger.finest("Debug monarch action: " + action); } else { action = RandomChoice.getWeightedRandom(logger, "Choose monarch action", random, monarch.getActionChoices()); } if (action != null) { if (monarch.actionIsValid(action)) { logger.finest("Monarch action: " + action); csMonarchAction(player, action, cs); } else { logger.finest("Skipping invalid monarch action: " + action); } } } // Flush accumulated changes and return. // Send to all players, taking care that the new player is // last, then return to the old player who requested // the end-of-turn. sendToList(getOtherPlayers(serverPlayer, (ServerPlayer)player), cs); sendElement((ServerPlayer)player, cs); return cs.build(serverPlayer); } }
diff --git a/search/org/eclipse/cdt/internal/core/search/matching/MatchLocator.java b/search/org/eclipse/cdt/internal/core/search/matching/MatchLocator.java index d7b4bd9fe..4977027db 100644 --- a/search/org/eclipse/cdt/internal/core/search/matching/MatchLocator.java +++ b/search/org/eclipse/cdt/internal/core/search/matching/MatchLocator.java @@ -1,668 +1,668 @@ /******************************************************************************* * Copyright (c) 2003, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corp. - Rational Software - initial implementation *******************************************************************************/ /* * Created on Jun 13, 2003 */ package org.eclipse.cdt.internal.core.search.matching; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.core.parser.CodeReader; import org.eclipse.cdt.core.parser.IParser; import org.eclipse.cdt.core.parser.IProblem; import org.eclipse.cdt.core.parser.IScanner; import org.eclipse.cdt.core.parser.IScannerInfo; import org.eclipse.cdt.core.parser.IScannerInfoProvider; import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate; import org.eclipse.cdt.core.parser.ParserFactory; import org.eclipse.cdt.core.parser.ParserFactoryError; import org.eclipse.cdt.core.parser.ParserLanguage; import org.eclipse.cdt.core.parser.ParserMode; import org.eclipse.cdt.core.parser.ParserUtil; import org.eclipse.cdt.core.parser.ScannerInfo; import org.eclipse.cdt.core.parser.ast.IASTASMDefinition; import org.eclipse.cdt.core.parser.ast.IASTAbstractTypeSpecifierDeclaration; import org.eclipse.cdt.core.parser.ast.IASTClassReference; import org.eclipse.cdt.core.parser.ast.IASTClassSpecifier; import org.eclipse.cdt.core.parser.ast.IASTCodeScope; import org.eclipse.cdt.core.parser.ast.IASTCompilationUnit; import org.eclipse.cdt.core.parser.ast.IASTDeclaration; import org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier; import org.eclipse.cdt.core.parser.ast.IASTEnumerationReference; import org.eclipse.cdt.core.parser.ast.IASTEnumerationSpecifier; import org.eclipse.cdt.core.parser.ast.IASTEnumerator; import org.eclipse.cdt.core.parser.ast.IASTEnumeratorReference; import org.eclipse.cdt.core.parser.ast.IASTField; import org.eclipse.cdt.core.parser.ast.IASTFieldReference; import org.eclipse.cdt.core.parser.ast.IASTFunction; import org.eclipse.cdt.core.parser.ast.IASTFunctionReference; import org.eclipse.cdt.core.parser.ast.IASTInclusion; import org.eclipse.cdt.core.parser.ast.IASTLinkageSpecification; import org.eclipse.cdt.core.parser.ast.IASTMacro; import org.eclipse.cdt.core.parser.ast.IASTMethod; import org.eclipse.cdt.core.parser.ast.IASTMethodReference; import org.eclipse.cdt.core.parser.ast.IASTNamespaceDefinition; import org.eclipse.cdt.core.parser.ast.IASTNamespaceReference; import org.eclipse.cdt.core.parser.ast.IASTOffsetableNamedElement; import org.eclipse.cdt.core.parser.ast.IASTParameterReference; import org.eclipse.cdt.core.parser.ast.IASTReference; import org.eclipse.cdt.core.parser.ast.IASTScope; import org.eclipse.cdt.core.parser.ast.IASTTemplateDeclaration; import org.eclipse.cdt.core.parser.ast.IASTTemplateInstantiation; import org.eclipse.cdt.core.parser.ast.IASTTemplateParameterReference; import org.eclipse.cdt.core.parser.ast.IASTTemplateSpecialization; import org.eclipse.cdt.core.parser.ast.IASTTypedefDeclaration; import org.eclipse.cdt.core.parser.ast.IASTTypedefReference; import org.eclipse.cdt.core.parser.ast.IASTUsingDeclaration; import org.eclipse.cdt.core.parser.ast.IASTUsingDirective; import org.eclipse.cdt.core.parser.ast.IASTVariable; import org.eclipse.cdt.core.parser.ast.IASTVariableReference; import org.eclipse.cdt.core.search.ICSearchPattern; import org.eclipse.cdt.core.search.ICSearchResultCollector; import org.eclipse.cdt.core.search.ICSearchScope; import org.eclipse.cdt.core.search.IMatch; import org.eclipse.cdt.core.search.IMatchLocator; import org.eclipse.cdt.internal.core.search.AcceptMatchOperation; import org.eclipse.cdt.internal.core.search.indexing.IndexProblemHandler; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; /** * @author aniefer * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class MatchLocator implements IMatchLocator{ ArrayList matchStorage; public static boolean VERBOSE = false; /** * */ public MatchLocator( ICSearchPattern pattern, ICSearchResultCollector collector, ICSearchScope scope) { super(); searchPattern = pattern; resultCollector = collector; searchScope = scope; } public boolean acceptProblem(IProblem problem) { return IndexProblemHandler.ruleOnProblem(problem, ParserMode.COMPLETE_PARSE ); } public void acceptUsingDirective(IASTUsingDirective usageDirective) { } public void acceptUsingDeclaration(IASTUsingDeclaration usageDeclaration) { } public void acceptASMDefinition(IASTASMDefinition asmDefinition) { } public void acceptAbstractTypeSpecDeclaration(IASTAbstractTypeSpecifierDeclaration abstractDeclaration) {} public void enterTemplateDeclaration(IASTTemplateDeclaration declaration) { } public void enterTemplateSpecialization(IASTTemplateSpecialization specialization) { } public void enterTemplateInstantiation(IASTTemplateInstantiation instantiation) { } public void exitTemplateDeclaration(IASTTemplateDeclaration declaration) {} public void exitTemplateSpecialization(IASTTemplateSpecialization specialization) { } public void exitTemplateExplicitInstantiation(IASTTemplateInstantiation instantiation) { } public void enterCodeBlock(IASTCodeScope scope) { } public void exitCodeBlock(IASTCodeScope scope) { } public void enterLinkageSpecification(IASTLinkageSpecification linkageSpec){ pushScope( linkageSpec ); } public void exitLinkageSpecification(IASTLinkageSpecification linkageSpec){ popScope(); } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptParameterReference(org.eclipse.cdt.internal.core.parser.ast.complete.ASTParameterReference) */ public void acceptParameterReference(IASTParameterReference reference) { check( REFERENCES, reference ); } public void acceptTemplateParameterReference(IASTTemplateParameterReference reference) { check( REFERENCES, reference ); } public void acceptTypedefDeclaration(IASTTypedefDeclaration typedef){ lastDeclaration = typedef; check( DECLARATIONS, typedef ); } public void acceptTypedefReference( IASTTypedefReference reference ){ check( REFERENCES, reference ); } public void acceptEnumeratorReference(IASTEnumeratorReference reference){ check( REFERENCES, reference ); } public void acceptMacro(IASTMacro macro){ check( DECLARATIONS, macro ); } public void acceptVariable(IASTVariable variable){ lastDeclaration = variable; check( DECLARATIONS, variable ); //A declaration is a definition unless...: //it contains the extern specifier or a linkage-spec and no initializer if( variable.getInitializerClause() != null || ( !variable.isExtern() && !(currentScope instanceof IASTLinkageSpecification) ) ){ check( DEFINITIONS, variable ); } } public void acceptField(IASTField field){ lastDeclaration = field; if( currentScope instanceof IASTClassSpecifier ){ check( DECLARATIONS, field ); if( !field.isStatic() ){ check( DEFINITIONS, field ); } } else { check( DEFINITIONS, field ); } } public void acceptEnumerationSpecifier(IASTEnumerationSpecifier enumeration){ lastDeclaration = enumeration; check( DECLARATIONS, enumeration ); Iterator iter = enumeration.getEnumerators(); while( iter.hasNext() ){ IASTEnumerator enumerator = (IASTEnumerator) iter.next(); lastDeclaration = enumerator; check ( DECLARATIONS, enumerator ); } } public void acceptFunctionDeclaration(IASTFunction function){ lastDeclaration = function; check( DECLARATIONS, function ); } public void acceptMethodDeclaration(IASTMethod method){ lastDeclaration = method; check( DECLARATIONS, method ); } public void acceptClassReference(IASTClassReference reference) { check( REFERENCES, reference ); } public void acceptNamespaceReference( IASTNamespaceReference reference ){ check( REFERENCES, reference ); } public void acceptVariableReference( IASTVariableReference reference ){ check( REFERENCES, reference ); } public void acceptFieldReference( IASTFieldReference reference ){ check( REFERENCES, reference ); } public void acceptEnumerationReference( IASTEnumerationReference reference ){ check( REFERENCES, reference ); } public void acceptFunctionReference( IASTFunctionReference reference ){ check( REFERENCES, reference ); } public void acceptMethodReference( IASTMethodReference reference ){ check( REFERENCES, reference ); } public void enterFunctionBody(IASTFunction function){ lastDeclaration = function; if( !function.previouslyDeclared() ) check( DECLARATIONS, function ); check( DEFINITIONS, function ); pushScope( function ); } public void enterMethodBody(IASTMethod method) { lastDeclaration = method; if( !method.previouslyDeclared() ) check( DECLARATIONS, method ); check( DEFINITIONS, method ); pushScope( method ); } public void enterCompilationUnit(IASTCompilationUnit compilationUnit) { pushScope( compilationUnit ); } public void enterNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) { lastDeclaration = namespaceDefinition; check( DECLARATIONS, namespaceDefinition ); check( DEFINITIONS, namespaceDefinition ); pushScope( namespaceDefinition ); } public void enterClassSpecifier(IASTClassSpecifier classSpecification) { lastDeclaration = classSpecification; check( DECLARATIONS, classSpecification ); pushScope( classSpecification ); } public void exitFunctionBody(IASTFunction function) { popScope(); } public void exitMethodBody(IASTMethod method) { popScope(); } public void exitClassSpecifier(IASTClassSpecifier classSpecification) { check(DECLARATIONS, classSpecification); popScope(); } public void exitNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) { popScope(); } public void exitCompilationUnit(IASTCompilationUnit compilationUnit){ popScope(); } public void enterInclusion(IASTInclusion inclusion) { String includePath = inclusion.getFullFileName(); IPath path = new Path( includePath ); IResource resource = null; if( workspaceRoot != null ){ resource = workspaceRoot.getFileForLocation( path ); // if( resource == null ){ // //TODO:What to do if the file is not in the workspace? // IFile file = currentResource.getProject().getFile( inclusion.getName() ); // try{ // file.createLink( path, 0, null ); // } catch ( CoreException e ){ // file = null; // } // resource = file; // } } resourceStack.addFirst( ( currentResource != null ) ? (Object)currentResource : (Object)currentPath ); currentResource = resource; currentPath = ( resource == null ) ? path : null; } public void exitInclusion(IASTInclusion inclusion) { Object obj = resourceStack.removeFirst(); if( obj instanceof IResource ){ currentResource = (IResource)obj; currentPath = null; } else { currentPath = (IPath) obj; currentResource = null; } } public void locateMatches( String [] paths, IWorkspace workspace, IWorkingCopy[] workingCopies ) throws InterruptedException{ matchStorage = new ArrayList(); workspaceRoot = (workspace != null) ? workspace.getRoot() : null; HashMap wcPaths = new HashMap(); int wcLength = (workingCopies == null) ? 0 : workingCopies.length; if( wcLength > 0 ){ String [] newPaths = new String[ wcLength ]; for( int i = 0; i < wcLength; i++ ){ IWorkingCopy workingCopy = workingCopies[ i ]; String path = workingCopy.getOriginalElement().getPath().toString(); wcPaths.put( path, workingCopy ); newPaths[ i ] = path; } int len = paths.length; String [] tempArray = new String[ len + wcLength ]; System.arraycopy( paths, 0, tempArray, 0, len ); System.arraycopy( newPaths, 0, tempArray, len, wcLength ); paths = tempArray; } Arrays.sort( paths ); int length = paths.length; if( progressMonitor != null ){ progressMonitor.beginTask( "", length ); //$NON-NLS-1$ } for( int i = 0; i < length; i++ ){ if( progressMonitor != null ) { if( progressMonitor.isCanceled() ){ throw new InterruptedException(); } else { progressMonitor.worked( 1 ); } } String pathString = paths[ i ]; //skip duplicates if( i > 0 && pathString.equals( paths[ i - 1 ] ) ) continue; if (!searchScope.encloses(pathString)) continue; CodeReader reader = null; realPath = null; IProject project = null; if( workspaceRoot != null ){ IWorkingCopy workingCopy = (IWorkingCopy)wcPaths.get( pathString ); if( workingCopy != null ){ currentResource = workingCopy.getResource(); if ( currentResource != null && currentResource.isAccessible() ) { reader = new CodeReader(currentResource.getLocation().toOSString(), workingCopy.getContents()); realPath = currentResource.getLocation(); project = currentResource.getProject(); } else { continue; } } else { currentResource = workspaceRoot.findMember( pathString, true ); InputStream contents = null; try{ if( currentResource != null ){ if (currentResource.isAccessible() && currentResource instanceof IFile) { IFile file = (IFile) currentResource; contents = file.getContents(); reader = new CodeReader(currentResource.getLocation().toOSString(), contents); realPath = currentResource.getLocation(); project = file.getProject(); } else { continue; } } } catch ( CoreException e ){ continue; } catch ( IOException e ) { continue; } finally { if (contents != null) { try { contents.close(); } catch (IOException io) { // ignore. } } } } } if( currentResource == null ) { try { IPath path = new Path( pathString ); currentPath = path; reader = new CodeReader(pathString); realPath = currentPath; } catch (IOException e) { continue; } } //Get the scanner info IScannerInfo scanInfo = new ScannerInfo(); IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project); if (provider != null){ - IScannerInfo buildScanInfo = provider.getScannerInformation(project); + IScannerInfo buildScanInfo = provider.getScannerInformation(currentResource != null ? currentResource : project); if( buildScanInfo != null ) scanInfo = new ScannerInfo(buildScanInfo.getDefinedSymbols(), buildScanInfo.getIncludePaths()); } ParserLanguage language = null; if( project != null ){ language = CoreModel.hasCCNature( project ) ? ParserLanguage.CPP : ParserLanguage.C; } else { //TODO no project, what language do we use? language = ParserLanguage.CPP; } IParser parser = null; try { IScanner scanner = ParserFactory.createScanner( reader, scanInfo, ParserMode.COMPLETE_PARSE, language, this, ParserUtil.getScannerLogService(), null ); parser = ParserFactory.createParser( scanner, this, ParserMode.COMPLETE_PARSE, language, ParserUtil.getParserLogService() ); } catch( ParserFactoryError pfe ) { } if (VERBOSE) MatchLocator.verbose("*** New Search for path: " + pathString); //$NON-NLS-1$ try{ parser.parse(); } catch(Exception ex){ if (VERBOSE){ ex.printStackTrace(); } } catch(VirtualMachineError vmErr){ if (VERBOSE){ MatchLocator.verbose("MatchLocator VM Error: "); //$NON-NLS-1$ vmErr.printStackTrace(); } } finally { scopeStack.clear(); resourceStack.clear(); lastDeclaration = null; currentScope = null; parser = null; } if( matchStorage.size() > 0 ){ AcceptMatchOperation acceptMatchOp = new AcceptMatchOperation( resultCollector, matchStorage ); try { CCorePlugin.getWorkspace().run(acceptMatchOp,null); } catch (CoreException e) {} matchStorage.clear(); } } } protected void report( ISourceElementCallbackDelegate node, int accuracyLevel ){ try { if( currentResource != null && !searchScope.encloses(currentResource.getFullPath().toOSString() ) ){ return; } int offset = 0; int end = 0; if( node instanceof IASTReference ){ IASTReference reference = (IASTReference) node; offset = reference.getOffset(); end = offset + reference.getName().length(); if (VERBOSE) MatchLocator.verbose("Report Match: " + reference.getName()); //$NON-NLS-1$ } else if( node instanceof IASTOffsetableNamedElement ){ IASTOffsetableNamedElement offsetableElement = (IASTOffsetableNamedElement) node; offset = offsetableElement.getNameOffset() != 0 ? offsetableElement.getNameOffset() : offsetableElement.getStartingOffset(); end = offsetableElement.getNameEndOffset(); if( end == 0 ){ end = offset + offsetableElement.getName().length(); } if (VERBOSE) MatchLocator.verbose("Report Match: " + offsetableElement.getName()); //$NON-NLS-1$ } IMatch match = null; ISourceElementCallbackDelegate object = null; if( node instanceof IASTReference ){ if( currentScope instanceof IASTFunction || currentScope instanceof IASTMethod ){ object = (ISourceElementCallbackDelegate) currentScope; } else { object = lastDeclaration; } } else { if( currentScope instanceof IASTFunction || currentScope instanceof IASTMethod ){ //local declaration, only report if not being filtered if( shouldExcludeLocalDeclarations ){ return; } object = (ISourceElementCallbackDelegate) currentScope; } else { object = node; } } if( currentResource != null ){ match = resultCollector.createMatch( currentResource, offset, end, object, null ); } else if( currentPath != null ){ match = resultCollector.createMatch( currentPath, offset, end, object, realPath ); } if( match != null ){ //Save till later //resultCollector.acceptMatch( match ); matchStorage.add(match); } } catch (CoreException e) { } } private void check( LimitTo limit, ISourceElementCallbackDelegate node ){ if( !searchPattern.canAccept( limit ) ) return; int level = ICSearchPattern.IMPOSSIBLE_MATCH; if( node instanceof IASTReference ){ level = searchPattern.matchLevel( ((IASTReference)node).getReferencedElement(), limit ); } else { level = searchPattern.matchLevel( node, limit ); } if( level != ICSearchPattern.IMPOSSIBLE_MATCH ) { report( node, level ); } } private void pushScope( IASTScope scope ){ scopeStack.addFirst( currentScope ); currentScope = scope; } private IASTScope popScope(){ IASTScope oldScope = currentScope; currentScope = (scopeStack.size() > 0 ) ? (IASTScope) scopeStack.removeFirst() : null; return oldScope; } public void setShouldExcludeLocalDeclarations( boolean exclude ){ shouldExcludeLocalDeclarations = exclude; } private boolean shouldExcludeLocalDeclarations = false; private ISourceElementCallbackDelegate lastDeclaration; private ICSearchPattern searchPattern; private ICSearchResultCollector resultCollector; private IProgressMonitor progressMonitor; private IPath currentPath = null; private ICSearchScope searchScope; private IWorkspaceRoot workspaceRoot; private IPath realPath; private IResource currentResource = null; private LinkedList resourceStack = new LinkedList(); private IASTScope currentScope = null; private LinkedList scopeStack = new LinkedList(); /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptElaboratedForewardDeclaration(org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier) */ public void acceptElaboratedForewardDeclaration(IASTElaboratedTypeSpecifier elaboratedType){ check( DECLARATIONS, elaboratedType ); } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptFriendDeclaration(org.eclipse.cdt.core.parser.ast.IASTDeclaration) */ public void acceptFriendDeclaration(IASTDeclaration declaration) { // TODO Auto-generated method stub } public static void verbose(String log) { System.out.println("(" + Thread.currentThread() + ") " + log); //$NON-NLS-1$ //$NON-NLS-2$ } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#createReader(java.lang.String) */ public CodeReader createReader(String finalPath, Iterator workingCopies) { return ParserUtil.createReader(finalPath,workingCopies); } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#parserTimeout() */ public boolean parserTimeout() { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see org.eclipse.cdt.core.search.IMatchLocator#setProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) */ public void setProgressMonitor(IProgressMonitor progressMonitor) { this.progressMonitor = progressMonitor; } }
true
true
public void locateMatches( String [] paths, IWorkspace workspace, IWorkingCopy[] workingCopies ) throws InterruptedException{ matchStorage = new ArrayList(); workspaceRoot = (workspace != null) ? workspace.getRoot() : null; HashMap wcPaths = new HashMap(); int wcLength = (workingCopies == null) ? 0 : workingCopies.length; if( wcLength > 0 ){ String [] newPaths = new String[ wcLength ]; for( int i = 0; i < wcLength; i++ ){ IWorkingCopy workingCopy = workingCopies[ i ]; String path = workingCopy.getOriginalElement().getPath().toString(); wcPaths.put( path, workingCopy ); newPaths[ i ] = path; } int len = paths.length; String [] tempArray = new String[ len + wcLength ]; System.arraycopy( paths, 0, tempArray, 0, len ); System.arraycopy( newPaths, 0, tempArray, len, wcLength ); paths = tempArray; } Arrays.sort( paths ); int length = paths.length; if( progressMonitor != null ){ progressMonitor.beginTask( "", length ); //$NON-NLS-1$ } for( int i = 0; i < length; i++ ){ if( progressMonitor != null ) { if( progressMonitor.isCanceled() ){ throw new InterruptedException(); } else { progressMonitor.worked( 1 ); } } String pathString = paths[ i ]; //skip duplicates if( i > 0 && pathString.equals( paths[ i - 1 ] ) ) continue; if (!searchScope.encloses(pathString)) continue; CodeReader reader = null; realPath = null; IProject project = null; if( workspaceRoot != null ){ IWorkingCopy workingCopy = (IWorkingCopy)wcPaths.get( pathString ); if( workingCopy != null ){ currentResource = workingCopy.getResource(); if ( currentResource != null && currentResource.isAccessible() ) { reader = new CodeReader(currentResource.getLocation().toOSString(), workingCopy.getContents()); realPath = currentResource.getLocation(); project = currentResource.getProject(); } else { continue; } } else { currentResource = workspaceRoot.findMember( pathString, true ); InputStream contents = null; try{ if( currentResource != null ){ if (currentResource.isAccessible() && currentResource instanceof IFile) { IFile file = (IFile) currentResource; contents = file.getContents(); reader = new CodeReader(currentResource.getLocation().toOSString(), contents); realPath = currentResource.getLocation(); project = file.getProject(); } else { continue; } } } catch ( CoreException e ){ continue; } catch ( IOException e ) { continue; } finally { if (contents != null) { try { contents.close(); } catch (IOException io) { // ignore. } } } } } if( currentResource == null ) { try { IPath path = new Path( pathString ); currentPath = path; reader = new CodeReader(pathString); realPath = currentPath; } catch (IOException e) { continue; } } //Get the scanner info IScannerInfo scanInfo = new ScannerInfo(); IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project); if (provider != null){ IScannerInfo buildScanInfo = provider.getScannerInformation(project); if( buildScanInfo != null ) scanInfo = new ScannerInfo(buildScanInfo.getDefinedSymbols(), buildScanInfo.getIncludePaths()); } ParserLanguage language = null; if( project != null ){ language = CoreModel.hasCCNature( project ) ? ParserLanguage.CPP : ParserLanguage.C; } else { //TODO no project, what language do we use? language = ParserLanguage.CPP; } IParser parser = null; try { IScanner scanner = ParserFactory.createScanner( reader, scanInfo, ParserMode.COMPLETE_PARSE, language, this, ParserUtil.getScannerLogService(), null ); parser = ParserFactory.createParser( scanner, this, ParserMode.COMPLETE_PARSE, language, ParserUtil.getParserLogService() ); } catch( ParserFactoryError pfe ) { } if (VERBOSE) MatchLocator.verbose("*** New Search for path: " + pathString); //$NON-NLS-1$ try{ parser.parse(); } catch(Exception ex){ if (VERBOSE){ ex.printStackTrace(); } } catch(VirtualMachineError vmErr){ if (VERBOSE){ MatchLocator.verbose("MatchLocator VM Error: "); //$NON-NLS-1$ vmErr.printStackTrace(); } } finally { scopeStack.clear(); resourceStack.clear(); lastDeclaration = null; currentScope = null; parser = null; } if( matchStorage.size() > 0 ){ AcceptMatchOperation acceptMatchOp = new AcceptMatchOperation( resultCollector, matchStorage ); try { CCorePlugin.getWorkspace().run(acceptMatchOp,null); } catch (CoreException e) {} matchStorage.clear(); } } }
public void locateMatches( String [] paths, IWorkspace workspace, IWorkingCopy[] workingCopies ) throws InterruptedException{ matchStorage = new ArrayList(); workspaceRoot = (workspace != null) ? workspace.getRoot() : null; HashMap wcPaths = new HashMap(); int wcLength = (workingCopies == null) ? 0 : workingCopies.length; if( wcLength > 0 ){ String [] newPaths = new String[ wcLength ]; for( int i = 0; i < wcLength; i++ ){ IWorkingCopy workingCopy = workingCopies[ i ]; String path = workingCopy.getOriginalElement().getPath().toString(); wcPaths.put( path, workingCopy ); newPaths[ i ] = path; } int len = paths.length; String [] tempArray = new String[ len + wcLength ]; System.arraycopy( paths, 0, tempArray, 0, len ); System.arraycopy( newPaths, 0, tempArray, len, wcLength ); paths = tempArray; } Arrays.sort( paths ); int length = paths.length; if( progressMonitor != null ){ progressMonitor.beginTask( "", length ); //$NON-NLS-1$ } for( int i = 0; i < length; i++ ){ if( progressMonitor != null ) { if( progressMonitor.isCanceled() ){ throw new InterruptedException(); } else { progressMonitor.worked( 1 ); } } String pathString = paths[ i ]; //skip duplicates if( i > 0 && pathString.equals( paths[ i - 1 ] ) ) continue; if (!searchScope.encloses(pathString)) continue; CodeReader reader = null; realPath = null; IProject project = null; if( workspaceRoot != null ){ IWorkingCopy workingCopy = (IWorkingCopy)wcPaths.get( pathString ); if( workingCopy != null ){ currentResource = workingCopy.getResource(); if ( currentResource != null && currentResource.isAccessible() ) { reader = new CodeReader(currentResource.getLocation().toOSString(), workingCopy.getContents()); realPath = currentResource.getLocation(); project = currentResource.getProject(); } else { continue; } } else { currentResource = workspaceRoot.findMember( pathString, true ); InputStream contents = null; try{ if( currentResource != null ){ if (currentResource.isAccessible() && currentResource instanceof IFile) { IFile file = (IFile) currentResource; contents = file.getContents(); reader = new CodeReader(currentResource.getLocation().toOSString(), contents); realPath = currentResource.getLocation(); project = file.getProject(); } else { continue; } } } catch ( CoreException e ){ continue; } catch ( IOException e ) { continue; } finally { if (contents != null) { try { contents.close(); } catch (IOException io) { // ignore. } } } } } if( currentResource == null ) { try { IPath path = new Path( pathString ); currentPath = path; reader = new CodeReader(pathString); realPath = currentPath; } catch (IOException e) { continue; } } //Get the scanner info IScannerInfo scanInfo = new ScannerInfo(); IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project); if (provider != null){ IScannerInfo buildScanInfo = provider.getScannerInformation(currentResource != null ? currentResource : project); if( buildScanInfo != null ) scanInfo = new ScannerInfo(buildScanInfo.getDefinedSymbols(), buildScanInfo.getIncludePaths()); } ParserLanguage language = null; if( project != null ){ language = CoreModel.hasCCNature( project ) ? ParserLanguage.CPP : ParserLanguage.C; } else { //TODO no project, what language do we use? language = ParserLanguage.CPP; } IParser parser = null; try { IScanner scanner = ParserFactory.createScanner( reader, scanInfo, ParserMode.COMPLETE_PARSE, language, this, ParserUtil.getScannerLogService(), null ); parser = ParserFactory.createParser( scanner, this, ParserMode.COMPLETE_PARSE, language, ParserUtil.getParserLogService() ); } catch( ParserFactoryError pfe ) { } if (VERBOSE) MatchLocator.verbose("*** New Search for path: " + pathString); //$NON-NLS-1$ try{ parser.parse(); } catch(Exception ex){ if (VERBOSE){ ex.printStackTrace(); } } catch(VirtualMachineError vmErr){ if (VERBOSE){ MatchLocator.verbose("MatchLocator VM Error: "); //$NON-NLS-1$ vmErr.printStackTrace(); } } finally { scopeStack.clear(); resourceStack.clear(); lastDeclaration = null; currentScope = null; parser = null; } if( matchStorage.size() > 0 ){ AcceptMatchOperation acceptMatchOp = new AcceptMatchOperation( resultCollector, matchStorage ); try { CCorePlugin.getWorkspace().run(acceptMatchOp,null); } catch (CoreException e) {} matchStorage.clear(); } } }
diff --git a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/DefaultProjectClasspathEntry.java b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/DefaultProjectClasspathEntry.java index f1fbdfeb5..1b9ba6544 100644 --- a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/DefaultProjectClasspathEntry.java +++ b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/DefaultProjectClasspathEntry.java @@ -1,350 +1,354 @@ /******************************************************************************* * Copyright (c) 2000, 2005 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.jdt.internal.launching; import com.ibm.icu.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jdt.core.ClasspathContainerInitializer; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.IRuntimeClasspathEntry; import org.eclipse.jdt.launching.IRuntimeContainerComparator; import org.eclipse.jdt.launching.JavaRuntime; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Default user classpath entries for a Java project */ public class DefaultProjectClasspathEntry extends AbstractRuntimeClasspathEntry { public static final String TYPE_ID = "org.eclipse.jdt.launching.classpathentry.defaultClasspath"; //$NON-NLS-1$ /** * Whether only exported entries should be on the runtime classpath. * By default all entries are on the runtime classpath. */ private boolean fExportedEntriesOnly = false; /** * Default constructor need to instantiate extensions */ public DefaultProjectClasspathEntry() { } /** * Constructs a new classpath entry for the given project. * * @param project Java project */ public DefaultProjectClasspathEntry(IJavaProject project) { setJavaProject(project); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.launching.AbstractRuntimeClasspathEntry#buildMemento(org.w3c.dom.Document, org.w3c.dom.Element) */ protected void buildMemento(Document document, Element memento) throws CoreException { memento.setAttribute("project", getJavaProject().getElementName()); //$NON-NLS-1$ memento.setAttribute("exportedEntriesOnly", Boolean.toString(fExportedEntriesOnly)); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#initializeFrom(org.w3c.dom.Element) */ public void initializeFrom(Element memento) throws CoreException { String name = memento.getAttribute("project"); //$NON-NLS-1$ if (name == null) { abort(LaunchingMessages.DefaultProjectClasspathEntry_3, null); } IJavaProject project = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(name)); setJavaProject(project); name = memento.getAttribute("exportedEntriesOnly"); //$NON-NLS-1$ if (name == null) { fExportedEntriesOnly = false; } else { fExportedEntriesOnly = Boolean.valueOf(name).booleanValue(); } } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#getTypeId() */ public String getTypeId() { return TYPE_ID; } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry#getType() */ public int getType() { return OTHER; } protected IProject getProject() { return getJavaProject().getProject(); } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry#getLocation() */ public String getLocation() { return getProject().getLocation().toOSString(); } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry#getPath() */ public IPath getPath() { return getProject().getFullPath(); } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry#getResource() */ public IResource getResource() { return getProject(); } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#getRuntimeClasspathEntries(org.eclipse.debug.core.ILaunchConfiguration) */ public IRuntimeClasspathEntry[] getRuntimeClasspathEntries(ILaunchConfiguration configuration) throws CoreException { IClasspathEntry entry = JavaCore.newProjectEntry(getJavaProject().getProject().getFullPath()); List classpathEntries = new ArrayList(5); List expanding = new ArrayList(5); expandProject(entry, classpathEntries, expanding); IRuntimeClasspathEntry[] runtimeEntries = new IRuntimeClasspathEntry[classpathEntries.size()]; for (int i = 0; i < runtimeEntries.length; i++) { Object e = classpathEntries.get(i); if (e instanceof IClasspathEntry) { IClasspathEntry cpe = (IClasspathEntry)e; runtimeEntries[i] = new RuntimeClasspathEntry(cpe); } else { runtimeEntries[i] = (IRuntimeClasspathEntry)e; } } // remove bootpath entries - this is a default user classpath List ordered = new ArrayList(runtimeEntries.length); for (int i = 0; i < runtimeEntries.length; i++) { if (runtimeEntries[i].getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES) { ordered.add(runtimeEntries[i]); } } return (IRuntimeClasspathEntry[]) ordered.toArray(new IRuntimeClasspathEntry[ordered.size()]); } /** * Returns the transitive closure of classpath entries for the * given project entry. * * @param projectEntry project classpath entry * @param expandedPath a list of entries already expanded, should be empty * to begin, and contains the result * @param expanding a list of projects that have been or are currently being * expanded (to detect cycles) * @exception CoreException if unable to expand the classpath */ private void expandProject(IClasspathEntry projectEntry, List expandedPath, List expanding) throws CoreException { expanding.add(projectEntry); // 1. Get the raw classpath // 2. Replace source folder entries with a project entry IPath projectPath = projectEntry.getPath(); IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(projectPath.lastSegment()); if (res == null) { // add project entry and return expandedPath.add(projectEntry); return; } IJavaProject project = (IJavaProject)JavaCore.create(res); if (project == null || !project.getProject().isOpen() || !project.exists()) { // add project entry and return expandedPath.add(projectEntry); return; } IClasspathEntry[] buildPath = project.getRawClasspath(); List unexpandedPath = new ArrayList(buildPath.length); boolean projectAdded = false; for (int i = 0; i < buildPath.length; i++) { IClasspathEntry classpathEntry = buildPath[i]; if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!projectAdded) { projectAdded = true; unexpandedPath.add(projectEntry); } } else { // add exported entires, as configured if (classpathEntry.isExported()) { unexpandedPath.add(classpathEntry); } else if (!isExportedEntriesOnly() || project.equals(getJavaProject())) { // add non exported entries from root project or if we are including all entries unexpandedPath.add(classpathEntry); } } } // 3. expand each project entry (except for the root project) // 4. replace each container entry with a runtime entry associated with the project Iterator iter = unexpandedPath.iterator(); while (iter.hasNext()) { IClasspathEntry entry = (IClasspathEntry)iter.next(); if (entry == projectEntry) { expandedPath.add(entry); } else { switch (entry.getEntryKind()) { case IClasspathEntry.CPE_PROJECT: if (!expanding.contains(entry)) { expandProject(entry, expandedPath, expanding); } break; case IClasspathEntry.CPE_CONTAINER: IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project); int property = -1; if (container != null) { switch (container.getKind()) { case IClasspathContainer.K_APPLICATION: property = IRuntimeClasspathEntry.USER_CLASSES; break; case IClasspathContainer.K_DEFAULT_SYSTEM: property = IRuntimeClasspathEntry.STANDARD_CLASSES; break; case IClasspathContainer.K_SYSTEM: property = IRuntimeClasspathEntry.BOOTSTRAP_CLASSES; break; } IRuntimeClasspathEntry r = JavaRuntime.newRuntimeContainerClasspathEntry(entry.getPath(), property, project); // check for duplicate/redundant entries boolean duplicate = false; ClasspathContainerInitializer initializer = JavaCore.getClasspathContainerInitializer(r.getPath().segment(0)); for (int i = 0; i < expandedPath.size(); i++) { Object o = expandedPath.get(i); if (o instanceof IRuntimeClasspathEntry) { IRuntimeClasspathEntry re = (IRuntimeClasspathEntry)o; if (re.getType() == IRuntimeClasspathEntry.CONTAINER) { if (container instanceof IRuntimeContainerComparator) { duplicate = ((IRuntimeContainerComparator)container).isDuplicate(re.getPath()); } else { ClasspathContainerInitializer initializer2 = JavaCore.getClasspathContainerInitializer(re.getPath().segment(0)); Object id1 = null; Object id2 = null; if (initializer == null) { id1 = r.getPath().segment(0); } else { id1 = initializer.getComparisonID(r.getPath(), project); } if (initializer2 == null) { id2 = re.getPath().segment(0); } else { - id2 = initializer2.getComparisonID(re.getPath(), project); + IJavaProject context = re.getJavaProject(); + if (context == null) { + context = project; + } + id2 = initializer2.getComparisonID(re.getPath(), context); } if (id1 == null) { duplicate = id2 == null; } else { duplicate = id1.equals(id2); } } if (duplicate) { break; } } } } if (!duplicate) { expandedPath.add(r); } } break; case IClasspathEntry.CPE_VARIABLE: if (entry.getPath().segment(0).equals(JavaRuntime.JRELIB_VARIABLE)) { IRuntimeClasspathEntry r = JavaRuntime.newVariableRuntimeClasspathEntry(entry.getPath()); r.setSourceAttachmentPath(entry.getSourceAttachmentPath()); r.setSourceAttachmentRootPath(entry.getSourceAttachmentRootPath()); r.setClasspathProperty(IRuntimeClasspathEntry.STANDARD_CLASSES); if (!expandedPath.contains(r)) { expandedPath.add(r); } break; } // fall through if not the special JRELIB variable default: if (!expandedPath.contains(entry)) { expandedPath.add(entry); } break; } } } return; } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#isComposite() */ public boolean isComposite() { return true; } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#getName() */ public String getName() { if (isExportedEntriesOnly()) { return MessageFormat.format(LaunchingMessages.DefaultProjectClasspathEntry_2, new String[] {getJavaProject().getElementName()}); } return MessageFormat.format(LaunchingMessages.DefaultProjectClasspathEntry_4, new String[] {getJavaProject().getElementName()}); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (obj instanceof DefaultProjectClasspathEntry) { DefaultProjectClasspathEntry entry = (DefaultProjectClasspathEntry) obj; return entry.getJavaProject().equals(getJavaProject()) && entry.isExportedEntriesOnly() == isExportedEntriesOnly(); } return false; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return getJavaProject().hashCode(); } /** * Sets whether the runtime classpath computaion should only * include exported entries in referenced projects. * * @param exportedOnly * @since 3.2 */ public void setExportedEntriesOnly(boolean exportedOnly) { fExportedEntriesOnly = exportedOnly; } /** * Returns whether the classpath computation only includes exported * entries in referenced projects. * * @return * @since 3.2 */ public boolean isExportedEntriesOnly() { return fExportedEntriesOnly; } }
true
true
private void expandProject(IClasspathEntry projectEntry, List expandedPath, List expanding) throws CoreException { expanding.add(projectEntry); // 1. Get the raw classpath // 2. Replace source folder entries with a project entry IPath projectPath = projectEntry.getPath(); IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(projectPath.lastSegment()); if (res == null) { // add project entry and return expandedPath.add(projectEntry); return; } IJavaProject project = (IJavaProject)JavaCore.create(res); if (project == null || !project.getProject().isOpen() || !project.exists()) { // add project entry and return expandedPath.add(projectEntry); return; } IClasspathEntry[] buildPath = project.getRawClasspath(); List unexpandedPath = new ArrayList(buildPath.length); boolean projectAdded = false; for (int i = 0; i < buildPath.length; i++) { IClasspathEntry classpathEntry = buildPath[i]; if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!projectAdded) { projectAdded = true; unexpandedPath.add(projectEntry); } } else { // add exported entires, as configured if (classpathEntry.isExported()) { unexpandedPath.add(classpathEntry); } else if (!isExportedEntriesOnly() || project.equals(getJavaProject())) { // add non exported entries from root project or if we are including all entries unexpandedPath.add(classpathEntry); } } } // 3. expand each project entry (except for the root project) // 4. replace each container entry with a runtime entry associated with the project Iterator iter = unexpandedPath.iterator(); while (iter.hasNext()) { IClasspathEntry entry = (IClasspathEntry)iter.next(); if (entry == projectEntry) { expandedPath.add(entry); } else { switch (entry.getEntryKind()) { case IClasspathEntry.CPE_PROJECT: if (!expanding.contains(entry)) { expandProject(entry, expandedPath, expanding); } break; case IClasspathEntry.CPE_CONTAINER: IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project); int property = -1; if (container != null) { switch (container.getKind()) { case IClasspathContainer.K_APPLICATION: property = IRuntimeClasspathEntry.USER_CLASSES; break; case IClasspathContainer.K_DEFAULT_SYSTEM: property = IRuntimeClasspathEntry.STANDARD_CLASSES; break; case IClasspathContainer.K_SYSTEM: property = IRuntimeClasspathEntry.BOOTSTRAP_CLASSES; break; } IRuntimeClasspathEntry r = JavaRuntime.newRuntimeContainerClasspathEntry(entry.getPath(), property, project); // check for duplicate/redundant entries boolean duplicate = false; ClasspathContainerInitializer initializer = JavaCore.getClasspathContainerInitializer(r.getPath().segment(0)); for (int i = 0; i < expandedPath.size(); i++) { Object o = expandedPath.get(i); if (o instanceof IRuntimeClasspathEntry) { IRuntimeClasspathEntry re = (IRuntimeClasspathEntry)o; if (re.getType() == IRuntimeClasspathEntry.CONTAINER) { if (container instanceof IRuntimeContainerComparator) { duplicate = ((IRuntimeContainerComparator)container).isDuplicate(re.getPath()); } else { ClasspathContainerInitializer initializer2 = JavaCore.getClasspathContainerInitializer(re.getPath().segment(0)); Object id1 = null; Object id2 = null; if (initializer == null) { id1 = r.getPath().segment(0); } else { id1 = initializer.getComparisonID(r.getPath(), project); } if (initializer2 == null) { id2 = re.getPath().segment(0); } else { id2 = initializer2.getComparisonID(re.getPath(), project); } if (id1 == null) { duplicate = id2 == null; } else { duplicate = id1.equals(id2); } } if (duplicate) { break; } } } } if (!duplicate) { expandedPath.add(r); } } break; case IClasspathEntry.CPE_VARIABLE: if (entry.getPath().segment(0).equals(JavaRuntime.JRELIB_VARIABLE)) { IRuntimeClasspathEntry r = JavaRuntime.newVariableRuntimeClasspathEntry(entry.getPath()); r.setSourceAttachmentPath(entry.getSourceAttachmentPath()); r.setSourceAttachmentRootPath(entry.getSourceAttachmentRootPath()); r.setClasspathProperty(IRuntimeClasspathEntry.STANDARD_CLASSES); if (!expandedPath.contains(r)) { expandedPath.add(r); } break; } // fall through if not the special JRELIB variable default: if (!expandedPath.contains(entry)) { expandedPath.add(entry); } break; } } } return; }
private void expandProject(IClasspathEntry projectEntry, List expandedPath, List expanding) throws CoreException { expanding.add(projectEntry); // 1. Get the raw classpath // 2. Replace source folder entries with a project entry IPath projectPath = projectEntry.getPath(); IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(projectPath.lastSegment()); if (res == null) { // add project entry and return expandedPath.add(projectEntry); return; } IJavaProject project = (IJavaProject)JavaCore.create(res); if (project == null || !project.getProject().isOpen() || !project.exists()) { // add project entry and return expandedPath.add(projectEntry); return; } IClasspathEntry[] buildPath = project.getRawClasspath(); List unexpandedPath = new ArrayList(buildPath.length); boolean projectAdded = false; for (int i = 0; i < buildPath.length; i++) { IClasspathEntry classpathEntry = buildPath[i]; if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!projectAdded) { projectAdded = true; unexpandedPath.add(projectEntry); } } else { // add exported entires, as configured if (classpathEntry.isExported()) { unexpandedPath.add(classpathEntry); } else if (!isExportedEntriesOnly() || project.equals(getJavaProject())) { // add non exported entries from root project or if we are including all entries unexpandedPath.add(classpathEntry); } } } // 3. expand each project entry (except for the root project) // 4. replace each container entry with a runtime entry associated with the project Iterator iter = unexpandedPath.iterator(); while (iter.hasNext()) { IClasspathEntry entry = (IClasspathEntry)iter.next(); if (entry == projectEntry) { expandedPath.add(entry); } else { switch (entry.getEntryKind()) { case IClasspathEntry.CPE_PROJECT: if (!expanding.contains(entry)) { expandProject(entry, expandedPath, expanding); } break; case IClasspathEntry.CPE_CONTAINER: IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project); int property = -1; if (container != null) { switch (container.getKind()) { case IClasspathContainer.K_APPLICATION: property = IRuntimeClasspathEntry.USER_CLASSES; break; case IClasspathContainer.K_DEFAULT_SYSTEM: property = IRuntimeClasspathEntry.STANDARD_CLASSES; break; case IClasspathContainer.K_SYSTEM: property = IRuntimeClasspathEntry.BOOTSTRAP_CLASSES; break; } IRuntimeClasspathEntry r = JavaRuntime.newRuntimeContainerClasspathEntry(entry.getPath(), property, project); // check for duplicate/redundant entries boolean duplicate = false; ClasspathContainerInitializer initializer = JavaCore.getClasspathContainerInitializer(r.getPath().segment(0)); for (int i = 0; i < expandedPath.size(); i++) { Object o = expandedPath.get(i); if (o instanceof IRuntimeClasspathEntry) { IRuntimeClasspathEntry re = (IRuntimeClasspathEntry)o; if (re.getType() == IRuntimeClasspathEntry.CONTAINER) { if (container instanceof IRuntimeContainerComparator) { duplicate = ((IRuntimeContainerComparator)container).isDuplicate(re.getPath()); } else { ClasspathContainerInitializer initializer2 = JavaCore.getClasspathContainerInitializer(re.getPath().segment(0)); Object id1 = null; Object id2 = null; if (initializer == null) { id1 = r.getPath().segment(0); } else { id1 = initializer.getComparisonID(r.getPath(), project); } if (initializer2 == null) { id2 = re.getPath().segment(0); } else { IJavaProject context = re.getJavaProject(); if (context == null) { context = project; } id2 = initializer2.getComparisonID(re.getPath(), context); } if (id1 == null) { duplicate = id2 == null; } else { duplicate = id1.equals(id2); } } if (duplicate) { break; } } } } if (!duplicate) { expandedPath.add(r); } } break; case IClasspathEntry.CPE_VARIABLE: if (entry.getPath().segment(0).equals(JavaRuntime.JRELIB_VARIABLE)) { IRuntimeClasspathEntry r = JavaRuntime.newVariableRuntimeClasspathEntry(entry.getPath()); r.setSourceAttachmentPath(entry.getSourceAttachmentPath()); r.setSourceAttachmentRootPath(entry.getSourceAttachmentRootPath()); r.setClasspathProperty(IRuntimeClasspathEntry.STANDARD_CLASSES); if (!expandedPath.contains(r)) { expandedPath.add(r); } break; } // fall through if not the special JRELIB variable default: if (!expandedPath.contains(entry)) { expandedPath.add(entry); } break; } } } return; }
diff --git a/org.kevoree.microsandbox.watchdog/src/main/java/org/kevoree/watchdog/child/jvm/LocateRuntimeJar.java b/org.kevoree.microsandbox.watchdog/src/main/java/org/kevoree/watchdog/child/jvm/LocateRuntimeJar.java index ab561c3..e744c9b 100644 --- a/org.kevoree.microsandbox.watchdog/src/main/java/org/kevoree/watchdog/child/jvm/LocateRuntimeJar.java +++ b/org.kevoree.microsandbox.watchdog/src/main/java/org/kevoree/watchdog/child/jvm/LocateRuntimeJar.java @@ -1,41 +1,41 @@ package org.kevoree.watchdog.child.jvm; import java.io.File; import java.io.InputStream; /** * Created with IntelliJ IDEA. * User: duke * Date: 04/07/13 * Time: 15:41 */ public class LocateRuntimeJar { public static File locateRuntimeJar(){ if(System.getProperty("os.name").toLowerCase().contains("mac")){ try { Process p = Runtime.getRuntime().exec("/usr/libexec/java_home"); InputStream rin = p.getInputStream(); p.waitFor(); String path = ""; while(rin.available() > 0){ char c = (char) rin.read(); path = path + c; } File classes = new File(path.trim()+File.separator+"classes"+File.separator+"classes.jar"); return classes; } catch (Exception e) { e.printStackTrace(); } } else { //TODO for unix, I just want to see this working - return new File("/usr/lib/jvm/java-1.7.0-openjdk-i386/jre/lib/rt.jar"); + return new File(System.getProperty("java.home") + File.separator + "lib" + File.separator + "rt.jar"); } return null; } }
true
true
public static File locateRuntimeJar(){ if(System.getProperty("os.name").toLowerCase().contains("mac")){ try { Process p = Runtime.getRuntime().exec("/usr/libexec/java_home"); InputStream rin = p.getInputStream(); p.waitFor(); String path = ""; while(rin.available() > 0){ char c = (char) rin.read(); path = path + c; } File classes = new File(path.trim()+File.separator+"classes"+File.separator+"classes.jar"); return classes; } catch (Exception e) { e.printStackTrace(); } } else { //TODO for unix, I just want to see this working return new File("/usr/lib/jvm/java-1.7.0-openjdk-i386/jre/lib/rt.jar"); } return null; }
public static File locateRuntimeJar(){ if(System.getProperty("os.name").toLowerCase().contains("mac")){ try { Process p = Runtime.getRuntime().exec("/usr/libexec/java_home"); InputStream rin = p.getInputStream(); p.waitFor(); String path = ""; while(rin.available() > 0){ char c = (char) rin.read(); path = path + c; } File classes = new File(path.trim()+File.separator+"classes"+File.separator+"classes.jar"); return classes; } catch (Exception e) { e.printStackTrace(); } } else { //TODO for unix, I just want to see this working return new File(System.getProperty("java.home") + File.separator + "lib" + File.separator + "rt.jar"); } return null; }
diff --git a/src/test/java/org/apache/hadoop/hbase/client/TestShell.java b/src/test/java/org/apache/hadoop/hbase/client/TestShell.java index 71fe1d9b1..5524ed865 100644 --- a/src/test/java/org/apache/hadoop/hbase/client/TestShell.java +++ b/src/test/java/org/apache/hadoop/hbase/client/TestShell.java @@ -1,71 +1,72 @@ /** * Copyright 2009 The Apache Software Foundation * * 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.hadoop.hbase.client; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.LargeTests; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.jruby.embed.ScriptingContainer; import org.jruby.embed.PathType; import org.junit.experimental.categories.Category; @Category(LargeTests.class) public class TestShell { final Log LOG = LogFactory.getLog(getClass()); private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private final static ScriptingContainer jruby = new ScriptingContainer(); @BeforeClass public static void setUpBeforeClass() throws Exception { // Start mini cluster + TEST_UTIL.getConfiguration().setBoolean("hbase.online.schema.update.enable", true); TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100); TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250); TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6); TEST_UTIL.startMiniCluster(); // Configure jruby runtime List<String> loadPaths = new ArrayList(); loadPaths.add("src/main/ruby"); loadPaths.add("src/test/ruby"); jruby.getProvider().setLoadPaths(loadPaths); jruby.put("$TEST_CLUSTER", TEST_UTIL); } @AfterClass public static void tearDownAfterClass() throws Exception { TEST_UTIL.shutdownMiniCluster(); } @Test public void testRunShellTests() throws IOException { // Start all ruby tests jruby.runScriptlet(PathType.ABSOLUTE, "src/test/ruby/tests_runner.rb"); } }
true
true
public static void setUpBeforeClass() throws Exception { // Start mini cluster TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100); TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250); TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6); TEST_UTIL.startMiniCluster(); // Configure jruby runtime List<String> loadPaths = new ArrayList(); loadPaths.add("src/main/ruby"); loadPaths.add("src/test/ruby"); jruby.getProvider().setLoadPaths(loadPaths); jruby.put("$TEST_CLUSTER", TEST_UTIL); }
public static void setUpBeforeClass() throws Exception { // Start mini cluster TEST_UTIL.getConfiguration().setBoolean("hbase.online.schema.update.enable", true); TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100); TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250); TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6); TEST_UTIL.startMiniCluster(); // Configure jruby runtime List<String> loadPaths = new ArrayList(); loadPaths.add("src/main/ruby"); loadPaths.add("src/test/ruby"); jruby.getProvider().setLoadPaths(loadPaths); jruby.put("$TEST_CLUSTER", TEST_UTIL); }
diff --git a/src/edu/ucla/cens/awserver/validator/AnnotatingValidator.java b/src/edu/ucla/cens/awserver/validator/AnnotatingValidator.java index 4bc7b70d..bcdfa190 100644 --- a/src/edu/ucla/cens/awserver/validator/AnnotatingValidator.java +++ b/src/edu/ucla/cens/awserver/validator/AnnotatingValidator.java @@ -1,25 +1,25 @@ package edu.ucla.cens.awserver.validator; /** * Abstract base class for Validators which need to annotate an AwRequest as part of their processing. * * @author selsky */ public abstract class AnnotatingValidator implements Validator { private AnnotateAwRequestStrategy _annotatingValidationStrategy; /** * @throws IllegalArgumentException if the provided AnnotateAwRequestStrategy is null */ public AnnotatingValidator(AnnotateAwRequestStrategy annotatingValidationStrategy) { if(null == annotatingValidationStrategy) { - throw new IllegalArgumentException("a AnnotateAwRequestStrategy is required"); + throw new IllegalArgumentException("an AnnotateAwRequestStrategy is required"); } _annotatingValidationStrategy = annotatingValidationStrategy; } protected AnnotateAwRequestStrategy getAnnotator() { return _annotatingValidationStrategy; } }
true
true
public AnnotatingValidator(AnnotateAwRequestStrategy annotatingValidationStrategy) { if(null == annotatingValidationStrategy) { throw new IllegalArgumentException("a AnnotateAwRequestStrategy is required"); } _annotatingValidationStrategy = annotatingValidationStrategy; }
public AnnotatingValidator(AnnotateAwRequestStrategy annotatingValidationStrategy) { if(null == annotatingValidationStrategy) { throw new IllegalArgumentException("an AnnotateAwRequestStrategy is required"); } _annotatingValidationStrategy = annotatingValidationStrategy; }
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/configure/ui/ConfigureRuleMediatorResultsDialog.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/configure/ui/ConfigureRuleMediatorResultsDialog.java index 3e254af01..dafee2588 100755 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/configure/ui/ConfigureRuleMediatorResultsDialog.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/configure/ui/ConfigureRuleMediatorResultsDialog.java @@ -1,599 +1,600 @@ /* * Copyright 2012 WSO2, Inc. (http://wso2.com) * * 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.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.configure.ui; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.common.command.CompoundCommand; import org.eclipse.emf.edit.command.AddCommand; import org.eclipse.emf.edit.command.RemoveCommand; import org.eclipse.emf.edit.command.SetCommand; import org.eclipse.emf.transaction.TransactionalEditingDomain; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.wso2.developerstudio.eclipse.esb.core.Activator; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage; import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty; import org.wso2.developerstudio.eclipse.gmf.esb.RegistryKeyProperty; import org.wso2.developerstudio.eclipse.gmf.esb.RuleMediator; import org.wso2.developerstudio.eclipse.gmf.esb.RuleResult; import org.wso2.developerstudio.eclipse.gmf.esb.RuleResultType; import org.wso2.developerstudio.eclipse.gmf.esb.RuleResultValueType; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; /** * RuleMediator results configuration *dialog * */ public class ConfigureRuleMediatorResultsDialog extends TitleAreaDialog { /** * logger */ private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID); /** * Domain model */ private RuleMediator ruleMediator; /** * Editing domain. */ private TransactionalEditingDomain editingDomain; /** * Command for recording user operations. */ private CompoundCommand resultCommand; /** * UI widgets */ private Table tblResults; private Button cmdResultAdd; private Button cmdResultRemove; private Combo cmbType; private Text txtName; private Combo cmbTargetType; private PropertyText txtValue; /** * table editors */ private TableEditor typeEditor; private TableEditor nameEditor; private TableEditor targetTypeEditor; private TableEditor valueEditor; private final static String LITERAL_VALUE = "Literal"; private final static String LITERAL_EXPRESSION = "Expression"; private final static String LITERAL_KEY = "Key"; private List<String> resultTypes = new ArrayList<String>(); public ConfigureRuleMediatorResultsDialog(Shell parentShell,RuleMediator ruleMediator, TransactionalEditingDomain editingDomain) { super(parentShell); this.ruleMediator = ruleMediator; this.editingDomain = editingDomain; } /** * Create contents of the *dialog. * @param parent */ @Override protected Control createDialogArea(Composite parent) { setTitle("Results Configuration"); setMessage("Results describes what should do with return values form the rule execution."); Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayoutData(new GridData(GridData.FILL_BOTH)); tblResults = new Table(container, SWT.BORDER | SWT.FULL_SELECTION); tblResults.setBounds(10, 10, 510, 222); tblResults.setHeaderVisible(true); tblResults.setLinesVisible(true); tblResults.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (null != e.item) { if (e.item instanceof TableItem) { TableItem item = (TableItem) e.item; editItem(item); cmdResultRemove.setEnabled(true); } } else{ cmdResultRemove.setEnabled(false); updateSelection(); } } }); TableColumn tblclmnType = new TableColumn(tblResults, SWT.NONE); tblclmnType.setWidth(100); tblclmnType.setText("Type"); TableColumn tblclmnName = new TableColumn(tblResults, SWT.NONE); tblclmnName.setWidth(111); tblclmnName.setText("Name"); TableColumn tblclmnTargetType = new TableColumn(tblResults, SWT.NONE); tblclmnTargetType.setWidth(100); tblclmnTargetType.setText("Target Type"); TableColumn tblclmnValue = new TableColumn(tblResults, SWT.NONE); tblclmnValue.setWidth(192); tblclmnValue.setText("Value"); cmdResultAdd = new Button(container, SWT.NONE); cmdResultAdd.setBounds(527, 10, 86, 29); cmdResultAdd.setText("Add"); cmdResultAdd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { RuleResult result = EsbFactory.eINSTANCE.createRuleResult(); ResultWrapper wrapper = new ResultWrapper(result); wrapper.setResultName(result.getResultName()); wrapper.setResultCustomType(result.getResultCustomType()); wrapper.setResultType(result.getResultType()); wrapper.setValueType(result.getValueType()); wrapper.setValueLiteral(result.getValueLiteral()); wrapper.setValueExpression(EsbFactory.eINSTANCE.copyNamespacedProperty(result.getValueExpression())); wrapper.setValueKey(EsbFactory.eINSTANCE.copyRegistryKeyProperty(result.getValueKey())); bindResult(wrapper); } }); cmdResultRemove = new Button(container, SWT.NONE); cmdResultRemove.setBounds(526, 45, 86, 29); cmdResultRemove.setText("Remove"); + cmdResultRemove.setEnabled(false); cmdResultRemove.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { int selectedIndex = tblResults.getSelectionIndex(); if (-1 != selectedIndex) { unbindResult(selectedIndex); // Select the next available candidate for deletion. if (selectedIndex < tblResults.getItemCount()) { tblResults.select(selectedIndex); } else { tblResults.select(selectedIndex - 1); } updateSelection(); } } }); for(RuleResultType ruleResultType : RuleResultType.VALUES){ if(ruleResultType!=RuleResultType.CUSTOM){ resultTypes.add(ruleResultType.getLiteral()); } } for(RuleResult result : ruleMediator.getResultsConfiguration().getResults()){ ResultWrapper wrapper = new ResultWrapper(result); wrapper.setResultName(result.getResultName()); wrapper.setResultCustomType(result.getResultCustomType()); wrapper.setResultType(result.getResultType()); wrapper.setValueType(result.getValueType()); wrapper.setValueLiteral(result.getValueLiteral()); wrapper.setValueExpression(EsbFactory.eINSTANCE.copyNamespacedProperty(result.getValueExpression())); wrapper.setValueKey(EsbFactory.eINSTANCE.copyRegistryKeyProperty(result.getValueKey())); bindResult(wrapper); } return area; } /** * Create contents of the button bar. * @param parent */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the *dialog. */ @Override protected Point getInitialSize() { return new Point(631, 400); } protected void editItem(final TableItem item) { final ResultWrapper wrapper = (ResultWrapper) item.getData(); typeEditor = initTableEditor(typeEditor, item.getParent()); cmbType = new Combo(item.getParent(),SWT.NONE); cmbType.setItems(resultTypes.toArray(new String[]{})); cmbType.setText(item.getText(0)); typeEditor.setEditor(cmbType, item, 0); item.getParent().redraw(); item.getParent().layout(); Listener cmbTypeListener = new Listener() { public void handleEvent(Event evt) { String text = cmbType.getText(); item.setText(0, text); if(RuleResultType.DOM.getLiteral().equals(text)){ wrapper.setResultType(RuleResultType.DOM); } else if(RuleResultType.MESSAGE.getLiteral().equals(text)){ wrapper.setResultType(RuleResultType.MESSAGE); } else if(RuleResultType.CONTEXT.getLiteral().equals(text)){ wrapper.setResultType(RuleResultType.CONTEXT); } else if(RuleResultType.OMELEMENT.getLiteral().equals(text)){ wrapper.setResultType(RuleResultType.OMELEMENT); } else if(RuleResultType.MEDIATOR.getLiteral().equals(text)){ wrapper.setResultType(RuleResultType.MEDIATOR); } else{ wrapper.setResultType(RuleResultType.CUSTOM); wrapper.setResultCustomType(text); } } }; cmbType.addListener(SWT.Selection, cmbTypeListener); cmbType.addListener(SWT.Modify, cmbTypeListener); nameEditor = initTableEditor(nameEditor, item.getParent()); txtName = new Text(item.getParent(),SWT.NONE); txtName.setText(item.getText(1)); nameEditor.setEditor(txtName, item, 1); item.getParent().redraw(); item.getParent().layout(); txtName.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { item.setText(1, txtName.getText()); wrapper.setResultName(txtName.getText()); } }); targetTypeEditor = initTableEditor(targetTypeEditor, item.getParent()); cmbTargetType = new Combo(item.getParent(), SWT.READ_ONLY); cmbTargetType.setItems(new String[] { LITERAL_VALUE, LITERAL_EXPRESSION,LITERAL_KEY }); cmbTargetType.setText(item.getText(2)); targetTypeEditor.setEditor(cmbTargetType, item, 2); item.getParent().redraw(); item.getParent().layout(); cmbTargetType.addListener(SWT.Selection, new Listener() { public void handleEvent(Event evt) { item.setText(2, cmbTargetType.getText()); if(cmbTargetType.getSelectionIndex()==2){ item.setText(3,wrapper.getValueKey().getKeyValue()); wrapper.setValueType(RuleResultValueType.REGISTRY_REFERENCE); } else if(cmbTargetType.getSelectionIndex()==1){ item.setText(3,wrapper.getValueExpression().getPropertyValue()); wrapper.setValueType(RuleResultValueType.EXPRESSION); } else{ wrapper.setValueType(RuleResultValueType.LITERAL); item.setText(3,wrapper.getValueLiteral()); } } }); valueEditor = initTableEditor(valueEditor, item.getParent()); txtValue = new PropertyText(item.getParent(), SWT.NONE, cmbTargetType); txtValue.addProperties(wrapper.getValueLiteral(),wrapper.getValueExpression(),wrapper.getValueKey()); valueEditor.setEditor(txtValue, item, 3); item.getParent().redraw(); item.getParent().layout(); txtValue.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { item.setText(3,txtValue.getText()); Object property = txtValue.getProperty(); if(property instanceof RegistryKeyProperty){ wrapper.setValueKey((RegistryKeyProperty)property); } else if(property instanceof NamespacedProperty){ wrapper.setValueExpression((NamespacedProperty)property); } else{ wrapper.setValueLiteral(property.toString()); } } }); } private void updateSelection(){ initTableEditor(typeEditor,tblResults); initTableEditor(nameEditor,tblResults); initTableEditor(targetTypeEditor,tblResults); initTableEditor(valueEditor,tblResults); if(tblResults.getSelectionIndex()==-1){ cmdResultRemove.setEnabled(false); } else{ cmdResultRemove.setEnabled(true); } } /** * {@inheritDoc} */ protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("RuleMediator Configuration"); } private TableEditor initTableEditor(TableEditor editor, Table table) { if (null != editor) { Control lastCtrl = editor.getEditor(); if (null != lastCtrl) { lastCtrl.dispose(); } } editor = new TableEditor(table); editor.horizontalAlignment = SWT.LEFT; editor.grabHorizontal = true; return editor; } /** * Utility method for binding a result into the UI. Note that this * method does not record any commands, it simply adds a new row into the * table and associates the passed {@link RuleResult} to it. * * @return {@link TableItem} which was introduced. */ private TableItem bindResult(ResultWrapper wrapper) { TableItem item = new TableItem(tblResults, SWT.NONE); if(wrapper.getResultType()==RuleResultType.CUSTOM){ item.setText(0, wrapper.getResultCustomType()); } else{ item.setText(0, wrapper.getResultType().getLiteral()); } item.setText(1, wrapper.getResultName()); if(wrapper.getValueType()==RuleResultValueType.EXPRESSION){ item.setText(2,LITERAL_EXPRESSION); item.setText(3,wrapper.getValueExpression().getPropertyValue()); } else if(wrapper.getValueType()==RuleResultValueType.REGISTRY_REFERENCE){ item.setText(2,LITERAL_KEY); item.setText(3,wrapper.getValueKey().getKeyValue()); } else{ item.setText(2,LITERAL_VALUE); item.setText(3,wrapper.getValueLiteral()); } item.setData(wrapper); return item; } /** * Removes the corresponding table item from the table and records a command * for detaching the corresponding argument from the model. * * @param itemIndex * index of the row which is to be removed. */ private void unbindResult(int itemIndex) { TableItem item = tblResults.getItem(itemIndex); ResultWrapper wrapper = (ResultWrapper) item.getData(); RuleResult result = wrapper.getResult(); if (null != result.eContainer()) { RemoveCommand removeCmd = new RemoveCommand(editingDomain, ruleMediator.getResultsConfiguration(), EsbPackage.Literals.RULE_RESULTS_CONFIGURATION__RESULTS, result); getResultCommand().append(removeCmd); } tblResults.remove(tblResults.indexOf(item)); } @Override protected void okPressed() { for (TableItem item : tblResults.getItems()) { ResultWrapper wrapper = (ResultWrapper) item.getData(); RuleResult result = wrapper.getResult(); AddCommand addCmd = null; if (null == result.eContainer()) { addCmd = new AddCommand(editingDomain, ruleMediator.getResultsConfiguration(), EsbPackage.Literals.RULE_RESULTS_CONFIGURATION__RESULTS, result); getResultCommand().append(addCmd); } SetCommand setCommand = null; if(!result.getResultName().equals(wrapper.getResultName())){ setCommand = new SetCommand(editingDomain, result, EsbPackage.Literals.RULE_RESULT__RESULT_NAME, wrapper.getResultName()); getResultCommand().append(setCommand); } if (!(result.getResultType().equals(wrapper.getResultType()) && result.getResultCustomType() .equals(wrapper.getResultCustomType()))) { String customResultType = "custom_type"; RuleResultType resultType = RuleResultType.CUSTOM; if (wrapper.getResultType() == RuleResultType.CUSTOM) { customResultType = wrapper.getResultCustomType(); } else { resultType = wrapper.getResultType(); } setCommand = new SetCommand(editingDomain, result, EsbPackage.Literals.RULE_RESULT__RESULT_CUSTOM_TYPE, customResultType); getResultCommand().append(setCommand); setCommand = new SetCommand(editingDomain, result, EsbPackage.Literals.RULE_RESULT__RESULT_TYPE, resultType); getResultCommand().append(setCommand); } if(!result.getValueType().equals(wrapper.getValueType())){ if(wrapper.getValueType()==RuleResultValueType.REGISTRY_REFERENCE){ wrapper.setValueLiteral("default"); wrapper.getValueExpression().setPropertyValue("/default/expression"); } else if(wrapper.getValueType()==RuleResultValueType.EXPRESSION){ wrapper.getValueKey().setKeyValue("/default/key"); wrapper.setValueLiteral("default"); } else{ wrapper.getValueExpression().setPropertyValue("/default/expression"); wrapper.setValueLiteral("default"); } setCommand = new SetCommand(editingDomain, result, EsbPackage.Literals.RULE_RESULT__VALUE_TYPE, wrapper.getValueType()); getResultCommand().append(setCommand); } if(!result.getValueLiteral().equals( wrapper.getValueLiteral())){ setCommand = new SetCommand(editingDomain, result, EsbPackage.Literals.RULE_RESULT__VALUE_LITERAL, wrapper.getValueLiteral()); getResultCommand().append(setCommand); } if(!result.getValueExpression().equals(wrapper.getValueExpression())){ setCommand = new SetCommand(editingDomain, result, EsbPackage.Literals.RULE_RESULT__VALUE_EXPRESSION, wrapper.getValueExpression()); getResultCommand().append(setCommand); } if(!result.getValueKey().equals(wrapper.getValueKey())){ setCommand = new SetCommand(editingDomain, result, EsbPackage.Literals.RULE_RESULT__VALUE_KEY, wrapper.getValueKey()); getResultCommand().append(setCommand); } } // Apply changes. if (getResultCommand().canExecute()) { editingDomain.getCommandStack().execute(getResultCommand()); } else { if(getResultCommand().getCommandList().size()>1){ log.error("RuleMediator results configuration : cannot save results", new Exception( "Cannot execute command stack ")); } } super.okPressed(); } /** * Utility method for retrieving the result {@link CompoundCommand} which is * used to record user operations. * * @return result command. */ private CompoundCommand getResultCommand() { if (null == resultCommand) { resultCommand = new CompoundCommand(); } return resultCommand; } /** * Wrapper class for RuleResult * */ class ResultWrapper{ RuleResult result; RuleResultType resultType; String resultCustomType; String resultName; RuleResultValueType valueType; String valueLiteral; NamespacedProperty valueExpression; RegistryKeyProperty valueKey; public ResultWrapper(RuleResult result){ this.result = result; } public RuleResult getResult() { return result; } public void setFact(RuleResult result) { this.result = result; } public RuleResultType getResultType() { return resultType; } public void setResultType(RuleResultType resultType) { this.resultType = resultType; } public String getResultCustomType() { return resultCustomType; } public void setResultCustomType(String resultCustomType) { this.resultCustomType = resultCustomType; } public String getResultName() { return resultName; } public void setResultName(String factName) { this.resultName = factName; } public RuleResultValueType getValueType() { return valueType; } public void setValueType(RuleResultValueType valueType) { this.valueType = valueType; } public String getValueLiteral() { return valueLiteral; } public void setValueLiteral(String valueLiteral) { this.valueLiteral = valueLiteral; } public NamespacedProperty getValueExpression() { return valueExpression; } public void setValueExpression(NamespacedProperty valueExpression) { this.valueExpression = valueExpression; } public RegistryKeyProperty getValueKey() { return valueKey; } public void setValueKey(RegistryKeyProperty valueKey) { this.valueKey = valueKey; } } }
true
true
protected Control createDialogArea(Composite parent) { setTitle("Results Configuration"); setMessage("Results describes what should do with return values form the rule execution."); Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayoutData(new GridData(GridData.FILL_BOTH)); tblResults = new Table(container, SWT.BORDER | SWT.FULL_SELECTION); tblResults.setBounds(10, 10, 510, 222); tblResults.setHeaderVisible(true); tblResults.setLinesVisible(true); tblResults.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (null != e.item) { if (e.item instanceof TableItem) { TableItem item = (TableItem) e.item; editItem(item); cmdResultRemove.setEnabled(true); } } else{ cmdResultRemove.setEnabled(false); updateSelection(); } } }); TableColumn tblclmnType = new TableColumn(tblResults, SWT.NONE); tblclmnType.setWidth(100); tblclmnType.setText("Type"); TableColumn tblclmnName = new TableColumn(tblResults, SWT.NONE); tblclmnName.setWidth(111); tblclmnName.setText("Name"); TableColumn tblclmnTargetType = new TableColumn(tblResults, SWT.NONE); tblclmnTargetType.setWidth(100); tblclmnTargetType.setText("Target Type"); TableColumn tblclmnValue = new TableColumn(tblResults, SWT.NONE); tblclmnValue.setWidth(192); tblclmnValue.setText("Value"); cmdResultAdd = new Button(container, SWT.NONE); cmdResultAdd.setBounds(527, 10, 86, 29); cmdResultAdd.setText("Add"); cmdResultAdd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { RuleResult result = EsbFactory.eINSTANCE.createRuleResult(); ResultWrapper wrapper = new ResultWrapper(result); wrapper.setResultName(result.getResultName()); wrapper.setResultCustomType(result.getResultCustomType()); wrapper.setResultType(result.getResultType()); wrapper.setValueType(result.getValueType()); wrapper.setValueLiteral(result.getValueLiteral()); wrapper.setValueExpression(EsbFactory.eINSTANCE.copyNamespacedProperty(result.getValueExpression())); wrapper.setValueKey(EsbFactory.eINSTANCE.copyRegistryKeyProperty(result.getValueKey())); bindResult(wrapper); } }); cmdResultRemove = new Button(container, SWT.NONE); cmdResultRemove.setBounds(526, 45, 86, 29); cmdResultRemove.setText("Remove"); cmdResultRemove.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { int selectedIndex = tblResults.getSelectionIndex(); if (-1 != selectedIndex) { unbindResult(selectedIndex); // Select the next available candidate for deletion. if (selectedIndex < tblResults.getItemCount()) { tblResults.select(selectedIndex); } else { tblResults.select(selectedIndex - 1); } updateSelection(); } } }); for(RuleResultType ruleResultType : RuleResultType.VALUES){ if(ruleResultType!=RuleResultType.CUSTOM){ resultTypes.add(ruleResultType.getLiteral()); } } for(RuleResult result : ruleMediator.getResultsConfiguration().getResults()){ ResultWrapper wrapper = new ResultWrapper(result); wrapper.setResultName(result.getResultName()); wrapper.setResultCustomType(result.getResultCustomType()); wrapper.setResultType(result.getResultType()); wrapper.setValueType(result.getValueType()); wrapper.setValueLiteral(result.getValueLiteral()); wrapper.setValueExpression(EsbFactory.eINSTANCE.copyNamespacedProperty(result.getValueExpression())); wrapper.setValueKey(EsbFactory.eINSTANCE.copyRegistryKeyProperty(result.getValueKey())); bindResult(wrapper); } return area; }
protected Control createDialogArea(Composite parent) { setTitle("Results Configuration"); setMessage("Results describes what should do with return values form the rule execution."); Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayoutData(new GridData(GridData.FILL_BOTH)); tblResults = new Table(container, SWT.BORDER | SWT.FULL_SELECTION); tblResults.setBounds(10, 10, 510, 222); tblResults.setHeaderVisible(true); tblResults.setLinesVisible(true); tblResults.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (null != e.item) { if (e.item instanceof TableItem) { TableItem item = (TableItem) e.item; editItem(item); cmdResultRemove.setEnabled(true); } } else{ cmdResultRemove.setEnabled(false); updateSelection(); } } }); TableColumn tblclmnType = new TableColumn(tblResults, SWT.NONE); tblclmnType.setWidth(100); tblclmnType.setText("Type"); TableColumn tblclmnName = new TableColumn(tblResults, SWT.NONE); tblclmnName.setWidth(111); tblclmnName.setText("Name"); TableColumn tblclmnTargetType = new TableColumn(tblResults, SWT.NONE); tblclmnTargetType.setWidth(100); tblclmnTargetType.setText("Target Type"); TableColumn tblclmnValue = new TableColumn(tblResults, SWT.NONE); tblclmnValue.setWidth(192); tblclmnValue.setText("Value"); cmdResultAdd = new Button(container, SWT.NONE); cmdResultAdd.setBounds(527, 10, 86, 29); cmdResultAdd.setText("Add"); cmdResultAdd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { RuleResult result = EsbFactory.eINSTANCE.createRuleResult(); ResultWrapper wrapper = new ResultWrapper(result); wrapper.setResultName(result.getResultName()); wrapper.setResultCustomType(result.getResultCustomType()); wrapper.setResultType(result.getResultType()); wrapper.setValueType(result.getValueType()); wrapper.setValueLiteral(result.getValueLiteral()); wrapper.setValueExpression(EsbFactory.eINSTANCE.copyNamespacedProperty(result.getValueExpression())); wrapper.setValueKey(EsbFactory.eINSTANCE.copyRegistryKeyProperty(result.getValueKey())); bindResult(wrapper); } }); cmdResultRemove = new Button(container, SWT.NONE); cmdResultRemove.setBounds(526, 45, 86, 29); cmdResultRemove.setText("Remove"); cmdResultRemove.setEnabled(false); cmdResultRemove.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { int selectedIndex = tblResults.getSelectionIndex(); if (-1 != selectedIndex) { unbindResult(selectedIndex); // Select the next available candidate for deletion. if (selectedIndex < tblResults.getItemCount()) { tblResults.select(selectedIndex); } else { tblResults.select(selectedIndex - 1); } updateSelection(); } } }); for(RuleResultType ruleResultType : RuleResultType.VALUES){ if(ruleResultType!=RuleResultType.CUSTOM){ resultTypes.add(ruleResultType.getLiteral()); } } for(RuleResult result : ruleMediator.getResultsConfiguration().getResults()){ ResultWrapper wrapper = new ResultWrapper(result); wrapper.setResultName(result.getResultName()); wrapper.setResultCustomType(result.getResultCustomType()); wrapper.setResultType(result.getResultType()); wrapper.setValueType(result.getValueType()); wrapper.setValueLiteral(result.getValueLiteral()); wrapper.setValueExpression(EsbFactory.eINSTANCE.copyNamespacedProperty(result.getValueExpression())); wrapper.setValueKey(EsbFactory.eINSTANCE.copyRegistryKeyProperty(result.getValueKey())); bindResult(wrapper); } return area; }
diff --git a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/InstitutionAddAction.java b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/InstitutionAddAction.java index 22a8fbbb3..0614aa095 100644 --- a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/InstitutionAddAction.java +++ b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/InstitutionAddAction.java @@ -1,143 +1,144 @@ package edu.wustl.catissuecore.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.Globals; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import edu.wustl.catissuecore.actionForm.InstitutionForm; import edu.wustl.catissuecore.ctrp.COPPAServiceClient; import edu.wustl.catissuecore.ctrp.COPPAUtil; import edu.wustl.catissuecore.ctrp.CTRPConstants; import edu.wustl.catissuecore.ctrp.CTRPPropertyHandler; import edu.wustl.catissuecore.domain.Institution; import edu.wustl.catissuecore.util.global.AppUtility; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.action.BaseAddEditAction; import edu.wustl.common.action.CommonAddAction; import edu.wustl.common.action.SecureAction; import edu.wustl.common.bizlogic.DefaultBizLogic; import edu.wustl.common.exception.ApplicationException; import edu.wustl.common.factory.AbstractFactoryConfig; import edu.wustl.common.factory.IFactory; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.coppa.po.Organization; public class InstitutionAddAction extends SecureAction { private static final Logger logger = Logger .getCommonLogger(InstitutionAddAction.class); @Override protected ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { BaseAddEditAction addAction; ActionForward actionfwd; try { if ( !isTokenValid(request) ) { ActionErrors actionErrors = new ActionErrors(); ActionError actionError = new ActionError("errors.item","Invalid request for add/edit operation"); actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError); saveErrors(request, actionErrors); return mapping.findForward("failure"); } resetToken(request); boolean coppaMatchFound = false; final InstitutionForm institutionForm = (InstitutionForm) form; // String remoteOperation = institutionForm.getRemoteOperation(); String remoteOperation = request.getParameter("remoteOperation"); // COPPA is enabled and user has not selected remote entity yet. // Check if Remote match exists System.out.println("Institution Add Action:" + "form name:" + institutionForm.getName() + ":form remote operation:" + institutionForm.getRemoteOperation() + ":form remoteid:" + institutionForm.getRemoteId() + ":form remote flag:" + institutionForm.isRemoteManagedFlag() +":request param operation:"+request.getParameter("remoteOperation")); if (COPPAUtil.isCOPPAEnabled() && (Constants.REMOTE_OPERATION_SEARCH .equalsIgnoreCase(remoteOperation))) { try { Organization[] organizationList = null; organizationList = new COPPAServiceClient() .searchOrganization(institutionForm.getName()); if (organizationList != null && organizationList.length > 0) { coppaMatchFound = true; request.setAttribute("COPPA_MATCH_FOUND", "true"); request.getSession().setAttribute("COPPA_ORGANIZATIONS", organizationList); } } catch (Exception e) { logger.error("Failed to look for Organizations in COPPA."); logger.error(e,e); } } if (coppaMatchFound) { // Redirect user to pop-up for selecting remote institution request.setAttribute("operationAdd", Constants.ADD); request.setAttribute("formName", Constants.INSTITUTION_ADD_ACTION); actionfwd = mapping.findForward("pageOfInstitution"); } else { // Either there is no COPPA match or user has already selected // COPPA match or user does not want to do remote link if (institutionForm.getRemoteId() != 0) { // Adding a new remote institution institutionForm.setRemoteManagedFlag(true); institutionForm.setDirtyEditFlag(false); // Get organization details by id Organization org = new COPPAServiceClient() .getOrganizationById("" + institutionForm.getRemoteId()); institutionForm.setName(org.getName().getPart().get(0) .getValue()); } addAction = new CommonAddAction(); logger.info("Insitution Add Action before adding to db:" + "remote id:" + institutionForm.getRemoteId() + "remote flag:" + institutionForm.isRemoteManagedFlag() + "dirty edit flag:" + institutionForm.isDirtyEditFlag() + "name:" + institutionForm.getName()); actionfwd = addAction.executeXSS(mapping, institutionForm, request, response); // over write action succuess message for remote link success if (institutionForm.getRemoteId() != 0) { AppUtility.replaceActionMessage(request, "ctrp.instituion.link.success"); } }// end -if adding user not remote pop-up } catch (ApplicationException applicationException) { logger.error("Institution Add failed.." + applicationException.getCustomizedMsg()); ActionErrors actionErrors = new ActionErrors(); ActionError actionError = new ActionError("errors.item", applicationException.getCustomizedMsg()); actionErrors.add("org.apache.struts.action.GLOBAL_ERROR", actionError); saveErrors(request, actionErrors); actionfwd = mapping.findForward("failure"); } + saveToken(request); return actionfwd; } }
true
true
protected ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { BaseAddEditAction addAction; ActionForward actionfwd; try { if ( !isTokenValid(request) ) { ActionErrors actionErrors = new ActionErrors(); ActionError actionError = new ActionError("errors.item","Invalid request for add/edit operation"); actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError); saveErrors(request, actionErrors); return mapping.findForward("failure"); } resetToken(request); boolean coppaMatchFound = false; final InstitutionForm institutionForm = (InstitutionForm) form; // String remoteOperation = institutionForm.getRemoteOperation(); String remoteOperation = request.getParameter("remoteOperation"); // COPPA is enabled and user has not selected remote entity yet. // Check if Remote match exists System.out.println("Institution Add Action:" + "form name:" + institutionForm.getName() + ":form remote operation:" + institutionForm.getRemoteOperation() + ":form remoteid:" + institutionForm.getRemoteId() + ":form remote flag:" + institutionForm.isRemoteManagedFlag() +":request param operation:"+request.getParameter("remoteOperation")); if (COPPAUtil.isCOPPAEnabled() && (Constants.REMOTE_OPERATION_SEARCH .equalsIgnoreCase(remoteOperation))) { try { Organization[] organizationList = null; organizationList = new COPPAServiceClient() .searchOrganization(institutionForm.getName()); if (organizationList != null && organizationList.length > 0) { coppaMatchFound = true; request.setAttribute("COPPA_MATCH_FOUND", "true"); request.getSession().setAttribute("COPPA_ORGANIZATIONS", organizationList); } } catch (Exception e) { logger.error("Failed to look for Organizations in COPPA."); logger.error(e,e); } } if (coppaMatchFound) { // Redirect user to pop-up for selecting remote institution request.setAttribute("operationAdd", Constants.ADD); request.setAttribute("formName", Constants.INSTITUTION_ADD_ACTION); actionfwd = mapping.findForward("pageOfInstitution"); } else { // Either there is no COPPA match or user has already selected // COPPA match or user does not want to do remote link if (institutionForm.getRemoteId() != 0) { // Adding a new remote institution institutionForm.setRemoteManagedFlag(true); institutionForm.setDirtyEditFlag(false); // Get organization details by id Organization org = new COPPAServiceClient() .getOrganizationById("" + institutionForm.getRemoteId()); institutionForm.setName(org.getName().getPart().get(0) .getValue()); } addAction = new CommonAddAction(); logger.info("Insitution Add Action before adding to db:" + "remote id:" + institutionForm.getRemoteId() + "remote flag:" + institutionForm.isRemoteManagedFlag() + "dirty edit flag:" + institutionForm.isDirtyEditFlag() + "name:" + institutionForm.getName()); actionfwd = addAction.executeXSS(mapping, institutionForm, request, response); // over write action succuess message for remote link success if (institutionForm.getRemoteId() != 0) { AppUtility.replaceActionMessage(request, "ctrp.instituion.link.success"); } }// end -if adding user not remote pop-up } catch (ApplicationException applicationException) { logger.error("Institution Add failed.." + applicationException.getCustomizedMsg()); ActionErrors actionErrors = new ActionErrors(); ActionError actionError = new ActionError("errors.item", applicationException.getCustomizedMsg()); actionErrors.add("org.apache.struts.action.GLOBAL_ERROR", actionError); saveErrors(request, actionErrors); actionfwd = mapping.findForward("failure"); } return actionfwd; }
protected ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { BaseAddEditAction addAction; ActionForward actionfwd; try { if ( !isTokenValid(request) ) { ActionErrors actionErrors = new ActionErrors(); ActionError actionError = new ActionError("errors.item","Invalid request for add/edit operation"); actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError); saveErrors(request, actionErrors); return mapping.findForward("failure"); } resetToken(request); boolean coppaMatchFound = false; final InstitutionForm institutionForm = (InstitutionForm) form; // String remoteOperation = institutionForm.getRemoteOperation(); String remoteOperation = request.getParameter("remoteOperation"); // COPPA is enabled and user has not selected remote entity yet. // Check if Remote match exists System.out.println("Institution Add Action:" + "form name:" + institutionForm.getName() + ":form remote operation:" + institutionForm.getRemoteOperation() + ":form remoteid:" + institutionForm.getRemoteId() + ":form remote flag:" + institutionForm.isRemoteManagedFlag() +":request param operation:"+request.getParameter("remoteOperation")); if (COPPAUtil.isCOPPAEnabled() && (Constants.REMOTE_OPERATION_SEARCH .equalsIgnoreCase(remoteOperation))) { try { Organization[] organizationList = null; organizationList = new COPPAServiceClient() .searchOrganization(institutionForm.getName()); if (organizationList != null && organizationList.length > 0) { coppaMatchFound = true; request.setAttribute("COPPA_MATCH_FOUND", "true"); request.getSession().setAttribute("COPPA_ORGANIZATIONS", organizationList); } } catch (Exception e) { logger.error("Failed to look for Organizations in COPPA."); logger.error(e,e); } } if (coppaMatchFound) { // Redirect user to pop-up for selecting remote institution request.setAttribute("operationAdd", Constants.ADD); request.setAttribute("formName", Constants.INSTITUTION_ADD_ACTION); actionfwd = mapping.findForward("pageOfInstitution"); } else { // Either there is no COPPA match or user has already selected // COPPA match or user does not want to do remote link if (institutionForm.getRemoteId() != 0) { // Adding a new remote institution institutionForm.setRemoteManagedFlag(true); institutionForm.setDirtyEditFlag(false); // Get organization details by id Organization org = new COPPAServiceClient() .getOrganizationById("" + institutionForm.getRemoteId()); institutionForm.setName(org.getName().getPart().get(0) .getValue()); } addAction = new CommonAddAction(); logger.info("Insitution Add Action before adding to db:" + "remote id:" + institutionForm.getRemoteId() + "remote flag:" + institutionForm.isRemoteManagedFlag() + "dirty edit flag:" + institutionForm.isDirtyEditFlag() + "name:" + institutionForm.getName()); actionfwd = addAction.executeXSS(mapping, institutionForm, request, response); // over write action succuess message for remote link success if (institutionForm.getRemoteId() != 0) { AppUtility.replaceActionMessage(request, "ctrp.instituion.link.success"); } }// end -if adding user not remote pop-up } catch (ApplicationException applicationException) { logger.error("Institution Add failed.." + applicationException.getCustomizedMsg()); ActionErrors actionErrors = new ActionErrors(); ActionError actionError = new ActionError("errors.item", applicationException.getCustomizedMsg()); actionErrors.add("org.apache.struts.action.GLOBAL_ERROR", actionError); saveErrors(request, actionErrors); actionfwd = mapping.findForward("failure"); } saveToken(request); return actionfwd; }
diff --git a/Freerider/src/no/ntnu/idi/socialhitchhiking/inbox/NotificationHandler.java b/Freerider/src/no/ntnu/idi/socialhitchhiking/inbox/NotificationHandler.java index fa286a0..9700e79 100644 --- a/Freerider/src/no/ntnu/idi/socialhitchhiking/inbox/NotificationHandler.java +++ b/Freerider/src/no/ntnu/idi/socialhitchhiking/inbox/NotificationHandler.java @@ -1,550 +1,550 @@ /******************************************************************************* * @contributor(s): Freerider Team (Group 4, IT2901 Fall 2012, NTNU) * @contributor(s): Freerider Team 2 (Group 3, IT2901 Spring 2013, NTNU) * @version: 2.0 * * Copyright 2013 Freerider Team 2 * * 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 no.ntnu.idi.socialhitchhiking.inbox; import java.io.IOException; import java.net.MalformedURLException; import java.util.Calendar; import java.util.concurrent.ExecutionException; import no.ntnu.idi.freerider.model.Journey; import no.ntnu.idi.freerider.model.Notification; import no.ntnu.idi.freerider.model.NotificationType; import no.ntnu.idi.freerider.model.Route; import no.ntnu.idi.freerider.model.User; import no.ntnu.idi.freerider.protocol.JourneyResponse; import no.ntnu.idi.freerider.protocol.NotificationRequest; import no.ntnu.idi.freerider.protocol.Request; import no.ntnu.idi.freerider.protocol.RequestType; import no.ntnu.idi.freerider.protocol.Response; import no.ntnu.idi.freerider.protocol.ResponseStatus; import no.ntnu.idi.freerider.protocol.SingleJourneyRequest; import no.ntnu.idi.freerider.protocol.UserRequest; import no.ntnu.idi.socialhitchhiking.R; import no.ntnu.idi.socialhitchhiking.SocialHitchhikingApplication; import no.ntnu.idi.socialhitchhiking.client.RequestTask; import no.ntnu.idi.socialhitchhiking.map.MapActivityAbstract; import no.ntnu.idi.socialhitchhiking.map.MapRoute; import org.apache.http.client.ClientProtocolException; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class NotificationHandler{ private static Inbox in; private static Notification not; private static SocialHitchhikingApplication app; /** * Static method to be called if the calling Activity is a {@link MapActivityAbstract}. * * * @param type - {@link NotificationType} * @param com * @return */ public static boolean handleMap(NotificationType type,String com){ return createRequest(true, type, com); } /** * Static method to handle a {@link Notification} when it's clicked. * Does nothing if the Notification is already read. Uses a * switch based on the {@link NotificationType), to handle unread * Notifications. * * @param nf - Notification to be handled * @param ap - Pointer to the Application, which will be used to get the current user etc. * @param i - The calling Inbox-activity which dialogs will be created upon */ public static void handleNotification(Notification nf,SocialHitchhikingApplication ap,Inbox i){ app = ap; not = nf; in = i; if(not.isRead() && not.getType() == NotificationType.MESSAGE){ createChatDialog(not); } else if(not.isRead()){ createConfirmDialog("Inactive", "Notification is inactive"); } else{ switch (not.getType()) { case DRIVER_CANCEL: createAorRDialog(); break; case HITCHHIKER_ACCEPTS_DRIVER_CANCEL: createMessageDialog(true,"Hitchhiker acknowledged", not.getSenderName()+" accepts cancel"); break; case HITCHHIKER_CANCEL: createMessageDialog(false,"Hitchhiker cancelled request", not.getSenderName()+" cancelled the request"); break; case HITCHHIKER_REQUEST: createNotificationDialog(); break; case REQUEST_ACCEPT: createAorRDialog(); break; case REQUEST_REJECT: createMessageDialog(false,"Request rejected by driver", "Your request was rejected by "+not.getSenderName()); break; case MESSAGE: createChatDialog(not); break; case RATING: createMessageDialogRating("Driver rating request", "Would you recommend "+ not.getSenderName()+"?"); break; default: createMessageDialog(false,"Unknown", "Status unknown"); break; } } } public static void createAorRDialog(){ final Dialog aorRDialog = new Dialog(in); aorRDialog.setContentView(R.layout.message_layout); ImageView okBtn = (ImageView)aorRDialog.findViewById(R.id.replyBtn); ImageView showBtn = (ImageView)aorRDialog.findViewById(R.id.showJourneyBtn); ImageView markAsReadBtn = (ImageView)aorRDialog.findViewById(R.id.markAsReadBtn); ImageView facebookBtn = (ImageView)aorRDialog.findViewById(R.id.shareOnFaceBtn); TextView contentTxt = (TextView)aorRDialog.findViewById(R.id.contentViewField); TextView targetTxt = (TextView)aorRDialog.findViewById(R.id.targetTxt); TextView content = (TextView)aorRDialog.findViewById(R.id.contentTxt); if(not.getType() == NotificationType.DRIVER_CANCEL){ aorRDialog.setTitle("Driver cancelled ride"); contentTxt.setText("The ride has been cancelled by " + not.getSenderName()); facebookBtn.setVisibility(View.GONE); }else{ aorRDialog.setTitle("Request accepted by driver"); contentTxt.setText("Your request was accepted by " +not.getSenderName()); } ((TextView)aorRDialog.findViewById(android.R.id.title)).setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); targetTxt.setVisibility(View.GONE); content.setVisibility(View.GONE); okBtn.setVisibility(View.GONE); facebookBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showFacebookDialog(); aorRDialog.dismiss(); } }); markAsReadBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createMarkedAsReadRequest(); aorRDialog.dismiss(); } }); showBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showBtn(); } }); aorRDialog.show(); } private static void createCommentForRequest(final NotificationType nt){ final EditText input = new EditText(in); new AlertDialog.Builder(in). setTitle("Comment"). setMessage("Write a comment"). setView(input). setPositiveButton("OK", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { createRequest(false, nt, input.getText().toString()); } }).show(); } /** * Creates a dialog, which asks the user whether they want to accept or reject * the Hitchhiker. Creates an accept notification or a reject notification * depending on the answer. */ private static void createNotificationDialog(){ final Dialog notifDialog = new Dialog(in); notifDialog.setTitle("Hitchhiker request"); notifDialog.setContentView(R.layout.notif_layout); ImageView okBtn = (ImageView)notifDialog.findViewById(R.id.okBtn); ImageView showBtn = (ImageView)notifDialog.findViewById(R.id.showBtn); TextView contentTxt = (TextView)notifDialog.findViewById(R.id.questionField); contentTxt.setText("Do you want to pick up " +not.getSenderName()); okBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createCommentForRequest(NotificationType.REQUEST_ACCEPT); notifDialog.dismiss(); } }); showBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showBtn(); } }); notifDialog.show(); } /** * Creates a simple dialog to show a message when a Notification is clicked. * * @param title - The title of the dialog that will be created. * @param msg - The message of the dialog that will be created. */ private static void createMessageDialog(final boolean hitchhiker_cancel,String title,String msg){ new AlertDialog.Builder(in). setTitle(title). setMessage(msg). setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { if(hitchhiker_cancel){ createCommentForRequest(NotificationType.HITCHHIKER_ACCEPTS_DRIVER_CANCEL); } createMarkedAsReadRequest(); } }). setNegativeButton("Cancel", null). show(); } private static void createMessageDialogRating(String title,String msg){ new AlertDialog.Builder(in). setTitle(title). setMessage(msg). setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { User u = new User(not.getSenderName(), not.getSenderID()); sendRating(u); createMarkedAsReadRequest(); } }). setNegativeButton("No", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // not.setRead(true); createMarkedAsReadRequest(); } }). show(); } public static void sendRating(User user){ UserRequest req = new UserRequest(RequestType.THUMBS_UP, user); try { Response res = RequestTask.sendRequest(req, app); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } public static void sendMessage(User mid, EditText input){ Notification nots = new Notification(app.getUser().getID(), mid.getID(), app.getUser().getFullName(), input.getText().toString(), not.getJourneySerial(), NotificationType.MESSAGE, Calendar.getInstance()); NotificationRequest req = new NotificationRequest(app.getUser(), nots); try { Response res = RequestTask.sendRequest(req, app); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } private static void showFacebookDialog(){ Journey journey = new Journey(999); try{ SingleJourneyRequest r = new SingleJourneyRequest(RequestType.GET_JOURNEY, app.getUser(), not.getJourneySerial()); JourneyResponse response = (JourneyResponse)RequestTask.sendRequest(r, app); if(response.getStatus() == ResponseStatus.OK){ if(response.getJourneys().size() > 0){ journey = response.getJourneys().get(0); } } else if(response.getStatus() == ResponseStatus.FAILED){ } }catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } Route route = new Route(journey.getRoute().getOwner(), journey.getRoute().getName(), journey.getRoute().getRouteData(), journey.getRoute().getSerial()); route.setMapPoints(journey.getRoute().getMapPoints()); Intent intent = new Intent(in, no.ntnu.idi.socialhitchhiking.utility.ShareOnFacebook.class); intent.putExtra("isDriver", false); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); app.setJourneyPickupPoint(not.getStartPoint()); app.setJourneyDropoffPoint(not.getStopPoint()); app.setSelectedNotification(not); app.setSelectedRoute(route); app.setSelectedJourney(journey); app.startActivity(intent); } public static void showBtn(){ Journey journey = new Journey(999); try{ SingleJourneyRequest r = new SingleJourneyRequest(RequestType.GET_JOURNEY, app.getUser(), not.getJourneySerial()); JourneyResponse response = (JourneyResponse)RequestTask.sendRequest(r, app); if(response.getStatus() == ResponseStatus.OK){ if(response.getJourneys().size() > 0){ journey = response.getJourneys().get(0); Intent intent = new Intent(in, no.ntnu.idi.socialhitchhiking.map.MapActivityJourney.class); MapRoute mr = new MapRoute(journey.getRoute().getOwner(), journey.getRoute().getName(), journey.getRoute().getSerial(), journey.getRoute().getMapPoints()); intent.putExtra("Journey", true); intent.putExtra("journeyAccepted", true); intent.putExtra("journeyRejected", false); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); app.setSelectedMapRoute(mr); app.setSelectedJourney(journey); app.setJourneyPickupPoint(not.getStartPoint()); app.setJourneyDropoffPoint(not.getStopPoint()); app.setSelectedNotification(not); app.startActivity(intent); } } else if(response.getStatus() == ResponseStatus.FAILED){ Toast.makeText(in, "Ride is finished", Toast.LENGTH_SHORT).show(); } }catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } public static void createChatDialog(final Notification not){ final Dialog messageDialog = new Dialog(in); messageDialog.setContentView(R.layout.message_layout); messageDialog.setTitle("Message"); TextView nameTxt = (TextView)messageDialog.findViewById(R.id.nameTxt); TextView contentTxt = (TextView)messageDialog.findViewById(R.id.contentViewField); ImageView replyBtn = (ImageView)messageDialog.findViewById(R.id.replyBtn); ImageView showRideBtn = (ImageView)messageDialog.findViewById(R.id.showJourneyBtn); ImageView markAsReadBtn = (ImageView)messageDialog.findViewById(R.id.markAsReadBtn); ImageView facebookBtn = (ImageView)messageDialog.findViewById(R.id.shareOnFaceBtn); facebookBtn.setVisibility(View.GONE); nameTxt.setText(not.getSenderName()); contentTxt.setText(not.getComment()); if(not.isRead()){ markAsReadBtn.setVisibility(View.GONE); } replyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Dialog replyDialog = new Dialog(in); replyDialog.setContentView(R.layout.replay_layout); - replyDialog.setTitle("Replay"); + replyDialog.setTitle("Reply"); ImageView sendBtn = (ImageView)replyDialog.findViewById(R.id.sendBtn); TextView sendTxt = (TextView)replyDialog.findViewById(R.id.sendTxt); TextView messageFromTxt = (TextView)replyDialog.findViewById(R.id.messageFromTxt); TextView messageContent = (TextView)replyDialog.findViewById(R.id.messageContent); final EditText inputField = (EditText)replyDialog.findViewById(R.id.input); sendTxt.setText(not.getSenderName()); messageFromTxt.setText("Message from: " + not.getSenderName()); messageContent.setText(not.getComment()); sendBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { User midUser = new User(); midUser.setID(not.getSenderID()); //sendMessage(midUser, inputField); if(inputField.getText().toString().equals("")){ inputField.setHint("Please fill in your message"); Toast toast = Toast.makeText(in, "Please fill in your message", Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM, toast.getXOffset() / 2, toast.getYOffset() / 2); toast.show(); }else{ sendMessage(midUser, inputField); Toast toast = Toast.makeText(in, "Message sent", Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM, toast.getXOffset() / 2, toast.getYOffset() / 2); toast.show(); replyDialog.dismiss(); } } }); replyDialog.show(); } }); showRideBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showBtn(); } }); markAsReadBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createMarkedAsReadRequest(); messageDialog.dismiss(); } }); messageDialog.show(); } /** * Creates a simple dialog to show a message when a Notification is clicked. * * @param title - The title of the dialog that will be created. * @param msg - The message of the dialog that will be created. */ private static void createConfirmDialog(String title,String msg){ new AlertDialog.Builder(in). setTitle(title). setMessage(msg). setNeutralButton("OK", null). show(); } /** * Creates a {@link NotificationRequest} to mark a Notification as read, * and sends it to the server. Creates a dialog that show if the request * was successfully sent. * */ private static boolean createMarkedAsReadRequest() { NotificationRequest req = new NotificationRequest(RequestType.MARK_NOTIFICATION_READ,app.getUser(), not); if(sendNotificationRequest(req)){ in.setNotificationRead(not); return true; } return false; } /** * Creates a {@link NotificationRequest} and sends it to the server. * Creates a dialog that show if the request was successfully sent. * * @param accept */ private static boolean createRequest(boolean mapmode,NotificationType type,String com) { Notification notif = new Notification(app.getUser().getID(), not.getSenderID(), "",com, not.getJourneySerial(), type); NotificationRequest req = new NotificationRequest(app.getUser(), notif); if(sendNotificationRequest(req)){ if(!mapmode)createConfirmDialog("Confirmed", "Successfully sent reply"); return createMarkedAsReadRequest(); } else { if(!mapmode)createConfirmDialog("ERROR", "Reply was not sent"); return false; } } /** * Sends a notification request. * * @param req - The request to be sent. * @return false if something went wrong, true if everything went well. */ public static boolean sendNotificationRequest(Request req){ Response res; try { res = RequestTask.sendRequest(req,app); boolean succeded = res.getStatus() == ResponseStatus.OK; return succeded; } catch (ClientProtocolException e) { } catch (IOException e) { } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return false; } }
true
true
public static void createChatDialog(final Notification not){ final Dialog messageDialog = new Dialog(in); messageDialog.setContentView(R.layout.message_layout); messageDialog.setTitle("Message"); TextView nameTxt = (TextView)messageDialog.findViewById(R.id.nameTxt); TextView contentTxt = (TextView)messageDialog.findViewById(R.id.contentViewField); ImageView replyBtn = (ImageView)messageDialog.findViewById(R.id.replyBtn); ImageView showRideBtn = (ImageView)messageDialog.findViewById(R.id.showJourneyBtn); ImageView markAsReadBtn = (ImageView)messageDialog.findViewById(R.id.markAsReadBtn); ImageView facebookBtn = (ImageView)messageDialog.findViewById(R.id.shareOnFaceBtn); facebookBtn.setVisibility(View.GONE); nameTxt.setText(not.getSenderName()); contentTxt.setText(not.getComment()); if(not.isRead()){ markAsReadBtn.setVisibility(View.GONE); } replyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Dialog replyDialog = new Dialog(in); replyDialog.setContentView(R.layout.replay_layout); replyDialog.setTitle("Replay"); ImageView sendBtn = (ImageView)replyDialog.findViewById(R.id.sendBtn); TextView sendTxt = (TextView)replyDialog.findViewById(R.id.sendTxt); TextView messageFromTxt = (TextView)replyDialog.findViewById(R.id.messageFromTxt); TextView messageContent = (TextView)replyDialog.findViewById(R.id.messageContent); final EditText inputField = (EditText)replyDialog.findViewById(R.id.input); sendTxt.setText(not.getSenderName()); messageFromTxt.setText("Message from: " + not.getSenderName()); messageContent.setText(not.getComment()); sendBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { User midUser = new User(); midUser.setID(not.getSenderID()); //sendMessage(midUser, inputField); if(inputField.getText().toString().equals("")){ inputField.setHint("Please fill in your message"); Toast toast = Toast.makeText(in, "Please fill in your message", Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM, toast.getXOffset() / 2, toast.getYOffset() / 2); toast.show(); }else{ sendMessage(midUser, inputField); Toast toast = Toast.makeText(in, "Message sent", Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM, toast.getXOffset() / 2, toast.getYOffset() / 2); toast.show(); replyDialog.dismiss(); } } }); replyDialog.show(); } }); showRideBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showBtn(); } }); markAsReadBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createMarkedAsReadRequest(); messageDialog.dismiss(); } }); messageDialog.show(); }
public static void createChatDialog(final Notification not){ final Dialog messageDialog = new Dialog(in); messageDialog.setContentView(R.layout.message_layout); messageDialog.setTitle("Message"); TextView nameTxt = (TextView)messageDialog.findViewById(R.id.nameTxt); TextView contentTxt = (TextView)messageDialog.findViewById(R.id.contentViewField); ImageView replyBtn = (ImageView)messageDialog.findViewById(R.id.replyBtn); ImageView showRideBtn = (ImageView)messageDialog.findViewById(R.id.showJourneyBtn); ImageView markAsReadBtn = (ImageView)messageDialog.findViewById(R.id.markAsReadBtn); ImageView facebookBtn = (ImageView)messageDialog.findViewById(R.id.shareOnFaceBtn); facebookBtn.setVisibility(View.GONE); nameTxt.setText(not.getSenderName()); contentTxt.setText(not.getComment()); if(not.isRead()){ markAsReadBtn.setVisibility(View.GONE); } replyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Dialog replyDialog = new Dialog(in); replyDialog.setContentView(R.layout.replay_layout); replyDialog.setTitle("Reply"); ImageView sendBtn = (ImageView)replyDialog.findViewById(R.id.sendBtn); TextView sendTxt = (TextView)replyDialog.findViewById(R.id.sendTxt); TextView messageFromTxt = (TextView)replyDialog.findViewById(R.id.messageFromTxt); TextView messageContent = (TextView)replyDialog.findViewById(R.id.messageContent); final EditText inputField = (EditText)replyDialog.findViewById(R.id.input); sendTxt.setText(not.getSenderName()); messageFromTxt.setText("Message from: " + not.getSenderName()); messageContent.setText(not.getComment()); sendBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { User midUser = new User(); midUser.setID(not.getSenderID()); //sendMessage(midUser, inputField); if(inputField.getText().toString().equals("")){ inputField.setHint("Please fill in your message"); Toast toast = Toast.makeText(in, "Please fill in your message", Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM, toast.getXOffset() / 2, toast.getYOffset() / 2); toast.show(); }else{ sendMessage(midUser, inputField); Toast toast = Toast.makeText(in, "Message sent", Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM, toast.getXOffset() / 2, toast.getYOffset() / 2); toast.show(); replyDialog.dismiss(); } } }); replyDialog.show(); } }); showRideBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showBtn(); } }); markAsReadBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createMarkedAsReadRequest(); messageDialog.dismiss(); } }); messageDialog.show(); }
diff --git a/src/net/loadingchunks/plugins/Leeroy/LeeroyCommands.java b/src/net/loadingchunks/plugins/Leeroy/LeeroyCommands.java index 4d3c9e0..e32c982 100644 --- a/src/net/loadingchunks/plugins/Leeroy/LeeroyCommands.java +++ b/src/net/loadingchunks/plugins/Leeroy/LeeroyCommands.java @@ -1,460 +1,460 @@ package net.loadingchunks.plugins.Leeroy; import java.util.List; import java.util.Map.Entry; import java.util.Set; import net.loadingchunks.plugins.Leeroy.Types.BasicNPC; import net.loadingchunks.plugins.Leeroy.Types.ButlerNPC; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.metadata.MetadataValue; import org.fusesource.jansi.Ansi.Color; import org.bukkit.craftbukkit.CraftWorld; public class LeeroyCommands implements CommandExecutor { public Leeroy plugin; public LeeroyCommands(Leeroy plugin) { this.plugin = plugin; } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("leeroy")) { this.plugin.log.info("[LEEROY] Got Leeroy Command Hook!"); if(args[0].equalsIgnoreCase("spawn")) { String name; if(args.length == 3) name = args[2]; else { return false; } this.plugin.log.info("[LEEROY] Got Spawn!"); if(!(sender instanceof Player)) { sender.sendMessage("[LEEROY] This command can only be used in-game."); return false; } if(!LeeroyPermissions.canSpawn((Player)sender)) { sender.sendMessage("[LEEROY] This command is op-only!"); return false; } this.plugin.log.info("[LEEROY] Init Handler."); LeeroyNPCHandler npc = new LeeroyNPCHandler(this.plugin); Set<Entry<String, Object>> entries = this.plugin.NPCList.entrySet(); for(Entry<String, Object> n : entries) { BasicNPC np = (BasicNPC)n.getValue(); if(np.name.equalsIgnoreCase(name) && np.npc.getBukkitEntity().getWorld().getName().equalsIgnoreCase(((Player)sender).getWorld().getName()) ) { sender.sendMessage("[LEEROY] An NPC already exists within this world with that name."); return true; } } this.plugin.log.info("[LEEROY] Spawning..."); npc.spawn(args[1], name, ((Player)sender).getLocation(), "", "", "", "", true, ((Player)sender).getWorld().getName(), null); return true; } else if(args[0].equalsIgnoreCase("angle") && sender instanceof Player) { sender.sendMessage("You Yaw is " + ((Player)sender).getLocation().getYaw() + " and your pitch is " + ((Player)sender).getLocation().getPitch() + "."); return true; } else if(args[0].equalsIgnoreCase("kill")) { String name; Integer radius = 5; if(!(sender instanceof Player)) return false; if(!LeeroyPermissions.canKill((Player)sender)) { sender.sendMessage("[LEEROY] This command is op-only!"); return false; } if(args.length < 2) return false; name = args[1]; if(args.length == 3) { radius = Integer.parseInt(args[2]); } Player p = (Player)sender; List<Entity> entities = p.getNearbyEntities(radius, radius, radius); for(Entity e : entities) { if(e instanceof HumanEntity) { List<MetadataValue> md = e.getMetadata("leeroy_id"); List<MetadataValue> mdtype = e.getMetadata("leeroy_type"); if(md.size() > 0) { if(((BasicNPC)this.plugin.NPCList.get(md.get(0).asString())).name.equalsIgnoreCase(name) || name.equalsIgnoreCase("*")) { this.plugin.log.info("[LEEROY] Killing NPC with ID: " + md.get(0).asString()); this.plugin.npcs.remove(md.get(0).asString()); } } } } return true; } else if(args[0].equalsIgnoreCase("look")) { String name; Integer radius = 5; if(!(sender instanceof Player)) return false; if(!LeeroyPermissions.canLook((Player)sender)) { sender.sendMessage("[LEEROY] This command is op-only!"); return false; } if(args.length < 2) { sender.sendMessage("[LEEROY] Not enough args!"); return false; } name = args[1]; if(args.length == 3) { radius = Integer.parseInt(args[2]); } Player p = (Player)sender; List<Entity> entities = p.getNearbyEntities(radius, radius, radius); for(Entity e : entities) { if(e instanceof HumanEntity) { List<MetadataValue> md = e.getMetadata("leeroy_id"); List<MetadataValue> mdtype = e.getMetadata("leeroy_type"); if(md.size() > 0) { if(((BasicNPC)this.plugin.NPCList.get(md.get(0).asString())).name.equalsIgnoreCase(name) || name.equalsIgnoreCase("*")) { ((BasicNPC)this.plugin.NPCList.get(md.get(0).asString())).npc.lookAtPoint(((Player)sender).getEyeLocation()); } } } } return true; } else if(args[0].equalsIgnoreCase("reload")) { if(sender.isOp()) { this.plugin.reloadConfig(); sender.sendMessage("Config reloaded!"); return true; } } else if(args[0].equalsIgnoreCase("list")) { if(sender.isOp()) { for(String s : this.plugin.getConfig().getStringList("general.templates")) { sender.sendMessage("- " + s); } } } else if(args[0].equalsIgnoreCase("purge")) { if(!sender.isOp()) return false; plugin.log.info("[LEEROY] Running checks on homeworlds."); List<World> worlds = plugin.getServer().getWorlds(); for(World w : worlds) { if(w == null) continue; if(w.getName().startsWith("homeworld_") && (w.getPlayers().isEmpty() || (w.getPlayers().size() == 1 && (w.getPlayers().get(0).getAddress() == null)))) { plugin.log.info("[LEEROY] Checking " + w.getName()); if(LeeroyUtils.hasNPC(plugin, w.getName()) && plugin.NPCList.containsKey(w.getName() + "_butler")) { plugin.log.info("[LEEROY] Redundant NPC Found in " + w.getName()); ((ButlerNPC)plugin.NPCList.get(w.getName() + "_butler")).npc.moveTo(plugin.mvcore.getMVWorldManager().getFirstSpawnWorld().getSpawnLocation()); ((ButlerNPC)plugin.NPCList.get(w.getName() + "_butler")).npc.getEntity().getBukkitEntity().remove(); ((CraftWorld) w).getHandle().getPlayerManager().a().removeEntity(((ButlerNPC)plugin.NPCList.get(w.getName() + "_butler")).npc.getEntity()); plugin.NPCList.remove(w.getName() + "_butler"); plugin.log.info("[LEEROY] Redundant NPC " + w.getName() + "_butler has been removed."); } if(!plugin.mvcore.getMVWorldManager().unloadWorld(w.getName())) { sender.sendMessage("Error purging world " + w.getName()); sender.sendMessage("Players/NPCs in World: " + w.getPlayers().size()); sender.sendMessage("Players: " + w.getPlayers().toString()); sender.sendMessage("HandlePlayers: " + ((CraftWorld) w).getHandle().players.size()); } } else if (w.getPlayers().size() > 0 && w.getName().startsWith("homeworld_") && !LeeroyUtils.hasNPC(plugin, w.getName())) { plugin.log.info("[LEEROY] No NPC found in loaded world " + w.getName()); Location nl = new Location(w, plugin.getConfig().getDouble("home.butler.x"), plugin.getConfig().getDouble("home.butler.y"), plugin.getConfig().getDouble("home.butler.z")); plugin.npcs.spawn("butler",plugin.getConfig().getString("home.butler.name"), nl, "", "", "", "", false, w.getName(), w.getName() + "_butler"); } } return true; } } if(cmd.getName().equalsIgnoreCase("invite")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(!(p.getWorld().getName().equalsIgnoreCase("homeworld_" + p.getName()))) { p.sendMessage("This is not your home world"); return true; } if(!p.hasPermission("leeroy.invite")) { p.sendMessage("You do not have permission to do that!"); return true; } if(args.length < 1) { p.sendMessage("You need to specify a player to invite"); return true; } if(plugin.getServer().getPlayer(args[0]) != null) { Player to = plugin.getServer().getPlayer(args[0]); to.sendMessage(ChatColor.AQUA + p.getDisplayName() + " has invited you to their home world. Type /accept to go there!"); this.plugin.inviteList.put(to.getName(), "homeworld_" + p.getName()); p.sendMessage(ChatColor.AQUA + "Invite sent to " + to.getName()); return true; } return false; } if(cmd.getName().equalsIgnoreCase("hw")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(args.length < 1) { return false; } LeeroyHomeCommand command = this.plugin.sql.GetCommand(args[0]); if(!this.plugin.sql.PlayerHasCommand(command.commandString, p.getName())) { sender.sendMessage("You do not have access to that command."); return true; } String executor = command.commandExec; int argcount = 1; for(String arg : args) { executor = executor.replaceAll("{arg" + argcount + "}", arg); } executor = executor.replaceAll("{player}", p.getName()); executor = executor.replaceAll("{playerdisplay}", p.getDisplayName()); // Protective checks if(command.commandCheck.length != (args.length - 1)) { sender.sendMessage("Invalid arguments given for command /hw " + command.commandString); sender.sendMessage("Usage: " + command.commandUsage); return true; } argcount = 0; for(String a : args) { if(argcount == 0) { argcount++; continue; } switch(command.commandCheck[argcount-1]) { case "Player": if(this.plugin.getServer().getPlayer(a) == null) { sender.sendMessage(ChatColor.RED + "Player " + a + " not found."); sender.sendMessage("Usage: " + command.commandUsage); return true; } break; case "Integer": try { Integer.parseInt(a); } catch(NumberFormatException e) { sender.sendMessage(ChatColor.RED + "Invalid number, you supplied " + a); sender.sendMessage("Usage: " + command.commandUsage); return true; } break; case "String": break; default: sender.sendMessage(ChatColor.RED + "An unknown error occurred while checking your command."); this.plugin.getLogger().warning("Bad Homeworld Argument Type Given: " + command.commandCheck[argcount]); sender.sendMessage("Usage: " + command.commandUsage); return true; } } String[] executors = executor.split("\n"); for(String ex : executors) { this.plugin.getServer().dispatchCommand((CommandSender) (this.plugin.getServer().getConsoleSender()), ex); } return false; } if(cmd.getName().equalsIgnoreCase("upgrade")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(args.length != 1) { sender.sendMessage("You need to specify an upgrade to buy!"); return false; } if(this.plugin.sql.PlayerHasCommand(args[0], p.getName())) { sender.sendMessage("You have already purchased this upgrade!"); return true; } LeeroyHomeCommand command = this.plugin.sql.GetCommand(args[0]); if(command == null) { sender.sendMessage("Unknown command."); return true; } if(!this.plugin.eco.has(p.getName(), command.commandPrice)) { - sender.sendMessage("You don't have enough money for this upgrade, it costs $" + ChatColor.GOLD + command.commandPrice + ChatColor.WHITE + " and you have $" + ChatColor.GOLD + this.plugin.eco.bankBalance(p.getName()) + ChatColor.WHITE + "."); + sender.sendMessage("You don't have enough money for this upgrade, it costs $" + ChatColor.GOLD + command.commandPrice + ChatColor.WHITE + " and you have $" + ChatColor.GOLD + this.plugin.eco.bankBalance(p.getName()).balance + ChatColor.WHITE + "."); return true; } this.plugin.sql.PurchaseCommand(command.commandString, p.getName()); this.plugin.eco.withdrawPlayer(p.getName(), command.commandPrice); this.plugin.eco.depositPlayer("lcbank", command.commandPrice); sender.sendMessage("Purchase successful!"); return true; } if(cmd.getName().equalsIgnoreCase("accept")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(!p.hasPermission("leeroy.accept")) { p.sendMessage("You do not have permission to do that!"); return true; } if(!plugin.inviteList.containsKey(p.getName())) { sender.sendMessage("Nobody has invited you to their home! :("); return true; } if(plugin.mvcore.getMVWorldManager().getUnloadedWorlds().contains(plugin.inviteList.get(p.getName()))) { sender.sendMessage("Nobody is in that world any more."); return true; } if(plugin.getServer().getPlayer(plugin.inviteList.get(p.getName()).replace("homeworld_", "")) == null) { sender.sendMessage("Player is not online."); return true; } p.teleport(plugin.mvcore.getMVWorldManager().getMVWorld(plugin.inviteList.get(p.getName())).getSpawnLocation()); plugin.getServer().getPlayer(plugin.inviteList.get(p.getName()).replace("homeworld_", "")).sendMessage(ChatColor.AQUA + p.getDisplayName() + " has accepted your invitation."); return true; } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("leeroy")) { this.plugin.log.info("[LEEROY] Got Leeroy Command Hook!"); if(args[0].equalsIgnoreCase("spawn")) { String name; if(args.length == 3) name = args[2]; else { return false; } this.plugin.log.info("[LEEROY] Got Spawn!"); if(!(sender instanceof Player)) { sender.sendMessage("[LEEROY] This command can only be used in-game."); return false; } if(!LeeroyPermissions.canSpawn((Player)sender)) { sender.sendMessage("[LEEROY] This command is op-only!"); return false; } this.plugin.log.info("[LEEROY] Init Handler."); LeeroyNPCHandler npc = new LeeroyNPCHandler(this.plugin); Set<Entry<String, Object>> entries = this.plugin.NPCList.entrySet(); for(Entry<String, Object> n : entries) { BasicNPC np = (BasicNPC)n.getValue(); if(np.name.equalsIgnoreCase(name) && np.npc.getBukkitEntity().getWorld().getName().equalsIgnoreCase(((Player)sender).getWorld().getName()) ) { sender.sendMessage("[LEEROY] An NPC already exists within this world with that name."); return true; } } this.plugin.log.info("[LEEROY] Spawning..."); npc.spawn(args[1], name, ((Player)sender).getLocation(), "", "", "", "", true, ((Player)sender).getWorld().getName(), null); return true; } else if(args[0].equalsIgnoreCase("angle") && sender instanceof Player) { sender.sendMessage("You Yaw is " + ((Player)sender).getLocation().getYaw() + " and your pitch is " + ((Player)sender).getLocation().getPitch() + "."); return true; } else if(args[0].equalsIgnoreCase("kill")) { String name; Integer radius = 5; if(!(sender instanceof Player)) return false; if(!LeeroyPermissions.canKill((Player)sender)) { sender.sendMessage("[LEEROY] This command is op-only!"); return false; } if(args.length < 2) return false; name = args[1]; if(args.length == 3) { radius = Integer.parseInt(args[2]); } Player p = (Player)sender; List<Entity> entities = p.getNearbyEntities(radius, radius, radius); for(Entity e : entities) { if(e instanceof HumanEntity) { List<MetadataValue> md = e.getMetadata("leeroy_id"); List<MetadataValue> mdtype = e.getMetadata("leeroy_type"); if(md.size() > 0) { if(((BasicNPC)this.plugin.NPCList.get(md.get(0).asString())).name.equalsIgnoreCase(name) || name.equalsIgnoreCase("*")) { this.plugin.log.info("[LEEROY] Killing NPC with ID: " + md.get(0).asString()); this.plugin.npcs.remove(md.get(0).asString()); } } } } return true; } else if(args[0].equalsIgnoreCase("look")) { String name; Integer radius = 5; if(!(sender instanceof Player)) return false; if(!LeeroyPermissions.canLook((Player)sender)) { sender.sendMessage("[LEEROY] This command is op-only!"); return false; } if(args.length < 2) { sender.sendMessage("[LEEROY] Not enough args!"); return false; } name = args[1]; if(args.length == 3) { radius = Integer.parseInt(args[2]); } Player p = (Player)sender; List<Entity> entities = p.getNearbyEntities(radius, radius, radius); for(Entity e : entities) { if(e instanceof HumanEntity) { List<MetadataValue> md = e.getMetadata("leeroy_id"); List<MetadataValue> mdtype = e.getMetadata("leeroy_type"); if(md.size() > 0) { if(((BasicNPC)this.plugin.NPCList.get(md.get(0).asString())).name.equalsIgnoreCase(name) || name.equalsIgnoreCase("*")) { ((BasicNPC)this.plugin.NPCList.get(md.get(0).asString())).npc.lookAtPoint(((Player)sender).getEyeLocation()); } } } } return true; } else if(args[0].equalsIgnoreCase("reload")) { if(sender.isOp()) { this.plugin.reloadConfig(); sender.sendMessage("Config reloaded!"); return true; } } else if(args[0].equalsIgnoreCase("list")) { if(sender.isOp()) { for(String s : this.plugin.getConfig().getStringList("general.templates")) { sender.sendMessage("- " + s); } } } else if(args[0].equalsIgnoreCase("purge")) { if(!sender.isOp()) return false; plugin.log.info("[LEEROY] Running checks on homeworlds."); List<World> worlds = plugin.getServer().getWorlds(); for(World w : worlds) { if(w == null) continue; if(w.getName().startsWith("homeworld_") && (w.getPlayers().isEmpty() || (w.getPlayers().size() == 1 && (w.getPlayers().get(0).getAddress() == null)))) { plugin.log.info("[LEEROY] Checking " + w.getName()); if(LeeroyUtils.hasNPC(plugin, w.getName()) && plugin.NPCList.containsKey(w.getName() + "_butler")) { plugin.log.info("[LEEROY] Redundant NPC Found in " + w.getName()); ((ButlerNPC)plugin.NPCList.get(w.getName() + "_butler")).npc.moveTo(plugin.mvcore.getMVWorldManager().getFirstSpawnWorld().getSpawnLocation()); ((ButlerNPC)plugin.NPCList.get(w.getName() + "_butler")).npc.getEntity().getBukkitEntity().remove(); ((CraftWorld) w).getHandle().getPlayerManager().a().removeEntity(((ButlerNPC)plugin.NPCList.get(w.getName() + "_butler")).npc.getEntity()); plugin.NPCList.remove(w.getName() + "_butler"); plugin.log.info("[LEEROY] Redundant NPC " + w.getName() + "_butler has been removed."); } if(!plugin.mvcore.getMVWorldManager().unloadWorld(w.getName())) { sender.sendMessage("Error purging world " + w.getName()); sender.sendMessage("Players/NPCs in World: " + w.getPlayers().size()); sender.sendMessage("Players: " + w.getPlayers().toString()); sender.sendMessage("HandlePlayers: " + ((CraftWorld) w).getHandle().players.size()); } } else if (w.getPlayers().size() > 0 && w.getName().startsWith("homeworld_") && !LeeroyUtils.hasNPC(plugin, w.getName())) { plugin.log.info("[LEEROY] No NPC found in loaded world " + w.getName()); Location nl = new Location(w, plugin.getConfig().getDouble("home.butler.x"), plugin.getConfig().getDouble("home.butler.y"), plugin.getConfig().getDouble("home.butler.z")); plugin.npcs.spawn("butler",plugin.getConfig().getString("home.butler.name"), nl, "", "", "", "", false, w.getName(), w.getName() + "_butler"); } } return true; } } if(cmd.getName().equalsIgnoreCase("invite")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(!(p.getWorld().getName().equalsIgnoreCase("homeworld_" + p.getName()))) { p.sendMessage("This is not your home world"); return true; } if(!p.hasPermission("leeroy.invite")) { p.sendMessage("You do not have permission to do that!"); return true; } if(args.length < 1) { p.sendMessage("You need to specify a player to invite"); return true; } if(plugin.getServer().getPlayer(args[0]) != null) { Player to = plugin.getServer().getPlayer(args[0]); to.sendMessage(ChatColor.AQUA + p.getDisplayName() + " has invited you to their home world. Type /accept to go there!"); this.plugin.inviteList.put(to.getName(), "homeworld_" + p.getName()); p.sendMessage(ChatColor.AQUA + "Invite sent to " + to.getName()); return true; } return false; } if(cmd.getName().equalsIgnoreCase("hw")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(args.length < 1) { return false; } LeeroyHomeCommand command = this.plugin.sql.GetCommand(args[0]); if(!this.plugin.sql.PlayerHasCommand(command.commandString, p.getName())) { sender.sendMessage("You do not have access to that command."); return true; } String executor = command.commandExec; int argcount = 1; for(String arg : args) { executor = executor.replaceAll("{arg" + argcount + "}", arg); } executor = executor.replaceAll("{player}", p.getName()); executor = executor.replaceAll("{playerdisplay}", p.getDisplayName()); // Protective checks if(command.commandCheck.length != (args.length - 1)) { sender.sendMessage("Invalid arguments given for command /hw " + command.commandString); sender.sendMessage("Usage: " + command.commandUsage); return true; } argcount = 0; for(String a : args) { if(argcount == 0) { argcount++; continue; } switch(command.commandCheck[argcount-1]) { case "Player": if(this.plugin.getServer().getPlayer(a) == null) { sender.sendMessage(ChatColor.RED + "Player " + a + " not found."); sender.sendMessage("Usage: " + command.commandUsage); return true; } break; case "Integer": try { Integer.parseInt(a); } catch(NumberFormatException e) { sender.sendMessage(ChatColor.RED + "Invalid number, you supplied " + a); sender.sendMessage("Usage: " + command.commandUsage); return true; } break; case "String": break; default: sender.sendMessage(ChatColor.RED + "An unknown error occurred while checking your command."); this.plugin.getLogger().warning("Bad Homeworld Argument Type Given: " + command.commandCheck[argcount]); sender.sendMessage("Usage: " + command.commandUsage); return true; } } String[] executors = executor.split("\n"); for(String ex : executors) { this.plugin.getServer().dispatchCommand((CommandSender) (this.plugin.getServer().getConsoleSender()), ex); } return false; } if(cmd.getName().equalsIgnoreCase("upgrade")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(args.length != 1) { sender.sendMessage("You need to specify an upgrade to buy!"); return false; } if(this.plugin.sql.PlayerHasCommand(args[0], p.getName())) { sender.sendMessage("You have already purchased this upgrade!"); return true; } LeeroyHomeCommand command = this.plugin.sql.GetCommand(args[0]); if(command == null) { sender.sendMessage("Unknown command."); return true; } if(!this.plugin.eco.has(p.getName(), command.commandPrice)) { sender.sendMessage("You don't have enough money for this upgrade, it costs $" + ChatColor.GOLD + command.commandPrice + ChatColor.WHITE + " and you have $" + ChatColor.GOLD + this.plugin.eco.bankBalance(p.getName()) + ChatColor.WHITE + "."); return true; } this.plugin.sql.PurchaseCommand(command.commandString, p.getName()); this.plugin.eco.withdrawPlayer(p.getName(), command.commandPrice); this.plugin.eco.depositPlayer("lcbank", command.commandPrice); sender.sendMessage("Purchase successful!"); return true; } if(cmd.getName().equalsIgnoreCase("accept")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(!p.hasPermission("leeroy.accept")) { p.sendMessage("You do not have permission to do that!"); return true; } if(!plugin.inviteList.containsKey(p.getName())) { sender.sendMessage("Nobody has invited you to their home! :("); return true; } if(plugin.mvcore.getMVWorldManager().getUnloadedWorlds().contains(plugin.inviteList.get(p.getName()))) { sender.sendMessage("Nobody is in that world any more."); return true; } if(plugin.getServer().getPlayer(plugin.inviteList.get(p.getName()).replace("homeworld_", "")) == null) { sender.sendMessage("Player is not online."); return true; } p.teleport(plugin.mvcore.getMVWorldManager().getMVWorld(plugin.inviteList.get(p.getName())).getSpawnLocation()); plugin.getServer().getPlayer(plugin.inviteList.get(p.getName()).replace("homeworld_", "")).sendMessage(ChatColor.AQUA + p.getDisplayName() + " has accepted your invitation."); return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(cmd.getName().equalsIgnoreCase("leeroy")) { this.plugin.log.info("[LEEROY] Got Leeroy Command Hook!"); if(args[0].equalsIgnoreCase("spawn")) { String name; if(args.length == 3) name = args[2]; else { return false; } this.plugin.log.info("[LEEROY] Got Spawn!"); if(!(sender instanceof Player)) { sender.sendMessage("[LEEROY] This command can only be used in-game."); return false; } if(!LeeroyPermissions.canSpawn((Player)sender)) { sender.sendMessage("[LEEROY] This command is op-only!"); return false; } this.plugin.log.info("[LEEROY] Init Handler."); LeeroyNPCHandler npc = new LeeroyNPCHandler(this.plugin); Set<Entry<String, Object>> entries = this.plugin.NPCList.entrySet(); for(Entry<String, Object> n : entries) { BasicNPC np = (BasicNPC)n.getValue(); if(np.name.equalsIgnoreCase(name) && np.npc.getBukkitEntity().getWorld().getName().equalsIgnoreCase(((Player)sender).getWorld().getName()) ) { sender.sendMessage("[LEEROY] An NPC already exists within this world with that name."); return true; } } this.plugin.log.info("[LEEROY] Spawning..."); npc.spawn(args[1], name, ((Player)sender).getLocation(), "", "", "", "", true, ((Player)sender).getWorld().getName(), null); return true; } else if(args[0].equalsIgnoreCase("angle") && sender instanceof Player) { sender.sendMessage("You Yaw is " + ((Player)sender).getLocation().getYaw() + " and your pitch is " + ((Player)sender).getLocation().getPitch() + "."); return true; } else if(args[0].equalsIgnoreCase("kill")) { String name; Integer radius = 5; if(!(sender instanceof Player)) return false; if(!LeeroyPermissions.canKill((Player)sender)) { sender.sendMessage("[LEEROY] This command is op-only!"); return false; } if(args.length < 2) return false; name = args[1]; if(args.length == 3) { radius = Integer.parseInt(args[2]); } Player p = (Player)sender; List<Entity> entities = p.getNearbyEntities(radius, radius, radius); for(Entity e : entities) { if(e instanceof HumanEntity) { List<MetadataValue> md = e.getMetadata("leeroy_id"); List<MetadataValue> mdtype = e.getMetadata("leeroy_type"); if(md.size() > 0) { if(((BasicNPC)this.plugin.NPCList.get(md.get(0).asString())).name.equalsIgnoreCase(name) || name.equalsIgnoreCase("*")) { this.plugin.log.info("[LEEROY] Killing NPC with ID: " + md.get(0).asString()); this.plugin.npcs.remove(md.get(0).asString()); } } } } return true; } else if(args[0].equalsIgnoreCase("look")) { String name; Integer radius = 5; if(!(sender instanceof Player)) return false; if(!LeeroyPermissions.canLook((Player)sender)) { sender.sendMessage("[LEEROY] This command is op-only!"); return false; } if(args.length < 2) { sender.sendMessage("[LEEROY] Not enough args!"); return false; } name = args[1]; if(args.length == 3) { radius = Integer.parseInt(args[2]); } Player p = (Player)sender; List<Entity> entities = p.getNearbyEntities(radius, radius, radius); for(Entity e : entities) { if(e instanceof HumanEntity) { List<MetadataValue> md = e.getMetadata("leeroy_id"); List<MetadataValue> mdtype = e.getMetadata("leeroy_type"); if(md.size() > 0) { if(((BasicNPC)this.plugin.NPCList.get(md.get(0).asString())).name.equalsIgnoreCase(name) || name.equalsIgnoreCase("*")) { ((BasicNPC)this.plugin.NPCList.get(md.get(0).asString())).npc.lookAtPoint(((Player)sender).getEyeLocation()); } } } } return true; } else if(args[0].equalsIgnoreCase("reload")) { if(sender.isOp()) { this.plugin.reloadConfig(); sender.sendMessage("Config reloaded!"); return true; } } else if(args[0].equalsIgnoreCase("list")) { if(sender.isOp()) { for(String s : this.plugin.getConfig().getStringList("general.templates")) { sender.sendMessage("- " + s); } } } else if(args[0].equalsIgnoreCase("purge")) { if(!sender.isOp()) return false; plugin.log.info("[LEEROY] Running checks on homeworlds."); List<World> worlds = plugin.getServer().getWorlds(); for(World w : worlds) { if(w == null) continue; if(w.getName().startsWith("homeworld_") && (w.getPlayers().isEmpty() || (w.getPlayers().size() == 1 && (w.getPlayers().get(0).getAddress() == null)))) { plugin.log.info("[LEEROY] Checking " + w.getName()); if(LeeroyUtils.hasNPC(plugin, w.getName()) && plugin.NPCList.containsKey(w.getName() + "_butler")) { plugin.log.info("[LEEROY] Redundant NPC Found in " + w.getName()); ((ButlerNPC)plugin.NPCList.get(w.getName() + "_butler")).npc.moveTo(plugin.mvcore.getMVWorldManager().getFirstSpawnWorld().getSpawnLocation()); ((ButlerNPC)plugin.NPCList.get(w.getName() + "_butler")).npc.getEntity().getBukkitEntity().remove(); ((CraftWorld) w).getHandle().getPlayerManager().a().removeEntity(((ButlerNPC)plugin.NPCList.get(w.getName() + "_butler")).npc.getEntity()); plugin.NPCList.remove(w.getName() + "_butler"); plugin.log.info("[LEEROY] Redundant NPC " + w.getName() + "_butler has been removed."); } if(!plugin.mvcore.getMVWorldManager().unloadWorld(w.getName())) { sender.sendMessage("Error purging world " + w.getName()); sender.sendMessage("Players/NPCs in World: " + w.getPlayers().size()); sender.sendMessage("Players: " + w.getPlayers().toString()); sender.sendMessage("HandlePlayers: " + ((CraftWorld) w).getHandle().players.size()); } } else if (w.getPlayers().size() > 0 && w.getName().startsWith("homeworld_") && !LeeroyUtils.hasNPC(plugin, w.getName())) { plugin.log.info("[LEEROY] No NPC found in loaded world " + w.getName()); Location nl = new Location(w, plugin.getConfig().getDouble("home.butler.x"), plugin.getConfig().getDouble("home.butler.y"), plugin.getConfig().getDouble("home.butler.z")); plugin.npcs.spawn("butler",plugin.getConfig().getString("home.butler.name"), nl, "", "", "", "", false, w.getName(), w.getName() + "_butler"); } } return true; } } if(cmd.getName().equalsIgnoreCase("invite")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(!(p.getWorld().getName().equalsIgnoreCase("homeworld_" + p.getName()))) { p.sendMessage("This is not your home world"); return true; } if(!p.hasPermission("leeroy.invite")) { p.sendMessage("You do not have permission to do that!"); return true; } if(args.length < 1) { p.sendMessage("You need to specify a player to invite"); return true; } if(plugin.getServer().getPlayer(args[0]) != null) { Player to = plugin.getServer().getPlayer(args[0]); to.sendMessage(ChatColor.AQUA + p.getDisplayName() + " has invited you to their home world. Type /accept to go there!"); this.plugin.inviteList.put(to.getName(), "homeworld_" + p.getName()); p.sendMessage(ChatColor.AQUA + "Invite sent to " + to.getName()); return true; } return false; } if(cmd.getName().equalsIgnoreCase("hw")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(args.length < 1) { return false; } LeeroyHomeCommand command = this.plugin.sql.GetCommand(args[0]); if(!this.plugin.sql.PlayerHasCommand(command.commandString, p.getName())) { sender.sendMessage("You do not have access to that command."); return true; } String executor = command.commandExec; int argcount = 1; for(String arg : args) { executor = executor.replaceAll("{arg" + argcount + "}", arg); } executor = executor.replaceAll("{player}", p.getName()); executor = executor.replaceAll("{playerdisplay}", p.getDisplayName()); // Protective checks if(command.commandCheck.length != (args.length - 1)) { sender.sendMessage("Invalid arguments given for command /hw " + command.commandString); sender.sendMessage("Usage: " + command.commandUsage); return true; } argcount = 0; for(String a : args) { if(argcount == 0) { argcount++; continue; } switch(command.commandCheck[argcount-1]) { case "Player": if(this.plugin.getServer().getPlayer(a) == null) { sender.sendMessage(ChatColor.RED + "Player " + a + " not found."); sender.sendMessage("Usage: " + command.commandUsage); return true; } break; case "Integer": try { Integer.parseInt(a); } catch(NumberFormatException e) { sender.sendMessage(ChatColor.RED + "Invalid number, you supplied " + a); sender.sendMessage("Usage: " + command.commandUsage); return true; } break; case "String": break; default: sender.sendMessage(ChatColor.RED + "An unknown error occurred while checking your command."); this.plugin.getLogger().warning("Bad Homeworld Argument Type Given: " + command.commandCheck[argcount]); sender.sendMessage("Usage: " + command.commandUsage); return true; } } String[] executors = executor.split("\n"); for(String ex : executors) { this.plugin.getServer().dispatchCommand((CommandSender) (this.plugin.getServer().getConsoleSender()), ex); } return false; } if(cmd.getName().equalsIgnoreCase("upgrade")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(args.length != 1) { sender.sendMessage("You need to specify an upgrade to buy!"); return false; } if(this.plugin.sql.PlayerHasCommand(args[0], p.getName())) { sender.sendMessage("You have already purchased this upgrade!"); return true; } LeeroyHomeCommand command = this.plugin.sql.GetCommand(args[0]); if(command == null) { sender.sendMessage("Unknown command."); return true; } if(!this.plugin.eco.has(p.getName(), command.commandPrice)) { sender.sendMessage("You don't have enough money for this upgrade, it costs $" + ChatColor.GOLD + command.commandPrice + ChatColor.WHITE + " and you have $" + ChatColor.GOLD + this.plugin.eco.bankBalance(p.getName()).balance + ChatColor.WHITE + "."); return true; } this.plugin.sql.PurchaseCommand(command.commandString, p.getName()); this.plugin.eco.withdrawPlayer(p.getName(), command.commandPrice); this.plugin.eco.depositPlayer("lcbank", command.commandPrice); sender.sendMessage("Purchase successful!"); return true; } if(cmd.getName().equalsIgnoreCase("accept")) { if(!(sender instanceof Player)) { sender.sendMessage("You can only do this in-game!"); return true; } Player p = (Player)sender; if(!p.hasPermission("leeroy.accept")) { p.sendMessage("You do not have permission to do that!"); return true; } if(!plugin.inviteList.containsKey(p.getName())) { sender.sendMessage("Nobody has invited you to their home! :("); return true; } if(plugin.mvcore.getMVWorldManager().getUnloadedWorlds().contains(plugin.inviteList.get(p.getName()))) { sender.sendMessage("Nobody is in that world any more."); return true; } if(plugin.getServer().getPlayer(plugin.inviteList.get(p.getName()).replace("homeworld_", "")) == null) { sender.sendMessage("Player is not online."); return true; } p.teleport(plugin.mvcore.getMVWorldManager().getMVWorld(plugin.inviteList.get(p.getName())).getSpawnLocation()); plugin.getServer().getPlayer(plugin.inviteList.get(p.getName()).replace("homeworld_", "")).sendMessage(ChatColor.AQUA + p.getDisplayName() + " has accepted your invitation."); return true; } return false; }
diff --git a/river/src/main/java/org/jboss/marshalling/river/RiverUnmarshaller.java b/river/src/main/java/org/jboss/marshalling/river/RiverUnmarshaller.java index aec9552..d252701 100644 --- a/river/src/main/java/org/jboss/marshalling/river/RiverUnmarshaller.java +++ b/river/src/main/java/org/jboss/marshalling/river/RiverUnmarshaller.java @@ -1,1587 +1,1590 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import java.io.Externalizable; import java.io.IOException; import java.io.InvalidClassException; import java.io.InvalidObjectException; import java.io.NotSerializableException; import java.io.ObjectInput; import java.io.ObjectInputValidation; import java.io.Serializable; import java.io.StreamCorruptedException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.jboss.marshalling.AbstractUnmarshaller; import org.jboss.marshalling.Creator; import org.jboss.marshalling.Externalizer; import org.jboss.marshalling.MarshallerObjectInput; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.UTFUtils; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.reflect.SerializableField; import static org.jboss.marshalling.river.Protocol.*; /** * */ public class RiverUnmarshaller extends AbstractUnmarshaller { private final ArrayList<Object> instanceCache; private final ArrayList<ClassDescriptor> classCache; private final SerializableClassRegistry registry; private ObjectInput objectInput; private int version; private int depth; private BlockUnmarshaller blockUnmarshaller; private RiverObjectInputStream objectInputStream; private SortedSet<Validator> validators; private int validatorSeq; private static final Field proxyInvocationHandler; static { proxyInvocationHandler = AccessController.doPrivileged(new PrivilegedAction<Field>() { public Field run() { try { final Field field = Proxy.class.getDeclaredField("h"); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { throw new NoSuchFieldError(e.getMessage()); } } }); } protected RiverUnmarshaller(final RiverMarshallerFactory marshallerFactory, final SerializableClassRegistry registry, final MarshallingConfiguration configuration) { super(marshallerFactory, configuration); this.registry = registry; instanceCache = new ArrayList<Object>(configuration.getInstanceCount()); classCache = new ArrayList<ClassDescriptor>(configuration.getClassCount()); } public void clearInstanceCache() throws IOException { instanceCache.clear(); } public void clearClassCache() throws IOException { clearInstanceCache(); classCache.clear(); } public void close() throws IOException { finish(); } public void finish() throws IOException { super.finish(); blockUnmarshaller = null; objectInput = null; objectInputStream = null; } private ObjectInput getObjectInput() { final ObjectInput objectInput = this.objectInput; return objectInput == null ? (this.objectInput = (version > 0 ? getBlockUnmarshaller() : new MarshallerObjectInput(this))) : objectInput; } private BlockUnmarshaller getBlockUnmarshaller() { final BlockUnmarshaller blockUnmarshaller = this.blockUnmarshaller; return blockUnmarshaller == null ? this.blockUnmarshaller = new BlockUnmarshaller(this) : blockUnmarshaller; } private final PrivilegedExceptionAction<RiverObjectInputStream> createObjectInputStreamAction = new PrivilegedExceptionAction<RiverObjectInputStream>() { public RiverObjectInputStream run() throws IOException { return new RiverObjectInputStream(RiverUnmarshaller.this, version > 0 ? getBlockUnmarshaller() : RiverUnmarshaller.this); } }; private RiverObjectInputStream getObjectInputStream() throws IOException { final RiverObjectInputStream objectInputStream = this.objectInputStream; return objectInputStream == null ? this.objectInputStream = createObjectInputStream() : objectInputStream; } private RiverObjectInputStream createObjectInputStream() throws IOException { try { return AccessController.doPrivileged(createObjectInputStreamAction); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } } protected Object doReadObject(final boolean unshared) throws ClassNotFoundException, IOException { final Object obj = doReadObject(readUnsignedByte(), unshared); if (depth == 0) { final SortedSet<Validator> validators = this.validators; if (validators != null) { this.validators = null; validatorSeq = 0; for (Validator validator : validators) { validator.getValidation().validateObject(); } } } return obj; } @SuppressWarnings({ "unchecked" }) Object doReadObject(int leadByte, final boolean unshared) throws IOException, ClassNotFoundException { depth ++; try { for (;;) switch (leadByte) { case ID_NULL: { return null; } case ID_REPEAT_OBJECT_FAR: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } final int index = readInt(); try { final Object obj = instanceCache.get(index); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID (absolute " + index + ")"); } case ID_REPEAT_OBJECT_NEAR: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } final int index = readByte() | 0xffffff00; try { final Object obj = instanceCache.get(index + instanceCache.size()); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID (relative near " + index + ")"); } case ID_REPEAT_OBJECT_NEARISH: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } final int index = readShort() | 0xffff0000; try { final Object obj = instanceCache.get(index + instanceCache.size()); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID (relative nearish " + index + ")"); } case ID_NEW_OBJECT: case ID_NEW_OBJECT_UNSHARED: { if (unshared != (leadByte == ID_NEW_OBJECT_UNSHARED)) { throw sharedMismatch(); } return doReadNewObject(readUnsignedByte(), unshared); } // v2 string types case ID_STRING_EMPTY: { return ""; } case ID_STRING_SMALL: { // ignore unshared setting int length = readUnsignedByte(); final String s = UTFUtils.readUTFBytes(this, length == 0 ? 0x100 : length); instanceCache.add(s); return s; } case ID_STRING_MEDIUM: { // ignore unshared setting int length = readUnsignedShort(); final String s = UTFUtils.readUTFBytes(this, length == 0 ? 0x10000 : length); instanceCache.add(s); return s; } case ID_STRING_LARGE: { // ignore unshared setting int length = readInt(); if (length <= 0) { throw new StreamCorruptedException("Invalid length value for string in stream (" + length + ")"); } final String s = UTFUtils.readUTFBytes(this, length); instanceCache.add(s); return s; } case ID_ARRAY_EMPTY: case ID_ARRAY_EMPTY_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_EMPTY_UNSHARED)) { throw sharedMismatch(); } final ArrayList<Object> instanceCache = this.instanceCache; final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Array.newInstance(doReadClassDescriptor(readUnsignedByte()).getType(), 0); instanceCache.set(idx, obj); final Object resolvedObject = objectResolver.readResolve(obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return obj; } case ID_ARRAY_SMALL: case ID_ARRAY_SMALL_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_SMALL_UNSHARED)) { throw sharedMismatch(); } final int len = readUnsignedByte(); return doReadArray(len == 0 ? 0x100 : len, unshared); } case ID_ARRAY_MEDIUM: case ID_ARRAY_MEDIUM_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_MEDIUM_UNSHARED)) { throw sharedMismatch(); } final int len = readUnsignedShort(); return doReadArray(len == 0 ? 0x10000 : len, unshared); } case ID_ARRAY_LARGE: case ID_ARRAY_LARGE_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_LARGE_UNSHARED)) { throw sharedMismatch(); } - final int len = readUnsignedShort(); + final int len = readInt(); + if (len <= 0) { + throw new StreamCorruptedException("Invalid length value for array in stream (" + len + ")"); + } return doReadArray(len, unshared); } case ID_PREDEFINED_OBJECT: { if (unshared) { throw new InvalidObjectException("Attempt to read a predefined object as unshared"); } if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); final Object obj = objectTable.readObject(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); return obj; } else { return objectTable.readObject(this); } } case ID_BOOLEAN_OBJECT_TRUE: { return objectResolver.readResolve(Boolean.TRUE); } case ID_BOOLEAN_OBJECT_FALSE: { return objectResolver.readResolve(Boolean.FALSE); } case ID_BYTE_OBJECT: { return objectResolver.readResolve(Byte.valueOf(readByte())); } case ID_SHORT_OBJECT: { return objectResolver.readResolve(Short.valueOf(readShort())); } case ID_INTEGER_OBJECT: { return objectResolver.readResolve(Integer.valueOf(readInt())); } case ID_LONG_OBJECT: { return objectResolver.readResolve(Long.valueOf(readLong())); } case ID_FLOAT_OBJECT: { return objectResolver.readResolve(Float.valueOf(readFloat())); } case ID_DOUBLE_OBJECT: { return objectResolver.readResolve(Double.valueOf(readDouble())); } case ID_CHARACTER_OBJECT: { return objectResolver.readResolve(Character.valueOf(readChar())); } case ID_PRIM_BYTE: { return byte.class; } case ID_PRIM_BOOLEAN: { return boolean.class; } case ID_PRIM_CHAR: { return char.class; } case ID_PRIM_DOUBLE: { return double.class; } case ID_PRIM_FLOAT: { return float.class; } case ID_PRIM_INT: { return int.class; } case ID_PRIM_LONG: { return long.class; } case ID_PRIM_SHORT: { return short.class; } case ID_VOID: { return void.class; } case ID_BYTE_CLASS: { return Byte.class; } case ID_BOOLEAN_CLASS: { return Boolean.class; } case ID_CHARACTER_CLASS: { return Character.class; } case ID_DOUBLE_CLASS: { return Double.class; } case ID_FLOAT_CLASS: { return Float.class; } case ID_INTEGER_CLASS: { return Integer.class; } case ID_LONG_CLASS: { return Long.class; } case ID_SHORT_CLASS: { return Short.class; } case ID_VOID_CLASS: { return Void.class; } case ID_OBJECT_CLASS: { return Object.class; } case ID_CLASS_CLASS: { return Class.class; } case ID_STRING_CLASS: { return String.class; } case ID_ENUM_CLASS: { return Enum.class; } case ID_BYTE_ARRAY_CLASS: { return byte[].class; } case ID_BOOLEAN_ARRAY_CLASS: { return boolean[].class; } case ID_CHAR_ARRAY_CLASS: { return char[].class; } case ID_DOUBLE_ARRAY_CLASS: { return double[].class; } case ID_FLOAT_ARRAY_CLASS: { return float[].class; } case ID_INT_ARRAY_CLASS: { return int[].class; } case ID_LONG_ARRAY_CLASS: { return long[].class; } case ID_SHORT_ARRAY_CLASS: { return short[].class; } case ID_CC_ARRAY_LIST: { return ArrayList.class; } case ID_CC_HASH_MAP: { return HashMap.class; } case ID_CC_HASH_SET: { return HashSet.class; } case ID_CC_HASHTABLE: { return Hashtable.class; } case ID_CC_IDENTITY_HASH_MAP: { return HashMap.class; } case ID_CC_LINKED_HASH_MAP: { return LinkedHashMap.class; } case ID_CC_LINKED_HASH_SET: { return LinkedHashSet.class; } case ID_CC_LINKED_LIST: { return LinkedList.class; } case ID_CC_TREE_MAP: { return TreeMap.class; } case ID_CC_TREE_SET: { return TreeSet.class; } case ID_SINGLETON_LIST_OBJECT: { final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Collections.singletonList(doReadObject(false)); final Object resolvedObject = objectResolver.readResolve(obj); if (! unshared) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_SINGLETON_SET_OBJECT: { final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Collections.singleton(doReadObject(false)); final Object resolvedObject = objectResolver.readResolve(obj); if (! unshared) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_SINGLETON_MAP_OBJECT: { final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Collections.singletonMap(doReadObject(false), doReadObject(false)); final Object resolvedObject = objectResolver.readResolve(obj); if (! unshared) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_EMPTY_LIST_OBJECT: { return Collections.emptyList(); } case ID_EMPTY_SET_OBJECT: { return Collections.emptySet(); } case ID_EMPTY_MAP_OBJECT: { return Collections.emptyMap(); } case ID_COLLECTION_EMPTY: case ID_COLLECTION_EMPTY_UNSHARED: case ID_COLLECTION_SMALL: case ID_COLLECTION_SMALL_UNSHARED: case ID_COLLECTION_MEDIUM: case ID_COLLECTION_MEDIUM_UNSHARED: case ID_COLLECTION_LARGE: case ID_COLLECTION_LARGE_UNSHARED: { final int len; switch (leadByte) { case ID_COLLECTION_EMPTY: case ID_COLLECTION_EMPTY_UNSHARED: { len = 0; break; } case ID_COLLECTION_SMALL: case ID_COLLECTION_SMALL_UNSHARED: { int b = readUnsignedByte(); len = b == 0 ? 0x100 : b; break; } case ID_COLLECTION_MEDIUM: case ID_COLLECTION_MEDIUM_UNSHARED: { int b = readUnsignedShort(); len = b == 0 ? 0x10000 : b; break; } case ID_COLLECTION_LARGE: case ID_COLLECTION_LARGE_UNSHARED: { len = readInt(); break; } default: { throw new IllegalStateException(); } } final int id = readUnsignedByte(); final int idx; final ArrayList<Object> instanceCache = this.instanceCache; switch (id) { case ID_CC_ARRAY_LIST: { final Collection target = new ArrayList(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_HASH_SET: { final Collection target = new HashSet(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_LINKED_HASH_SET: { final Collection target = new LinkedHashSet(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_LINKED_LIST: { final Collection target = new LinkedList(); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_TREE_SET: { final Collection target = new TreeSet((Comparator)doReadObject(false)); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_HASH_MAP: { final Map target = new HashMap(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_HASHTABLE: { final Map target = new Hashtable(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_IDENTITY_HASH_MAP: { final Map target = new IdentityHashMap(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_LINKED_HASH_MAP: { final Map target = new LinkedHashMap(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_TREE_MAP: { final Map target = new TreeMap((Comparator)doReadObject(false)); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } default: { throw new StreamCorruptedException("Unexpected byte foudn when reading a collection type: " + leadByte); } } } case ID_CLEAR_CLASS_CACHE: { if (depth > 1) { throw new StreamCorruptedException("ID_CLEAR_CLASS_CACHE token in the middle of stream processing"); } classCache.clear(); instanceCache.clear(); leadByte = readUnsignedByte(); continue; } case ID_CLEAR_INSTANCE_CACHE: { if (depth > 1) { throw new StreamCorruptedException("ID_CLEAR_INSTANCE_CACHE token in the middle of stream processing"); } instanceCache.clear(); continue; } default: { throw new StreamCorruptedException("Unexpected byte found when reading an object: " + leadByte); } } } finally { depth --; } } private static InvalidObjectException sharedMismatch() { return new InvalidObjectException("Shared/unshared object mismatch"); } ClassDescriptor doReadClassDescriptor(final int classType) throws IOException, ClassNotFoundException { final ArrayList<ClassDescriptor> classCache = this.classCache; switch (classType) { case ID_REPEAT_CLASS_FAR: { return classCache.get(readInt()); } case ID_REPEAT_CLASS_NEAR: { return classCache.get((readByte() | 0xffffff00) + classCache.size()); } case ID_REPEAT_CLASS_NEARISH: { return classCache.get((readShort() | 0xffff0000) + classCache.size()); } case ID_PREDEFINED_ENUM_TYPE_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class<?> type = readClassTableClass(); final ClassDescriptor descriptor = new ClassDescriptor(type, ID_ENUM_TYPE_CLASS); classCache.set(idx, descriptor); return descriptor; } case ID_PREDEFINED_EXTERNALIZABLE_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class<?> type = readClassTableClass(); final ClassDescriptor descriptor = new ClassDescriptor(type, ID_EXTERNALIZABLE_CLASS); classCache.set(idx, descriptor); return descriptor; } case ID_PREDEFINED_EXTERNALIZER_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class<?> type = readClassTableClass(); final Externalizer externalizer = (Externalizer) readObject(); final ClassDescriptor descriptor = new ExternalizerClassDescriptor(type, externalizer); classCache.set(idx, descriptor); return descriptor; } case ID_PREDEFINED_PLAIN_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class<?> type = readClassTableClass(); final ClassDescriptor descriptor = new ClassDescriptor(type, ID_PLAIN_CLASS); classCache.set(idx, descriptor); return descriptor; } case ID_PREDEFINED_PROXY_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class<?> type = readClassTableClass(); final ClassDescriptor descriptor = new ClassDescriptor(type, ID_PROXY_CLASS); classCache.set(idx, descriptor); return descriptor; } case ID_PREDEFINED_SERIALIZABLE_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class<?> type = readClassTableClass(); final SerializableClass serializableClass = registry.lookup(type); int descType = version > 0 && serializableClass.hasWriteObject() ? ID_WRITE_OBJECT_CLASS : ID_SERIALIZABLE_CLASS; final ClassDescriptor descriptor = new SerializableClassDescriptor(serializableClass, doReadClassDescriptor(readUnsignedByte()), serializableClass.getFields(), descType); classCache.set(idx, descriptor); return descriptor; } case ID_PLAIN_CLASS: { final String className = readString(); final Class<?> clazz = doResolveClass(className, 0L); final ClassDescriptor descriptor = new ClassDescriptor(clazz, ID_PLAIN_CLASS); classCache.add(descriptor); return descriptor; } case ID_PROXY_CLASS: { String[] interfaces = new String[readInt()]; for (int i = 0; i < interfaces.length; i ++) { interfaces[i] = readString(); } final ClassDescriptor descriptor; if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); descriptor = new ClassDescriptor(classResolver.resolveProxyClass(blockUnmarshaller, interfaces), ID_PROXY_CLASS); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { descriptor = new ClassDescriptor(classResolver.resolveProxyClass(this, interfaces), ID_PROXY_CLASS); } classCache.add(descriptor); return descriptor; } case ID_WRITE_OBJECT_CLASS: case ID_SERIALIZABLE_CLASS: { int idx = classCache.size(); classCache.add(null); final String className = readString(); final long uid = readLong(); final Class<?> clazz = doResolveClass(className, uid); final Class<?> superClazz = clazz.getSuperclass(); classCache.set(idx, new IncompleteClassDescriptor(clazz, classType)); final int cnt = readInt(); final String[] names = new String[cnt]; final ClassDescriptor[] descriptors = new ClassDescriptor[cnt]; final boolean[] unshareds = new boolean[cnt]; for (int i = 0; i < cnt; i ++) { names[i] = readUTF(); descriptors[i] = doReadClassDescriptor(readUnsignedByte()); unshareds[i] = readBoolean(); } ClassDescriptor superDescriptor = doReadClassDescriptor(readUnsignedByte()); if (superDescriptor != null) { final Class<?> superType = superDescriptor.getType(); if (! superType.isAssignableFrom(clazz)) { throw new InvalidClassException(clazz.getName(), "Class does not extend stream superclass"); } Class<?> cl = superClazz; while (cl != superType) { superDescriptor = new SerializableClassDescriptor(registry.lookup(cl), superDescriptor); cl = cl.getSuperclass(); } } else if (superClazz != null) { Class<?> cl = superClazz; while (Serializable.class.isAssignableFrom(cl)) { superDescriptor = new SerializableClassDescriptor(registry.lookup(cl), superDescriptor); cl = cl.getSuperclass(); } } final SerializableClass serializableClass = registry.lookup(clazz); final SerializableField[] fields = new SerializableField[cnt]; for (int i = 0; i < cnt; i ++) { fields[i] = serializableClass.getSerializableField(names[i], descriptors[i].getType(), unshareds[i]); } final ClassDescriptor descriptor = new SerializableClassDescriptor(serializableClass, superDescriptor, fields, classType); classCache.set(idx, descriptor); return descriptor; } case ID_EXTERNALIZABLE_CLASS: { final String className = readString(); final long uid = readLong(); final Class<?> clazz = doResolveClass(className, uid); final ClassDescriptor descriptor = new ClassDescriptor(clazz, ID_EXTERNALIZABLE_CLASS); classCache.add(descriptor); return descriptor; } case ID_EXTERNALIZER_CLASS: { final String className = readString(); int idx = classCache.size(); classCache.add(null); final Class<?> clazz = doResolveClass(className, 0L); final Externalizer externalizer = (Externalizer) readObject(); final ClassDescriptor descriptor = new ExternalizerClassDescriptor(clazz, externalizer); classCache.set(idx, descriptor); return descriptor; } case ID_ENUM_TYPE_CLASS: { final ClassDescriptor descriptor = new ClassDescriptor(doResolveClass(readString(), 0L), ID_ENUM_TYPE_CLASS); classCache.add(descriptor); return descriptor; } case ID_OBJECT_ARRAY_TYPE_CLASS: { final ClassDescriptor elementType = doReadClassDescriptor(readUnsignedByte()); final ClassDescriptor arrayDescriptor = new ClassDescriptor(Array.newInstance(elementType.getType(), 0).getClass(), ID_OBJECT_ARRAY_TYPE_CLASS); classCache.add(arrayDescriptor); return arrayDescriptor; } case ID_CC_ARRAY_LIST: { return ClassDescriptor.CC_ARRAY_LIST; } case ID_CC_LINKED_LIST: { return ClassDescriptor.CC_LINKED_LIST; } case ID_CC_HASH_SET: { return ClassDescriptor.CC_HASH_SET; } case ID_CC_LINKED_HASH_SET: { return ClassDescriptor.CC_LINKED_HASH_SET; } case ID_CC_TREE_SET: { return ClassDescriptor.CC_TREE_SET; } case ID_CC_IDENTITY_HASH_MAP: { return ClassDescriptor.CC_IDENTITY_HASH_MAP; } case ID_CC_HASH_MAP: { return ClassDescriptor.CC_HASH_MAP; } case ID_CC_HASHTABLE: { return ClassDescriptor.CC_HASHTABLE; } case ID_CC_LINKED_HASH_MAP: { return ClassDescriptor.CC_LINKED_HASH_MAP; } case ID_CC_TREE_MAP: { return ClassDescriptor.CC_TREE_MAP; } case ID_STRING_CLASS: { return ClassDescriptor.STRING_DESCRIPTOR; } case ID_OBJECT_CLASS: { return ClassDescriptor.OBJECT_DESCRIPTOR; } case ID_CLASS_CLASS: { return ClassDescriptor.CLASS_DESCRIPTOR; } case ID_ENUM_CLASS: { return ClassDescriptor.ENUM_DESCRIPTOR; } case ID_BOOLEAN_ARRAY_CLASS: { return ClassDescriptor.BOOLEAN_ARRAY; } case ID_BYTE_ARRAY_CLASS: { return ClassDescriptor.BYTE_ARRAY; } case ID_SHORT_ARRAY_CLASS: { return ClassDescriptor.SHORT_ARRAY; } case ID_INT_ARRAY_CLASS: { return ClassDescriptor.INT_ARRAY; } case ID_LONG_ARRAY_CLASS: { return ClassDescriptor.LONG_ARRAY; } case ID_CHAR_ARRAY_CLASS: { return ClassDescriptor.CHAR_ARRAY; } case ID_FLOAT_ARRAY_CLASS: { return ClassDescriptor.FLOAT_ARRAY; } case ID_DOUBLE_ARRAY_CLASS: { return ClassDescriptor.DOUBLE_ARRAY; } case ID_PRIM_BOOLEAN: { return ClassDescriptor.BOOLEAN; } case ID_PRIM_BYTE: { return ClassDescriptor.BYTE; } case ID_PRIM_CHAR: { return ClassDescriptor.CHAR; } case ID_PRIM_DOUBLE: { return ClassDescriptor.DOUBLE; } case ID_PRIM_FLOAT: { return ClassDescriptor.FLOAT; } case ID_PRIM_INT: { return ClassDescriptor.INT; } case ID_PRIM_LONG: { return ClassDescriptor.LONG; } case ID_PRIM_SHORT: { return ClassDescriptor.SHORT; } case ID_VOID: { return ClassDescriptor.VOID; } case ID_BOOLEAN_CLASS: { return ClassDescriptor.BOOLEAN_OBJ; } case ID_BYTE_CLASS: { return ClassDescriptor.BYTE_OBJ; } case ID_SHORT_CLASS: { return ClassDescriptor.SHORT_OBJ; } case ID_INTEGER_CLASS: { return ClassDescriptor.INTEGER_OBJ; } case ID_LONG_CLASS: { return ClassDescriptor.LONG_OBJ; } case ID_CHARACTER_CLASS: { return ClassDescriptor.CHARACTER_OBJ; } case ID_FLOAT_CLASS: { return ClassDescriptor.FLOAT_OBJ; } case ID_DOUBLE_CLASS: { return ClassDescriptor.DOUBLE_OBJ; } case ID_VOID_CLASS: { return ClassDescriptor.VOID_OBJ; } default: { throw new InvalidClassException("Unexpected class ID " + classType); } } } private Class<?> readClassTableClass() throws IOException, ClassNotFoundException { if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); final Class<?> type = classTable.readClass(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); return type; } else { return classTable.readClass(this); } } private Class<?> doResolveClass(final String className, final long uid) throws IOException, ClassNotFoundException { if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); final Class<?> resolvedClass = classResolver.resolveClass(blockUnmarshaller, className, uid); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); return resolvedClass; } else { return classResolver.resolveClass(this, className, uid); } } protected String readString() throws IOException { final int length = readInt(); return UTFUtils.readUTFBytes(this, length); } private static final class DummyInvocationHandler implements InvocationHandler { public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { throw new NoSuchMethodError("Invocation handler not yet loaded"); } } protected void doStart() throws IOException { super.doStart(); if (configuredVersion > 0) { int version = readUnsignedByte(); if (version > MAX_VERSION) { throw new IOException("Unsupported protocol version " + version); } this.version = version; } else { version = 0; } } private static final InvocationHandler DUMMY_HANDLER = new DummyInvocationHandler(); private static Object createProxyInstance(Creator creator, Class<?> type) throws IOException { try { return creator.create(type); } catch (Exception e) { return Proxy.newProxyInstance(type.getClassLoader(), type.getInterfaces(), DUMMY_HANDLER); } } protected Object doReadNewObject(final int streamClassType, final boolean unshared) throws ClassNotFoundException, IOException { final ClassDescriptor descriptor = doReadClassDescriptor(streamClassType); final int classType = descriptor.getTypeID(); final List<Object> instanceCache = this.instanceCache; switch (classType) { case ID_PROXY_CLASS: { final Class<?> type = descriptor.getType(); final Object obj = createProxyInstance(creator, type); final int idx = instanceCache.size(); instanceCache.add(obj); try { proxyInvocationHandler.set(obj, doReadObject(unshared)); } catch (IllegalAccessException e) { throw new InvalidClassException(type.getName(), "Unable to set proxy invocation handler"); } final Object resolvedObject = objectResolver.readResolve(obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_WRITE_OBJECT_CLASS: case ID_SERIALIZABLE_CLASS: { final SerializableClassDescriptor serializableClassDescriptor = (SerializableClassDescriptor) descriptor; final Class<?> type = descriptor.getType(); final SerializableClass serializableClass = serializableClassDescriptor.getSerializableClass(); final Object obj = creator.create(type); final int idx = instanceCache.size(); instanceCache.add(obj); doInitSerializable(obj, serializableClassDescriptor); final Object resolvedObject = objectResolver.readResolve(serializableClass.hasReadResolve() ? serializableClass.callReadResolve(obj) : obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_EXTERNALIZABLE_CLASS: { final Class<?> type = descriptor.getType(); final SerializableClass serializableClass = registry.lookup(type); final Externalizable obj = (Externalizable) creator.create(type); final int idx = instanceCache.size(); instanceCache.add(obj); if (version > 0) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); obj.readExternal(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { obj.readExternal(getObjectInput()); } final Object resolvedObject = objectResolver.readResolve(serializableClass.hasReadResolve() ? serializableClass.callReadResolve(obj) : obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_EXTERNALIZER_CLASS: { final int idx = instanceCache.size(); instanceCache.add(null); Externalizer externalizer = ((ExternalizerClassDescriptor) descriptor).getExternalizer(); final Class<?> type = descriptor.getType(); final SerializableClass serializableClass = registry.lookup(type); final Object obj; if (version > 0) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); obj = externalizer.createExternal(type, blockUnmarshaller, creator); instanceCache.set(idx, obj); externalizer.readExternal(obj, blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { obj = externalizer.createExternal(type, this, creator); instanceCache.set(idx, obj); externalizer.readExternal(obj, getObjectInput()); } final Object resolvedObject = objectResolver.readResolve(serializableClass.hasReadResolve() ? serializableClass.callReadResolve(obj) : obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_ENUM_TYPE_CLASS: { final String name = readString(); final Enum obj = resolveEnumConstant(descriptor, name); final int idx = instanceCache.size(); instanceCache.add(obj); final Object resolvedObject = objectResolver.readResolve(obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_OBJECT_ARRAY_TYPE_CLASS: { return doReadObjectArray(readInt(), descriptor.getType().getComponentType(), unshared); } case ID_STRING_CLASS: { // v1 string final String obj = readString(); final Object resolvedObject = objectResolver.readResolve(obj); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } case ID_CLASS_CLASS: { final ClassDescriptor nestedDescriptor = doReadClassDescriptor(readUnsignedByte()); // Classes are not resolved and may not be unshared! final Class<?> obj = nestedDescriptor.getType(); return obj; } case ID_BOOLEAN_ARRAY_CLASS: { return doReadBooleanArray(readInt(), unshared); } case ID_BYTE_ARRAY_CLASS: { return doReadByteArray(readInt(), unshared); } case ID_SHORT_ARRAY_CLASS: { return doReadShortArray(readInt(), unshared); } case ID_INT_ARRAY_CLASS: { return doReadIntArray(readInt(), unshared); } case ID_LONG_ARRAY_CLASS: { return doReadLongArray(readInt(), unshared); } case ID_CHAR_ARRAY_CLASS: { return doReadCharArray(readInt(), unshared); } case ID_FLOAT_ARRAY_CLASS: { return doReadFloatArray(readInt(), unshared); } case ID_DOUBLE_ARRAY_CLASS: { return doReadDoubleArray(readInt(), unshared); } case ID_BOOLEAN_CLASS: { return objectResolver.readResolve(Boolean.valueOf(readBoolean())); } case ID_BYTE_CLASS: { return objectResolver.readResolve(Byte.valueOf(readByte())); } case ID_SHORT_CLASS: { return objectResolver.readResolve(Short.valueOf(readShort())); } case ID_INTEGER_CLASS: { return objectResolver.readResolve(Integer.valueOf(readInt())); } case ID_LONG_CLASS: { return objectResolver.readResolve(Long.valueOf(readLong())); } case ID_CHARACTER_CLASS: { return objectResolver.readResolve(Character.valueOf(readChar())); } case ID_FLOAT_CLASS: { return objectResolver.readResolve(Float.valueOf(readFloat())); } case ID_DOUBLE_CLASS: { return objectResolver.readResolve(Double.valueOf(readDouble())); } case ID_OBJECT_CLASS: case ID_PLAIN_CLASS: { throw new NotSerializableException("(remote)" + descriptor.getType().getName()); } default: { throw new InvalidObjectException("Unexpected class type " + classType); } } } private Object doReadDoubleArray(final int cnt, final boolean unshared) throws IOException { final double[] array = new double[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readDouble(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } private Object doReadFloatArray(final int cnt, final boolean unshared) throws IOException { final float[] array = new float[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readFloat(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } private Object doReadCharArray(final int cnt, final boolean unshared) throws IOException { final char[] array = new char[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readChar(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } private Object doReadLongArray(final int cnt, final boolean unshared) throws IOException { final long[] array = new long[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readLong(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } private Object doReadIntArray(final int cnt, final boolean unshared) throws IOException { final int[] array = new int[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readInt(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } private Object doReadShortArray(final int cnt, final boolean unshared) throws IOException { final short[] array = new short[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readShort(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } private Object doReadByteArray(final int cnt, final boolean unshared) throws IOException { final byte[] array = new byte[cnt]; readFully(array, 0, array.length); final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } private Object doReadBooleanArray(final int cnt, final boolean unshared) throws IOException { final boolean[] array = new boolean[cnt]; int v = 0; int bc = cnt & ~7; for (int i = 0; i < bc; ) { v = readByte(); array[i++] = (v & 1) != 0; array[i++] = (v & 2) != 0; array[i++] = (v & 4) != 0; array[i++] = (v & 8) != 0; array[i++] = (v & 16) != 0; array[i++] = (v & 32) != 0; array[i++] = (v & 64) != 0; array[i++] = (v & 128) != 0; } if (bc < cnt) { v = readByte(); switch (cnt & 7) { case 7: array[bc + 6] = (v & 64) != 0; case 6: array[bc + 5] = (v & 32) != 0; case 5: array[bc + 4] = (v & 16) != 0; case 4: array[bc + 3] = (v & 8) != 0; case 3: array[bc + 2] = (v & 4) != 0; case 2: array[bc + 1] = (v & 2) != 0; case 1: array[bc] = (v & 1) != 0; } } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } private Object doReadObjectArray(final int cnt, final Class<?> type, final boolean unshared) throws ClassNotFoundException, IOException { final Object[] array = (Object[]) Array.newInstance(type, cnt); final int idx = instanceCache.size(); instanceCache.add(array); for (int i = 0; i < cnt; i ++) { array[i] = doReadObject(unshared); } final Object resolvedObject = objectResolver.readResolve(array); if (unshared) { instanceCache.set(idx, null); } else if (array != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } private Object doReadArray(final int cnt, final boolean unshared) throws ClassNotFoundException, IOException { final int leadByte = readUnsignedByte(); switch (leadByte) { case ID_PRIM_BOOLEAN: { return doReadBooleanArray(cnt, unshared); } case ID_PRIM_BYTE: { return doReadByteArray(cnt, unshared); } case ID_PRIM_CHAR: { return doReadCharArray(cnt, unshared); } case ID_PRIM_DOUBLE: { return doReadDoubleArray(cnt, unshared); } case ID_PRIM_FLOAT: { return doReadFloatArray(cnt, unshared); } case ID_PRIM_INT: { return doReadIntArray(cnt, unshared); } case ID_PRIM_LONG: { return doReadLongArray(cnt, unshared); } case ID_PRIM_SHORT: { return doReadShortArray(cnt, unshared); } default: { return doReadObjectArray(cnt, doReadClassDescriptor(leadByte).getType(), unshared); } } } @SuppressWarnings({"unchecked"}) private static Enum resolveEnumConstant(final ClassDescriptor descriptor, final String name) { return Enum.valueOf((Class<? extends Enum>)descriptor.getType(), name); } private void doInitSerializable(final Object obj, final SerializableClassDescriptor descriptor) throws IOException, ClassNotFoundException { final Class<?> type = descriptor.getType(); final SerializableClass info = registry.lookup(type); final ClassDescriptor superDescriptor = descriptor.getSuperClassDescriptor(); if (superDescriptor instanceof SerializableClassDescriptor) { final SerializableClassDescriptor serializableSuperDescriptor = (SerializableClassDescriptor) superDescriptor; doInitSerializable(obj, serializableSuperDescriptor); } final int typeId = descriptor.getTypeID(); final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); if (descriptor.isGap()) { if (info.hasReadObjectNoData()) { info.callReadObjectNoData(obj); } } else if (info.hasReadObject()) { final RiverObjectInputStream objectInputStream = getObjectInputStream(); final SerializableClassDescriptor oldDescriptor = objectInputStream.swapClass(descriptor); final Object oldObj = objectInputStream.swapCurrent(obj); final RiverObjectInputStream.State restoreState = objectInputStream.start(); boolean ok = false; try { if (typeId == ID_WRITE_OBJECT_CLASS) { // protocol version >= 1; read fields info.callReadObject(obj, objectInputStream); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else if (version >= 1) { // protocol version >= 1 but no fields to read blockUnmarshaller.endOfStream(); info.callReadObject(obj, objectInputStream); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { // protocol version 0 info.callReadObject(obj, objectInputStream); } objectInputStream.finish(restoreState); objectInputStream.swapCurrent(oldObj); objectInputStream.swapClass(oldDescriptor); ok = true; } finally { if (! ok) { objectInputStream.fullReset(); } } } else { readFields(obj, descriptor); if (typeId == ID_WRITE_OBJECT_CLASS) { // protocol version >= 1 with useless user data blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } } } protected void readFields(final Object obj, final SerializableClassDescriptor descriptor) throws IOException, ClassNotFoundException { for (SerializableField serializableField : descriptor.getFields()) { final Field field = serializableField.getField(); if (field == null) { // missing; consume stream data only switch (serializableField.getKind()) { case BOOLEAN: { readBoolean(); break; } case BYTE: { readByte(); break; } case CHAR: { readChar(); break; } case DOUBLE: { readDouble(); break; } case FLOAT: { readFloat(); break; } case INT: { readInt(); break; } case LONG: { readLong(); break; } case OBJECT: { if (serializableField.isUnshared()) { readObjectUnshared(); } else { readObject(); } break; } case SHORT: { readShort(); break; } } } else try { switch (serializableField.getKind()) { case BOOLEAN: { field.setBoolean(obj, readBoolean()); break; } case BYTE: { field.setByte(obj, readByte()); break; } case CHAR: { field.setChar(obj, readChar()); break; } case DOUBLE: { field.setDouble(obj, readDouble()); break; } case FLOAT: { field.setFloat(obj, readFloat()); break; } case INT: { field.setInt(obj, readInt()); break; } case LONG: { field.setLong(obj, readLong()); break; } case OBJECT: { final Object robj; if (serializableField.isUnshared()) { robj = readObjectUnshared(); } else { robj = readObject(); } field.set(obj, robj); break; } case SHORT: { field.setShort(obj, readShort()); break; } } } catch (IllegalAccessException e) { final InvalidObjectException ioe = new InvalidObjectException("Unable to set a field"); ioe.initCause(e); throw ioe; } } } void addValidation(final ObjectInputValidation validation, final int prio) { final Validator validator = new Validator(prio, validatorSeq++, validation); final SortedSet<Validator> validators = this.validators; (validators == null ? this.validators = new TreeSet<Validator>() : validators).add(validator); } public String readUTF() throws IOException { final int len = readInt(); return UTFUtils.readUTFBytes(this, len); } }
true
true
Object doReadObject(int leadByte, final boolean unshared) throws IOException, ClassNotFoundException { depth ++; try { for (;;) switch (leadByte) { case ID_NULL: { return null; } case ID_REPEAT_OBJECT_FAR: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } final int index = readInt(); try { final Object obj = instanceCache.get(index); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID (absolute " + index + ")"); } case ID_REPEAT_OBJECT_NEAR: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } final int index = readByte() | 0xffffff00; try { final Object obj = instanceCache.get(index + instanceCache.size()); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID (relative near " + index + ")"); } case ID_REPEAT_OBJECT_NEARISH: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } final int index = readShort() | 0xffff0000; try { final Object obj = instanceCache.get(index + instanceCache.size()); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID (relative nearish " + index + ")"); } case ID_NEW_OBJECT: case ID_NEW_OBJECT_UNSHARED: { if (unshared != (leadByte == ID_NEW_OBJECT_UNSHARED)) { throw sharedMismatch(); } return doReadNewObject(readUnsignedByte(), unshared); } // v2 string types case ID_STRING_EMPTY: { return ""; } case ID_STRING_SMALL: { // ignore unshared setting int length = readUnsignedByte(); final String s = UTFUtils.readUTFBytes(this, length == 0 ? 0x100 : length); instanceCache.add(s); return s; } case ID_STRING_MEDIUM: { // ignore unshared setting int length = readUnsignedShort(); final String s = UTFUtils.readUTFBytes(this, length == 0 ? 0x10000 : length); instanceCache.add(s); return s; } case ID_STRING_LARGE: { // ignore unshared setting int length = readInt(); if (length <= 0) { throw new StreamCorruptedException("Invalid length value for string in stream (" + length + ")"); } final String s = UTFUtils.readUTFBytes(this, length); instanceCache.add(s); return s; } case ID_ARRAY_EMPTY: case ID_ARRAY_EMPTY_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_EMPTY_UNSHARED)) { throw sharedMismatch(); } final ArrayList<Object> instanceCache = this.instanceCache; final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Array.newInstance(doReadClassDescriptor(readUnsignedByte()).getType(), 0); instanceCache.set(idx, obj); final Object resolvedObject = objectResolver.readResolve(obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return obj; } case ID_ARRAY_SMALL: case ID_ARRAY_SMALL_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_SMALL_UNSHARED)) { throw sharedMismatch(); } final int len = readUnsignedByte(); return doReadArray(len == 0 ? 0x100 : len, unshared); } case ID_ARRAY_MEDIUM: case ID_ARRAY_MEDIUM_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_MEDIUM_UNSHARED)) { throw sharedMismatch(); } final int len = readUnsignedShort(); return doReadArray(len == 0 ? 0x10000 : len, unshared); } case ID_ARRAY_LARGE: case ID_ARRAY_LARGE_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_LARGE_UNSHARED)) { throw sharedMismatch(); } final int len = readUnsignedShort(); return doReadArray(len, unshared); } case ID_PREDEFINED_OBJECT: { if (unshared) { throw new InvalidObjectException("Attempt to read a predefined object as unshared"); } if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); final Object obj = objectTable.readObject(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); return obj; } else { return objectTable.readObject(this); } } case ID_BOOLEAN_OBJECT_TRUE: { return objectResolver.readResolve(Boolean.TRUE); } case ID_BOOLEAN_OBJECT_FALSE: { return objectResolver.readResolve(Boolean.FALSE); } case ID_BYTE_OBJECT: { return objectResolver.readResolve(Byte.valueOf(readByte())); } case ID_SHORT_OBJECT: { return objectResolver.readResolve(Short.valueOf(readShort())); } case ID_INTEGER_OBJECT: { return objectResolver.readResolve(Integer.valueOf(readInt())); } case ID_LONG_OBJECT: { return objectResolver.readResolve(Long.valueOf(readLong())); } case ID_FLOAT_OBJECT: { return objectResolver.readResolve(Float.valueOf(readFloat())); } case ID_DOUBLE_OBJECT: { return objectResolver.readResolve(Double.valueOf(readDouble())); } case ID_CHARACTER_OBJECT: { return objectResolver.readResolve(Character.valueOf(readChar())); } case ID_PRIM_BYTE: { return byte.class; } case ID_PRIM_BOOLEAN: { return boolean.class; } case ID_PRIM_CHAR: { return char.class; } case ID_PRIM_DOUBLE: { return double.class; } case ID_PRIM_FLOAT: { return float.class; } case ID_PRIM_INT: { return int.class; } case ID_PRIM_LONG: { return long.class; } case ID_PRIM_SHORT: { return short.class; } case ID_VOID: { return void.class; } case ID_BYTE_CLASS: { return Byte.class; } case ID_BOOLEAN_CLASS: { return Boolean.class; } case ID_CHARACTER_CLASS: { return Character.class; } case ID_DOUBLE_CLASS: { return Double.class; } case ID_FLOAT_CLASS: { return Float.class; } case ID_INTEGER_CLASS: { return Integer.class; } case ID_LONG_CLASS: { return Long.class; } case ID_SHORT_CLASS: { return Short.class; } case ID_VOID_CLASS: { return Void.class; } case ID_OBJECT_CLASS: { return Object.class; } case ID_CLASS_CLASS: { return Class.class; } case ID_STRING_CLASS: { return String.class; } case ID_ENUM_CLASS: { return Enum.class; } case ID_BYTE_ARRAY_CLASS: { return byte[].class; } case ID_BOOLEAN_ARRAY_CLASS: { return boolean[].class; } case ID_CHAR_ARRAY_CLASS: { return char[].class; } case ID_DOUBLE_ARRAY_CLASS: { return double[].class; } case ID_FLOAT_ARRAY_CLASS: { return float[].class; } case ID_INT_ARRAY_CLASS: { return int[].class; } case ID_LONG_ARRAY_CLASS: { return long[].class; } case ID_SHORT_ARRAY_CLASS: { return short[].class; } case ID_CC_ARRAY_LIST: { return ArrayList.class; } case ID_CC_HASH_MAP: { return HashMap.class; } case ID_CC_HASH_SET: { return HashSet.class; } case ID_CC_HASHTABLE: { return Hashtable.class; } case ID_CC_IDENTITY_HASH_MAP: { return HashMap.class; } case ID_CC_LINKED_HASH_MAP: { return LinkedHashMap.class; } case ID_CC_LINKED_HASH_SET: { return LinkedHashSet.class; } case ID_CC_LINKED_LIST: { return LinkedList.class; } case ID_CC_TREE_MAP: { return TreeMap.class; } case ID_CC_TREE_SET: { return TreeSet.class; } case ID_SINGLETON_LIST_OBJECT: { final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Collections.singletonList(doReadObject(false)); final Object resolvedObject = objectResolver.readResolve(obj); if (! unshared) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_SINGLETON_SET_OBJECT: { final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Collections.singleton(doReadObject(false)); final Object resolvedObject = objectResolver.readResolve(obj); if (! unshared) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_SINGLETON_MAP_OBJECT: { final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Collections.singletonMap(doReadObject(false), doReadObject(false)); final Object resolvedObject = objectResolver.readResolve(obj); if (! unshared) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_EMPTY_LIST_OBJECT: { return Collections.emptyList(); } case ID_EMPTY_SET_OBJECT: { return Collections.emptySet(); } case ID_EMPTY_MAP_OBJECT: { return Collections.emptyMap(); } case ID_COLLECTION_EMPTY: case ID_COLLECTION_EMPTY_UNSHARED: case ID_COLLECTION_SMALL: case ID_COLLECTION_SMALL_UNSHARED: case ID_COLLECTION_MEDIUM: case ID_COLLECTION_MEDIUM_UNSHARED: case ID_COLLECTION_LARGE: case ID_COLLECTION_LARGE_UNSHARED: { final int len; switch (leadByte) { case ID_COLLECTION_EMPTY: case ID_COLLECTION_EMPTY_UNSHARED: { len = 0; break; } case ID_COLLECTION_SMALL: case ID_COLLECTION_SMALL_UNSHARED: { int b = readUnsignedByte(); len = b == 0 ? 0x100 : b; break; } case ID_COLLECTION_MEDIUM: case ID_COLLECTION_MEDIUM_UNSHARED: { int b = readUnsignedShort(); len = b == 0 ? 0x10000 : b; break; } case ID_COLLECTION_LARGE: case ID_COLLECTION_LARGE_UNSHARED: { len = readInt(); break; } default: { throw new IllegalStateException(); } } final int id = readUnsignedByte(); final int idx; final ArrayList<Object> instanceCache = this.instanceCache; switch (id) { case ID_CC_ARRAY_LIST: { final Collection target = new ArrayList(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_HASH_SET: { final Collection target = new HashSet(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_LINKED_HASH_SET: { final Collection target = new LinkedHashSet(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_LINKED_LIST: { final Collection target = new LinkedList(); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_TREE_SET: { final Collection target = new TreeSet((Comparator)doReadObject(false)); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_HASH_MAP: { final Map target = new HashMap(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_HASHTABLE: { final Map target = new Hashtable(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_IDENTITY_HASH_MAP: { final Map target = new IdentityHashMap(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_LINKED_HASH_MAP: { final Map target = new LinkedHashMap(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_TREE_MAP: { final Map target = new TreeMap((Comparator)doReadObject(false)); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } default: { throw new StreamCorruptedException("Unexpected byte foudn when reading a collection type: " + leadByte); } } } case ID_CLEAR_CLASS_CACHE: { if (depth > 1) { throw new StreamCorruptedException("ID_CLEAR_CLASS_CACHE token in the middle of stream processing"); } classCache.clear(); instanceCache.clear(); leadByte = readUnsignedByte(); continue; } case ID_CLEAR_INSTANCE_CACHE: { if (depth > 1) { throw new StreamCorruptedException("ID_CLEAR_INSTANCE_CACHE token in the middle of stream processing"); } instanceCache.clear(); continue; } default: { throw new StreamCorruptedException("Unexpected byte found when reading an object: " + leadByte); } } } finally { depth --; } }
Object doReadObject(int leadByte, final boolean unshared) throws IOException, ClassNotFoundException { depth ++; try { for (;;) switch (leadByte) { case ID_NULL: { return null; } case ID_REPEAT_OBJECT_FAR: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } final int index = readInt(); try { final Object obj = instanceCache.get(index); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID (absolute " + index + ")"); } case ID_REPEAT_OBJECT_NEAR: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } final int index = readByte() | 0xffffff00; try { final Object obj = instanceCache.get(index + instanceCache.size()); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID (relative near " + index + ")"); } case ID_REPEAT_OBJECT_NEARISH: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } final int index = readShort() | 0xffff0000; try { final Object obj = instanceCache.get(index + instanceCache.size()); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID (relative nearish " + index + ")"); } case ID_NEW_OBJECT: case ID_NEW_OBJECT_UNSHARED: { if (unshared != (leadByte == ID_NEW_OBJECT_UNSHARED)) { throw sharedMismatch(); } return doReadNewObject(readUnsignedByte(), unshared); } // v2 string types case ID_STRING_EMPTY: { return ""; } case ID_STRING_SMALL: { // ignore unshared setting int length = readUnsignedByte(); final String s = UTFUtils.readUTFBytes(this, length == 0 ? 0x100 : length); instanceCache.add(s); return s; } case ID_STRING_MEDIUM: { // ignore unshared setting int length = readUnsignedShort(); final String s = UTFUtils.readUTFBytes(this, length == 0 ? 0x10000 : length); instanceCache.add(s); return s; } case ID_STRING_LARGE: { // ignore unshared setting int length = readInt(); if (length <= 0) { throw new StreamCorruptedException("Invalid length value for string in stream (" + length + ")"); } final String s = UTFUtils.readUTFBytes(this, length); instanceCache.add(s); return s; } case ID_ARRAY_EMPTY: case ID_ARRAY_EMPTY_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_EMPTY_UNSHARED)) { throw sharedMismatch(); } final ArrayList<Object> instanceCache = this.instanceCache; final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Array.newInstance(doReadClassDescriptor(readUnsignedByte()).getType(), 0); instanceCache.set(idx, obj); final Object resolvedObject = objectResolver.readResolve(obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return obj; } case ID_ARRAY_SMALL: case ID_ARRAY_SMALL_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_SMALL_UNSHARED)) { throw sharedMismatch(); } final int len = readUnsignedByte(); return doReadArray(len == 0 ? 0x100 : len, unshared); } case ID_ARRAY_MEDIUM: case ID_ARRAY_MEDIUM_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_MEDIUM_UNSHARED)) { throw sharedMismatch(); } final int len = readUnsignedShort(); return doReadArray(len == 0 ? 0x10000 : len, unshared); } case ID_ARRAY_LARGE: case ID_ARRAY_LARGE_UNSHARED: { if (unshared != (leadByte == ID_ARRAY_LARGE_UNSHARED)) { throw sharedMismatch(); } final int len = readInt(); if (len <= 0) { throw new StreamCorruptedException("Invalid length value for array in stream (" + len + ")"); } return doReadArray(len, unshared); } case ID_PREDEFINED_OBJECT: { if (unshared) { throw new InvalidObjectException("Attempt to read a predefined object as unshared"); } if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); final Object obj = objectTable.readObject(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); return obj; } else { return objectTable.readObject(this); } } case ID_BOOLEAN_OBJECT_TRUE: { return objectResolver.readResolve(Boolean.TRUE); } case ID_BOOLEAN_OBJECT_FALSE: { return objectResolver.readResolve(Boolean.FALSE); } case ID_BYTE_OBJECT: { return objectResolver.readResolve(Byte.valueOf(readByte())); } case ID_SHORT_OBJECT: { return objectResolver.readResolve(Short.valueOf(readShort())); } case ID_INTEGER_OBJECT: { return objectResolver.readResolve(Integer.valueOf(readInt())); } case ID_LONG_OBJECT: { return objectResolver.readResolve(Long.valueOf(readLong())); } case ID_FLOAT_OBJECT: { return objectResolver.readResolve(Float.valueOf(readFloat())); } case ID_DOUBLE_OBJECT: { return objectResolver.readResolve(Double.valueOf(readDouble())); } case ID_CHARACTER_OBJECT: { return objectResolver.readResolve(Character.valueOf(readChar())); } case ID_PRIM_BYTE: { return byte.class; } case ID_PRIM_BOOLEAN: { return boolean.class; } case ID_PRIM_CHAR: { return char.class; } case ID_PRIM_DOUBLE: { return double.class; } case ID_PRIM_FLOAT: { return float.class; } case ID_PRIM_INT: { return int.class; } case ID_PRIM_LONG: { return long.class; } case ID_PRIM_SHORT: { return short.class; } case ID_VOID: { return void.class; } case ID_BYTE_CLASS: { return Byte.class; } case ID_BOOLEAN_CLASS: { return Boolean.class; } case ID_CHARACTER_CLASS: { return Character.class; } case ID_DOUBLE_CLASS: { return Double.class; } case ID_FLOAT_CLASS: { return Float.class; } case ID_INTEGER_CLASS: { return Integer.class; } case ID_LONG_CLASS: { return Long.class; } case ID_SHORT_CLASS: { return Short.class; } case ID_VOID_CLASS: { return Void.class; } case ID_OBJECT_CLASS: { return Object.class; } case ID_CLASS_CLASS: { return Class.class; } case ID_STRING_CLASS: { return String.class; } case ID_ENUM_CLASS: { return Enum.class; } case ID_BYTE_ARRAY_CLASS: { return byte[].class; } case ID_BOOLEAN_ARRAY_CLASS: { return boolean[].class; } case ID_CHAR_ARRAY_CLASS: { return char[].class; } case ID_DOUBLE_ARRAY_CLASS: { return double[].class; } case ID_FLOAT_ARRAY_CLASS: { return float[].class; } case ID_INT_ARRAY_CLASS: { return int[].class; } case ID_LONG_ARRAY_CLASS: { return long[].class; } case ID_SHORT_ARRAY_CLASS: { return short[].class; } case ID_CC_ARRAY_LIST: { return ArrayList.class; } case ID_CC_HASH_MAP: { return HashMap.class; } case ID_CC_HASH_SET: { return HashSet.class; } case ID_CC_HASHTABLE: { return Hashtable.class; } case ID_CC_IDENTITY_HASH_MAP: { return HashMap.class; } case ID_CC_LINKED_HASH_MAP: { return LinkedHashMap.class; } case ID_CC_LINKED_HASH_SET: { return LinkedHashSet.class; } case ID_CC_LINKED_LIST: { return LinkedList.class; } case ID_CC_TREE_MAP: { return TreeMap.class; } case ID_CC_TREE_SET: { return TreeSet.class; } case ID_SINGLETON_LIST_OBJECT: { final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Collections.singletonList(doReadObject(false)); final Object resolvedObject = objectResolver.readResolve(obj); if (! unshared) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_SINGLETON_SET_OBJECT: { final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Collections.singleton(doReadObject(false)); final Object resolvedObject = objectResolver.readResolve(obj); if (! unshared) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_SINGLETON_MAP_OBJECT: { final int idx = instanceCache.size(); instanceCache.add(null); final Object obj = Collections.singletonMap(doReadObject(false), doReadObject(false)); final Object resolvedObject = objectResolver.readResolve(obj); if (! unshared) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_EMPTY_LIST_OBJECT: { return Collections.emptyList(); } case ID_EMPTY_SET_OBJECT: { return Collections.emptySet(); } case ID_EMPTY_MAP_OBJECT: { return Collections.emptyMap(); } case ID_COLLECTION_EMPTY: case ID_COLLECTION_EMPTY_UNSHARED: case ID_COLLECTION_SMALL: case ID_COLLECTION_SMALL_UNSHARED: case ID_COLLECTION_MEDIUM: case ID_COLLECTION_MEDIUM_UNSHARED: case ID_COLLECTION_LARGE: case ID_COLLECTION_LARGE_UNSHARED: { final int len; switch (leadByte) { case ID_COLLECTION_EMPTY: case ID_COLLECTION_EMPTY_UNSHARED: { len = 0; break; } case ID_COLLECTION_SMALL: case ID_COLLECTION_SMALL_UNSHARED: { int b = readUnsignedByte(); len = b == 0 ? 0x100 : b; break; } case ID_COLLECTION_MEDIUM: case ID_COLLECTION_MEDIUM_UNSHARED: { int b = readUnsignedShort(); len = b == 0 ? 0x10000 : b; break; } case ID_COLLECTION_LARGE: case ID_COLLECTION_LARGE_UNSHARED: { len = readInt(); break; } default: { throw new IllegalStateException(); } } final int id = readUnsignedByte(); final int idx; final ArrayList<Object> instanceCache = this.instanceCache; switch (id) { case ID_CC_ARRAY_LIST: { final Collection target = new ArrayList(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_HASH_SET: { final Collection target = new HashSet(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_LINKED_HASH_SET: { final Collection target = new LinkedHashSet(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_LINKED_LIST: { final Collection target = new LinkedList(); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_TREE_SET: { final Collection target = new TreeSet((Comparator)doReadObject(false)); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.add(doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_HASH_MAP: { final Map target = new HashMap(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_HASHTABLE: { final Map target = new Hashtable(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_IDENTITY_HASH_MAP: { final Map target = new IdentityHashMap(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_LINKED_HASH_MAP: { final Map target = new LinkedHashMap(len); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case ID_CC_TREE_MAP: { final Map target = new TreeMap((Comparator)doReadObject(false)); idx = instanceCache.size(); instanceCache.add(target); for (int i = 0; i < len; i ++) { target.put(doReadObject(false), doReadObject(false)); } final Object resolvedObject = objectResolver.readResolve(target); if (unshared) { instanceCache.set(idx, null); } else if (target != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } default: { throw new StreamCorruptedException("Unexpected byte foudn when reading a collection type: " + leadByte); } } } case ID_CLEAR_CLASS_CACHE: { if (depth > 1) { throw new StreamCorruptedException("ID_CLEAR_CLASS_CACHE token in the middle of stream processing"); } classCache.clear(); instanceCache.clear(); leadByte = readUnsignedByte(); continue; } case ID_CLEAR_INSTANCE_CACHE: { if (depth > 1) { throw new StreamCorruptedException("ID_CLEAR_INSTANCE_CACHE token in the middle of stream processing"); } instanceCache.clear(); continue; } default: { throw new StreamCorruptedException("Unexpected byte found when reading an object: " + leadByte); } } } finally { depth --; } }
diff --git a/weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.java b/weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.java index cb0295c06..7d6ab0ebb 100644 --- a/weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.java +++ b/weaver/src/org/aspectj/weaver/patterns/WithinCodeAnnotationPointcut.java @@ -1,221 +1,224 @@ /* ******************************************************************* * Copyright (c) 2004 IBM Corporation. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.AnnotatedElement; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.Member; import org.aspectj.weaver.NameMangler; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.Shadow; import org.aspectj.weaver.ShadowMunger; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.ast.Literal; import org.aspectj.weaver.ast.Test; import org.aspectj.weaver.ast.Var; /** * @author colyer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class WithinCodeAnnotationPointcut extends NameBindingPointcut { private ExactAnnotationTypePattern annotationTypePattern; private ShadowMunger munger = null; // only set after concretization private String declarationText; private static final int matchedShadowKinds; static { int flags = Shadow.ALL_SHADOW_KINDS_BITS; for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { if (Shadow.SHADOW_KINDS[i].isEnclosingKind()) flags -= Shadow.SHADOW_KINDS[i].bit; } matchedShadowKinds=flags; } public WithinCodeAnnotationPointcut(ExactAnnotationTypePattern type) { super(); this.annotationTypePattern = type; this.pointcutKind = Pointcut.ATWITHINCODE; buildDeclarationText(); } public WithinCodeAnnotationPointcut(ExactAnnotationTypePattern type, ShadowMunger munger) { this(type); this.munger = munger; this.pointcutKind = Pointcut.ATWITHINCODE; } public ExactAnnotationTypePattern getAnnotationTypePattern() { return annotationTypePattern; } public int couldMatchKinds() { return matchedShadowKinds; } public Pointcut parameterizeWith(Map typeVariableMap) { WithinCodeAnnotationPointcut ret = new WithinCodeAnnotationPointcut((ExactAnnotationTypePattern)this.annotationTypePattern.parameterizeWith(typeVariableMap)); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#fastMatch(org.aspectj.weaver.patterns.FastMatchInfo) */ public FuzzyBoolean fastMatch(FastMatchInfo info) { return FuzzyBoolean.MAYBE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#match(org.aspectj.weaver.Shadow) */ protected FuzzyBoolean matchInternal(Shadow shadow) { AnnotatedElement toMatchAgainst = null; Member member = shadow.getEnclosingCodeSignature(); ResolvedMember rMember = member.resolve(shadow.getIWorld()); if (rMember == null) { if (member.getName().startsWith(NameMangler.PREFIX)) { return FuzzyBoolean.NO; } shadow.getIWorld().getLint().unresolvableMember.signal(member.toString(), getSourceLocation()); return FuzzyBoolean.NO; } annotationTypePattern.resolve(shadow.getIWorld()); return annotationTypePattern.matches(rMember); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#resolveBindings(org.aspectj.weaver.patterns.IScope, org.aspectj.weaver.patterns.Bindings) */ protected void resolveBindings(IScope scope, Bindings bindings) { if (!scope.getWorld().isInJava5Mode()) { scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.ATWITHINCODE_ONLY_SUPPORTED_AT_JAVA5_LEVEL), getSourceLocation())); return; } annotationTypePattern = (ExactAnnotationTypePattern) annotationTypePattern.resolveBindings(scope,bindings,true); // must be either a Var, or an annotation type pattern } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#concretize1(org.aspectj.weaver.ResolvedType, org.aspectj.weaver.IntMap) */ protected Pointcut concretize1(ResolvedType inAspect, ResolvedType declaringType, IntMap bindings) { ExactAnnotationTypePattern newType = (ExactAnnotationTypePattern) annotationTypePattern.remapAdviceFormals(bindings); Pointcut ret = new WithinCodeAnnotationPointcut(newType, bindings.getEnclosingAdvice()); ret.copyLocationFrom(this); return ret; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.Pointcut#findResidue(org.aspectj.weaver.Shadow, org.aspectj.weaver.patterns.ExposedState) */ protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.annotationType; Var var = shadow.getWithinCodeAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]"); state.set(btp.getFormalIndex(),var); } - return Literal.TRUE; + if (matchInternal(shadow).alwaysTrue()) + return Literal.TRUE; + else + return Literal.FALSE; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingAnnotationTypePatterns() */ public List getBindingAnnotationTypePatterns() { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { List l = new ArrayList(); l.add(annotationTypePattern); return l; } else return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.NameBindingPointcut#getBindingTypePatterns() */ public List getBindingTypePatterns() { return Collections.EMPTY_LIST; } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.PatternNode#write(java.io.DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(Pointcut.ATWITHINCODE); annotationTypePattern.write(s); writeLocation(s); } public static Pointcut read(VersionedDataInputStream s, ISourceContext context) throws IOException { AnnotationTypePattern type = AnnotationTypePattern.read(s, context); WithinCodeAnnotationPointcut ret = new WithinCodeAnnotationPointcut((ExactAnnotationTypePattern)type); ret.readLocation(context, s); return ret; } public boolean equals(Object other) { if (!(other instanceof WithinCodeAnnotationPointcut)) return false; WithinCodeAnnotationPointcut o = (WithinCodeAnnotationPointcut)other; return o.annotationTypePattern.equals(this.annotationTypePattern); } public int hashCode() { int result = 17; result = 23*result + annotationTypePattern.hashCode(); return result; } private void buildDeclarationText() { StringBuffer buf = new StringBuffer(); buf.append("@withincode("); String annPatt = annotationTypePattern.toString(); buf.append(annPatt.startsWith("@") ? annPatt.substring(1) : annPatt); buf.append(")"); this.declarationText = buf.toString(); } public String toString() { return this.declarationText; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } }
true
true
protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.annotationType; Var var = shadow.getWithinCodeAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]"); state.set(btp.getFormalIndex(),var); } return Literal.TRUE; }
protected Test findResidueInternal(Shadow shadow, ExposedState state) { if (annotationTypePattern instanceof BindingAnnotationTypePattern) { BindingAnnotationTypePattern btp = (BindingAnnotationTypePattern)annotationTypePattern; UnresolvedType annotationType = btp.annotationType; Var var = shadow.getWithinCodeAnnotationVar(annotationType); // This should not happen, we shouldn't have gotten this far // if we weren't going to find the annotation if (var == null) throw new BCException("Impossible! annotation=["+annotationType+ "] shadow=["+shadow+" at "+shadow.getSourceLocation()+ "] pointcut is at ["+getSourceLocation()+"]"); state.set(btp.getFormalIndex(),var); } if (matchInternal(shadow).alwaysTrue()) return Literal.TRUE; else return Literal.FALSE; }
diff --git a/src/org/apache/xerces/impl/XMLNamespaceBinder.java b/src/org/apache/xerces/impl/XMLNamespaceBinder.java index 727b6421..31487b6e 100644 --- a/src/org/apache/xerces/impl/XMLNamespaceBinder.java +++ b/src/org/apache/xerces/impl/XMLNamespaceBinder.java @@ -1,847 +1,847 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000,2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.impl; import java.util.Enumeration; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.msg.XMLMessageFormatter; import org.apache.xerces.util.NamespaceSupport; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDocumentFilter; /** * This class performs namespace binding on the startElement and endElement * method calls and passes all other methods through to the registered * document handler. This class can be configured to only pass the * start and end prefix mappings (start/endPrefixMapping). * <p> * This component requires the following features and properties from the * component manager that uses it: * <ul> * <li>http://xml.org/sax/features/namespaces</li> * <li>http://apache.org/xml/properties/internal/symbol-table</li> * <li>http://apache.org/xml/properties/internal/error-reporter</li> * </ul> * * @author Andy Clark, IBM * * @version $Id$ */ public class XMLNamespaceBinder implements XMLComponent, XMLDocumentFilter { // // Constants // // feature identifiers /** Feature identifier: namespaces. */ protected static final String NAMESPACES = Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE; // property identifiers /** Property identifier: symbol table. */ protected static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error reporter. */ protected static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; // recognized features and properties /** Recognized features. */ protected static final String[] RECOGNIZED_FEATURES = { NAMESPACES, }; /** Recognized properties. */ protected static final String[] RECOGNIZED_PROPERTIES = { SYMBOL_TABLE, ERROR_REPORTER, }; // // Data // // features /** Namespaces. */ protected boolean fNamespaces; // properties /** Symbol table. */ protected SymbolTable fSymbolTable; /** Error reporter. */ protected XMLErrorReporter fErrorReporter; // handlers /** Document handler. */ protected XMLDocumentHandler fDocumentHandler; // namespaces /** Namespace support. */ protected NamespaceSupport fNamespaceSupport = new NamespaceSupport(); // settings /** Only pass start and end prefix mapping events. */ protected boolean fOnlyPassPrefixMappingEvents; // shared context /** Namespace context. */ private NamespaceContext fNamespaceContext; // temp vars /** Attribute QName. */ private QName fAttributeQName = new QName(); // symbols /** Symbol: "". */ private String fEmptySymbol; /** Symbol: "xml". */ private String fXmlSymbol; /** Symbol: "xmlns". */ private String fXmlnsSymbol; // // Constructors // /** Default constructor. */ public XMLNamespaceBinder() { this(null); } // <init>() /** * Constructs a namespace binder that shares the specified namespace * context during each parse. * * @param namespaceContext The shared context. */ public XMLNamespaceBinder(NamespaceContext namespaceContext) { fNamespaceContext = namespaceContext; } // <init>(NamespaceContext) // // Public methods // /** Returns the current namespace context. */ public NamespaceContext getNamespaceContext() { return fNamespaceSupport; } // getNamespaceContext():NamespaceContext // settings /** * Sets whether the namespace binder only passes the prefix mapping * events to the registered document handler or passes all document * events. * * @param onlyPassPrefixMappingEvents True to pass only the prefix * mapping events; false to pass * all events. */ public void setOnlyPassPrefixMappingEvents(boolean onlyPassPrefixMappingEvents) { fOnlyPassPrefixMappingEvents = onlyPassPrefixMappingEvents; } // setOnlyPassPrefixMappingEvents(boolean) /** * Returns true if the namespace binder only passes the prefix mapping * events to the registered document handler; false if the namespace * binder passes all document events. */ public boolean getOnlyPassPrefixMappingEvents() { return fOnlyPassPrefixMappingEvents; } // getOnlyPassPrefixMappingEvents():boolean // // XMLComponent methods // /** * Resets the component. The component can query the component manager * about any features and properties that affect the operation of the * component. * * @param componentManager The component manager. * * @throws SAXException Thrown by component on initialization error. * For example, if a feature or property is * required for the operation of the component, the * component manager may throw a * SAXNotRecognizedException or a * SAXNotSupportedException. */ public void reset(XMLComponentManager componentManager) throws XNIException { // features try { fNamespaces = componentManager.getFeature(NAMESPACES); } catch (XMLConfigurationException e) { fNamespaces = true; } // Xerces properties fSymbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE); fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); // initialize vars fNamespaceSupport.reset(fSymbolTable); // save built-in entity names fEmptySymbol = fSymbolTable.addSymbol(""); fXmlSymbol = fSymbolTable.addSymbol("xml"); fXmlnsSymbol = fSymbolTable.addSymbol("xmlns"); // use shared context NamespaceContext context = fNamespaceContext; while (context != null) { int count = context.getDeclaredPrefixCount(); for (int i = 0; i < count; i++) { String prefix = context.getDeclaredPrefixAt(i); if (fNamespaceSupport.getURI(prefix) == null) { String uri = context.getURI(prefix); fNamespaceSupport.declarePrefix(prefix, uri); } } context = context.getParentContext(); } } // reset(XMLComponentManager) /** * Returns a list of feature identifiers that are recognized by * this component. This method may return null if no features * are recognized by this component. */ public String[] getRecognizedFeatures() { return RECOGNIZED_FEATURES; } // getRecognizedFeatures():String[] /** * Sets the state of a feature. This method is called by the component * manager any time after reset when a feature changes state. * <p> * <strong>Note:</strong> Components should silently ignore features * that do not affect the operation of the component. * * @param featureId The feature identifier. * @param state The state of the feature. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { } // setFeature(String,boolean) /** * Returns a list of property identifiers that are recognized by * this component. This method may return null if no properties * are recognized by this component. */ public String[] getRecognizedProperties() { return RECOGNIZED_PROPERTIES; } // getRecognizedProperties():String[] /** * Sets the value of a property during parsing. * * @param propertyId * @param value */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { // Xerces properties if (propertyId.startsWith(Constants.XERCES_PROPERTY_PREFIX)) { String property = propertyId.substring(Constants.XERCES_PROPERTY_PREFIX.length()); if (property.equals(Constants.SYMBOL_TABLE_PROPERTY)) { fSymbolTable = (SymbolTable)value; } else if (property.equals(Constants.ERROR_REPORTER_PROPERTY)) { fErrorReporter = (XMLErrorReporter)value; } return; } } // setProperty(String,Object) // // XMLDocumentSource methods // /** * Sets the document handler to receive information about the document. * * @param documentHandler The document handler. */ public void setDocumentHandler(XMLDocumentHandler documentHandler) { fDocumentHandler = documentHandler; } // setDocumentHandler(XMLDocumentHandler) // // XMLDocumentHandler methods // /** * This method notifies the start of an entity. General entities are just * specified by their name. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * @param publicId The public identifier of the entity if the entity * is external, null otherwise. * @param systemId The system identifier of the entity if the entity * is external, null otherwise. * @param baseSystemId The base system identifier of the entity if * the entity is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * * @throws XNIException Thrown by handler to signal an error. */ public void startEntity(String name, String publicId, String systemId, String baseSystemId, String encoding) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.startEntity(name, publicId, systemId, baseSystemId, encoding); } } // startEntity(String,String,String,String,String) /** * Notifies of the presence of a TextDecl line in an entity. If present, * this method will be called immediately following the startEntity call. * <p> * <strong>Note:</strong> This method will never be called for the * document entity; it is only called for external general entities * referenced in document content. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param version The XML version, or null if not specified. * @param encoding The IANA encoding name of the entity. * * @throws XNIException Thrown by handler to signal an error. */ public void textDecl(String version, String encoding) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.textDecl(version, encoding); } } // textDecl(String,String) /** * The start of the document. * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument(XMLLocator locator, String encoding) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.startDocument(locator, encoding); } } // startDocument(XMLLocator,String) /** * Notifies of the presence of an XMLDecl line in the document. If * present, this method will be called immediately following the * startDocument call. * * @param version The XML version. * @param encoding The IANA encoding name of the document, or null if * not specified. * @param standalone The standalone value, or null if not specified. * * @throws XNIException Thrown by handler to signal an error. */ public void xmlDecl(String version, String encoding, String standalone) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.xmlDecl(version, encoding, standalone); } } // xmlDecl(String,String,String) /** * Notifies of the presence of the DOCTYPE line in the document. * * @param rootElement The name of the root element. * @param publicId The public identifier if an external DTD or null * if the external DTD is specified using SYSTEM. * @param systemId The system identifier if an external DTD, null * otherwise. * * @throws XNIException Thrown by handler to signal an error. */ public void doctypeDecl(String rootElement, String publicId, String systemId) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.doctypeDecl(rootElement, publicId, systemId); } } // doctypeDecl(String,String,String) /** * A comment. * * @param text The text in the comment. * * @throws XNIException Thrown by application to signal an error. */ public void comment(XMLString text) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.comment(text); } } // comment(XMLString) /** * A processing instruction. Processing instructions consist of a * target name and, optionally, text data. The data is only meaningful * to the application. * <p> * Typically, a processing instruction's data will contain a series * of pseudo-attributes. These pseudo-attributes follow the form of * element attributes but are <strong>not</strong> parsed or presented * to the application as anything other than text. The application is * responsible for parsing the data. * * @param target The target. * @param data The data or null if none specified. * * @throws XNIException Thrown by handler to signal an error. */ public void processingInstruction(String target, XMLString data) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.processingInstruction(target, data); } } // processingInstruction(String,XMLString) /** * The start of a namespace prefix mapping. This method will only be * called when namespace processing is enabled. * * @param prefix The namespace prefix. * @param uri The URI bound to the prefix. * * @throws XNIException Thrown by handler to signal an error. */ public void startPrefixMapping(String prefix, String uri) throws XNIException { // REVISIT: Should prefix mapping from previous stage in // the pipeline affect the namespaces? // call handlers if (fDocumentHandler != null) { fDocumentHandler.startPrefixMapping(prefix, uri); } } // startPrefixMapping(String,String) /** * Binds the namespaces. This method will handle calling the * document handler to start the prefix mappings. * <p> * <strong>Note:</strong> This method makes use of the * fAttributeQName variable. Any contents of the variable will * be destroyed. Caller should copy the values out of this * temporary variable before calling this method. * * @param element The name of the element. * @param attributes The element attributes. * * @throws XNIException Thrown by handler to signal an error. */ public void startElement(QName element, XMLAttributes attributes) throws XNIException { if (fNamespaces) { handleStartElement(element, attributes, false); } else if (fDocumentHandler != null) { fDocumentHandler.startElement(element, attributes); } } // startElement(QName,XMLAttributes) /** * An empty element. * * @param element The name of the element. * @param attributes The element attributes. * * @throws XNIException Thrown by handler to signal an error. */ public void emptyElement(QName element, XMLAttributes attributes) throws XNIException { if (fNamespaces) { handleStartElement(element, attributes, true); handleEndElement(element, true); } else if (fDocumentHandler != null) { fDocumentHandler.emptyElement(element, attributes); } } // emptyElement(QName,XMLAttributes) /** * Character content. * * @param text The content. * * @throws XNIException Thrown by handler to signal an error. */ public void characters(XMLString text) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.characters(text); } } // characters(XMLString) /** * Ignorable whitespace. For this method to be called, the document * source must have some way of determining that the text containing * only whitespace characters should be considered ignorable. For * example, the validator can determine if a length of whitespace * characters in the document are ignorable based on the element * content model. * * @param text The ignorable whitespace. * * @throws XNIException Thrown by handler to signal an error. */ public void ignorableWhitespace(XMLString text) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.ignorableWhitespace(text); } } // ignorableWhitespace(XMLString) /** * The end of an element. * * @param element The name of the element. * * @throws XNIException Thrown by handler to signal an error. */ public void endElement(QName element) throws XNIException { if (fNamespaces) { handleEndElement(element, false); } else if (fDocumentHandler != null) { fDocumentHandler.endElement(element); } } // endElement(QName) /** * The end of a namespace prefix mapping. This method will only be * called when namespace processing is enabled. * * @param prefix The namespace prefix. * * @throws XNIException Thrown by handler to signal an error. */ public void endPrefixMapping(String prefix) throws XNIException { // REVISIT: Should prefix mapping from previous stage in // the pipeline affect the namespaces? // call handlers if (fDocumentHandler != null) { fDocumentHandler.endPrefixMapping(prefix); } } // endPrefixMapping(String) /** * The start of a CDATA section. * * @throws XNIException Thrown by handler to signal an error. */ public void startCDATA() throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.startCDATA(); } } // startCDATA() /** * The end of a CDATA section. * * @throws XNIException Thrown by handler to signal an error. */ public void endCDATA() throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.endCDATA(); } } // endCDATA() /** * The end of the document. * * @throws XNIException Thrown by handler to signal an error. */ public void endDocument() throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.endDocument(); } } // endDocument() /** * This method notifies the end of an entity. General entities are just * specified by their name. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * * @throws XNIException Thrown by handler to signal an error. */ public void endEntity(String name) throws XNIException { if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { fDocumentHandler.endEntity(name); } } // endEntity(String) // // Protected methods // /** Handles start element. */ protected void handleStartElement(QName element, XMLAttributes attributes, boolean isEmpty) throws XNIException { // add new namespace context fNamespaceSupport.pushContext(); // search for new namespace bindings int length = attributes.getLength(); for (int i = 0; i < length; i++) { String localpart = attributes.getLocalName(i); String prefix = attributes.getPrefix(i); if (prefix == fXmlnsSymbol || localpart == fXmlnsSymbol) { // check for duplicates prefix = localpart != fXmlnsSymbol ? localpart : fEmptySymbol; String uri = attributes.getValue(i); uri = fSymbolTable.addSymbol(uri); // http://www.w3.org/TR/1999/REC-xml-names-19990114/#dt-prefix // We should only report an error if there is a prefix, // that is, the local part is not "xmlns". -SG if (uri == fEmptySymbol && localpart != fXmlnsSymbol) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "EmptyPrefixedAttName", - new Object[]{element.rawname}, + new Object[]{attributes.getQName(i)}, XMLErrorReporter.SEVERITY_FATAL_ERROR); continue; } // declare prefix in context fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null); // call handler if (fDocumentHandler != null) { fDocumentHandler.startPrefixMapping(prefix, uri); } } } // bind the element String prefix = element.prefix != null ? element.prefix : fEmptySymbol; element.uri = fNamespaceSupport.getURI(prefix); if (element.prefix == null && element.uri != null) { element.prefix = fEmptySymbol; } if (element.prefix != null && element.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "ElementPrefixUnbound", new Object[]{element.prefix, element.rawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } // bind the attributes for (int i = 0; i < length; i++) { attributes.getName(i, fAttributeQName); String aprefix = fAttributeQName.prefix != null ? fAttributeQName.prefix : fEmptySymbol; String arawname = fAttributeQName.rawname; if (aprefix == fXmlSymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(fXmlSymbol); attributes.setName(i, fAttributeQName); } else if (arawname != fXmlnsSymbol && !arawname.startsWith("xmlns:")) { if (aprefix != fEmptySymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(aprefix); if (fAttributeQName.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributePrefixUnbound", new Object[]{aprefix, arawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } attributes.setName(i, fAttributeQName); } } } // verify that duplicate attributes don't exist // Example: <foo xmlns:a='NS' xmlns:b='NS' a:attr='v1' b:attr='v2'/> int attrCount = attributes.getLength(); for (int i = 0; i < attrCount - 1; i++) { String alocalpart = attributes.getLocalName(i); String auri = attributes.getURI(i); for (int j = i + 1; j < attrCount; j++) { String blocalpart = attributes.getLocalName(j); String buri = attributes.getURI(j); if (alocalpart == blocalpart && auri == buri) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributeNSNotUnique", new Object[]{element.rawname,alocalpart, auri}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } } } // call handler if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { if (isEmpty) { fDocumentHandler.emptyElement(element, attributes); } else { fDocumentHandler.startElement(element, attributes); } } } // handleStartElement(QName,XMLAttributes,boolean) /** Handles end element. */ protected void handleEndElement(QName element, boolean isEmpty) throws XNIException { // bind element String eprefix = element.prefix != null ? element.prefix : fEmptySymbol; element.uri = fNamespaceSupport.getURI(eprefix); if (element.uri != null) { element.prefix = eprefix; } // call handlers if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { if (!isEmpty) { fDocumentHandler.endElement(element); } } // end prefix mappings if (fDocumentHandler != null) { int count = fNamespaceSupport.getDeclaredPrefixCount(); for (int i = count - 1; i >= 0; i--) { String prefix = fNamespaceSupport.getDeclaredPrefixAt(i); fDocumentHandler.endPrefixMapping(prefix); } } // pop context fNamespaceSupport.popContext(); } // handleEndElement(QName,boolean) } // class XMLNamespaceBinder
true
true
protected void handleStartElement(QName element, XMLAttributes attributes, boolean isEmpty) throws XNIException { // add new namespace context fNamespaceSupport.pushContext(); // search for new namespace bindings int length = attributes.getLength(); for (int i = 0; i < length; i++) { String localpart = attributes.getLocalName(i); String prefix = attributes.getPrefix(i); if (prefix == fXmlnsSymbol || localpart == fXmlnsSymbol) { // check for duplicates prefix = localpart != fXmlnsSymbol ? localpart : fEmptySymbol; String uri = attributes.getValue(i); uri = fSymbolTable.addSymbol(uri); // http://www.w3.org/TR/1999/REC-xml-names-19990114/#dt-prefix // We should only report an error if there is a prefix, // that is, the local part is not "xmlns". -SG if (uri == fEmptySymbol && localpart != fXmlnsSymbol) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "EmptyPrefixedAttName", new Object[]{element.rawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); continue; } // declare prefix in context fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null); // call handler if (fDocumentHandler != null) { fDocumentHandler.startPrefixMapping(prefix, uri); } } } // bind the element String prefix = element.prefix != null ? element.prefix : fEmptySymbol; element.uri = fNamespaceSupport.getURI(prefix); if (element.prefix == null && element.uri != null) { element.prefix = fEmptySymbol; } if (element.prefix != null && element.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "ElementPrefixUnbound", new Object[]{element.prefix, element.rawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } // bind the attributes for (int i = 0; i < length; i++) { attributes.getName(i, fAttributeQName); String aprefix = fAttributeQName.prefix != null ? fAttributeQName.prefix : fEmptySymbol; String arawname = fAttributeQName.rawname; if (aprefix == fXmlSymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(fXmlSymbol); attributes.setName(i, fAttributeQName); } else if (arawname != fXmlnsSymbol && !arawname.startsWith("xmlns:")) { if (aprefix != fEmptySymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(aprefix); if (fAttributeQName.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributePrefixUnbound", new Object[]{aprefix, arawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } attributes.setName(i, fAttributeQName); } } } // verify that duplicate attributes don't exist // Example: <foo xmlns:a='NS' xmlns:b='NS' a:attr='v1' b:attr='v2'/> int attrCount = attributes.getLength(); for (int i = 0; i < attrCount - 1; i++) { String alocalpart = attributes.getLocalName(i); String auri = attributes.getURI(i); for (int j = i + 1; j < attrCount; j++) { String blocalpart = attributes.getLocalName(j); String buri = attributes.getURI(j); if (alocalpart == blocalpart && auri == buri) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributeNSNotUnique", new Object[]{element.rawname,alocalpart, auri}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } } } // call handler if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { if (isEmpty) { fDocumentHandler.emptyElement(element, attributes); } else { fDocumentHandler.startElement(element, attributes); } } } // handleStartElement(QName,XMLAttributes,boolean)
protected void handleStartElement(QName element, XMLAttributes attributes, boolean isEmpty) throws XNIException { // add new namespace context fNamespaceSupport.pushContext(); // search for new namespace bindings int length = attributes.getLength(); for (int i = 0; i < length; i++) { String localpart = attributes.getLocalName(i); String prefix = attributes.getPrefix(i); if (prefix == fXmlnsSymbol || localpart == fXmlnsSymbol) { // check for duplicates prefix = localpart != fXmlnsSymbol ? localpart : fEmptySymbol; String uri = attributes.getValue(i); uri = fSymbolTable.addSymbol(uri); // http://www.w3.org/TR/1999/REC-xml-names-19990114/#dt-prefix // We should only report an error if there is a prefix, // that is, the local part is not "xmlns". -SG if (uri == fEmptySymbol && localpart != fXmlnsSymbol) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "EmptyPrefixedAttName", new Object[]{attributes.getQName(i)}, XMLErrorReporter.SEVERITY_FATAL_ERROR); continue; } // declare prefix in context fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null); // call handler if (fDocumentHandler != null) { fDocumentHandler.startPrefixMapping(prefix, uri); } } } // bind the element String prefix = element.prefix != null ? element.prefix : fEmptySymbol; element.uri = fNamespaceSupport.getURI(prefix); if (element.prefix == null && element.uri != null) { element.prefix = fEmptySymbol; } if (element.prefix != null && element.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "ElementPrefixUnbound", new Object[]{element.prefix, element.rawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } // bind the attributes for (int i = 0; i < length; i++) { attributes.getName(i, fAttributeQName); String aprefix = fAttributeQName.prefix != null ? fAttributeQName.prefix : fEmptySymbol; String arawname = fAttributeQName.rawname; if (aprefix == fXmlSymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(fXmlSymbol); attributes.setName(i, fAttributeQName); } else if (arawname != fXmlnsSymbol && !arawname.startsWith("xmlns:")) { if (aprefix != fEmptySymbol) { fAttributeQName.uri = fNamespaceSupport.getURI(aprefix); if (fAttributeQName.uri == null) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributePrefixUnbound", new Object[]{aprefix, arawname}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } attributes.setName(i, fAttributeQName); } } } // verify that duplicate attributes don't exist // Example: <foo xmlns:a='NS' xmlns:b='NS' a:attr='v1' b:attr='v2'/> int attrCount = attributes.getLength(); for (int i = 0; i < attrCount - 1; i++) { String alocalpart = attributes.getLocalName(i); String auri = attributes.getURI(i); for (int j = i + 1; j < attrCount; j++) { String blocalpart = attributes.getLocalName(j); String buri = attributes.getURI(j); if (alocalpart == blocalpart && auri == buri) { fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN, "AttributeNSNotUnique", new Object[]{element.rawname,alocalpart, auri}, XMLErrorReporter.SEVERITY_FATAL_ERROR); } } } // call handler if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) { if (isEmpty) { fDocumentHandler.emptyElement(element, attributes); } else { fDocumentHandler.startElement(element, attributes); } } } // handleStartElement(QName,XMLAttributes,boolean)
diff --git a/src/poppio/cg/Furniture.java b/src/poppio/cg/Furniture.java index a4bd1a4..f8e98db 100644 --- a/src/poppio/cg/Furniture.java +++ b/src/poppio/cg/Furniture.java @@ -1,88 +1,88 @@ package poppio.cg; // for store data of furnitures public class Furniture extends roomObject{ private String path; private WavefrontObjectLoader_VertexBufferObject obj; float colorR,colorG,colorB; public Furniture (int id, int furnitureCount, int objectID) { super(id); if(objectID == 1){ // bin this.name = "bin"+furnitureCount; this.path = "obj/bin.obj"; this.colorR = new Float(0.5); this.colorG = new Float(0.445); this.colorB = new Float(0.447); this.coorZ = -7f; }else if(objectID == 2){ // table this.name = "table"+furnitureCount; this.path = "obj/table.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -7f; }else if(objectID == 3){ // table this.name = "chair"+furnitureCount; this.path = "obj/chair.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); - this.coorZ = -7f; + this.coorZ = -10f; }else if(objectID == 4){ // cuble this.name = "cube"+furnitureCount; this.path = "obj/cube.obj"; this.colorR = new Float(1); this.colorG = new Float(0); this.colorB = new Float(0.750); this.coorZ = -8.5f; }else if(objectID == 5){ // table this.name = "sphere"+furnitureCount; this.path = "obj/sphere_tex.obj"; this.colorR = new Float(0); this.colorG = new Float(0.667); this.colorB = new Float(1); this.coorZ = -9.2f; }else if(objectID == 6){ // table this.name = "urn"+furnitureCount; this.path = "obj/urn.obj"; this.colorR = new Float(0.962); this.colorG = new Float(0.860); this.colorB = new Float(0.317); this.coorZ = -8.5f; }else if(objectID == 7){ // table this.name = "shelf"+furnitureCount; this.path = "obj/shelf.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -8.7f; }else if(objectID == 8){ // table this.name = "wardrobe"+furnitureCount; this.path = "obj/wardrobe.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -3.4f; }else{ // gonna add more // wtf } this.obj = new WavefrontObjectLoader_VertexBufferObject(path); } public WavefrontObjectLoader_VertexBufferObject getObjectLoader() { return this.obj; } }
true
true
public Furniture (int id, int furnitureCount, int objectID) { super(id); if(objectID == 1){ // bin this.name = "bin"+furnitureCount; this.path = "obj/bin.obj"; this.colorR = new Float(0.5); this.colorG = new Float(0.445); this.colorB = new Float(0.447); this.coorZ = -7f; }else if(objectID == 2){ // table this.name = "table"+furnitureCount; this.path = "obj/table.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -7f; }else if(objectID == 3){ // table this.name = "chair"+furnitureCount; this.path = "obj/chair.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -7f; }else if(objectID == 4){ // cuble this.name = "cube"+furnitureCount; this.path = "obj/cube.obj"; this.colorR = new Float(1); this.colorG = new Float(0); this.colorB = new Float(0.750); this.coorZ = -8.5f; }else if(objectID == 5){ // table this.name = "sphere"+furnitureCount; this.path = "obj/sphere_tex.obj"; this.colorR = new Float(0); this.colorG = new Float(0.667); this.colorB = new Float(1); this.coorZ = -9.2f; }else if(objectID == 6){ // table this.name = "urn"+furnitureCount; this.path = "obj/urn.obj"; this.colorR = new Float(0.962); this.colorG = new Float(0.860); this.colorB = new Float(0.317); this.coorZ = -8.5f; }else if(objectID == 7){ // table this.name = "shelf"+furnitureCount; this.path = "obj/shelf.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -8.7f; }else if(objectID == 8){ // table this.name = "wardrobe"+furnitureCount; this.path = "obj/wardrobe.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -3.4f; }else{ // gonna add more // wtf } this.obj = new WavefrontObjectLoader_VertexBufferObject(path); }
public Furniture (int id, int furnitureCount, int objectID) { super(id); if(objectID == 1){ // bin this.name = "bin"+furnitureCount; this.path = "obj/bin.obj"; this.colorR = new Float(0.5); this.colorG = new Float(0.445); this.colorB = new Float(0.447); this.coorZ = -7f; }else if(objectID == 2){ // table this.name = "table"+furnitureCount; this.path = "obj/table.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -7f; }else if(objectID == 3){ // table this.name = "chair"+furnitureCount; this.path = "obj/chair.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -10f; }else if(objectID == 4){ // cuble this.name = "cube"+furnitureCount; this.path = "obj/cube.obj"; this.colorR = new Float(1); this.colorG = new Float(0); this.colorB = new Float(0.750); this.coorZ = -8.5f; }else if(objectID == 5){ // table this.name = "sphere"+furnitureCount; this.path = "obj/sphere_tex.obj"; this.colorR = new Float(0); this.colorG = new Float(0.667); this.colorB = new Float(1); this.coorZ = -9.2f; }else if(objectID == 6){ // table this.name = "urn"+furnitureCount; this.path = "obj/urn.obj"; this.colorR = new Float(0.962); this.colorG = new Float(0.860); this.colorB = new Float(0.317); this.coorZ = -8.5f; }else if(objectID == 7){ // table this.name = "shelf"+furnitureCount; this.path = "obj/shelf.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -8.7f; }else if(objectID == 8){ // table this.name = "wardrobe"+furnitureCount; this.path = "obj/wardrobe.obj"; this.colorR = new Float(0.633); this.colorG = new Float(0.423); this.colorB = new Float(0.240); this.coorZ = -3.4f; }else{ // gonna add more // wtf } this.obj = new WavefrontObjectLoader_VertexBufferObject(path); }
diff --git a/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareProviderSelect.java b/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareProviderSelect.java index 4fb165bf..9cd0b639 100644 --- a/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareProviderSelect.java +++ b/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareProviderSelect.java @@ -1,48 +1,48 @@ /* * Created on 27.3.2003 */ package se.idega.idegaweb.commune.childcare.presentation; import java.util.Collection; import java.util.Iterator; import se.idega.idegaweb.commune.childcare.event.ChildCareEventListener; import com.idega.block.school.data.School; import com.idega.presentation.IWContext; import com.idega.presentation.text.Text; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.Form; /** * @author laddi */ public class ChildCareProviderSelect extends ChildCareBlock { /** * @see se.idega.idegaweb.commune.childcare.presentation.ChildCareBlock#init(com.idega.presentation.IWContext) */ public void init(IWContext iwc) throws Exception { Form form = new Form(); form.setEventListener(ChildCareEventListener.class); - DropdownMenu menu = new DropdownMenu(getSession().getParameterChildCareID()); + DropdownMenu menu = (DropdownMenu) getStyledInterface(new DropdownMenu(getSession().getParameterChildCareID())); menu.addMenuElementFirst("-1", localize("child_care.select_provider","Select provider")); menu.setSelectedElement(getSession().getChildCareID()); menu.setToSubmit(); Collection providers = getBusiness().getSchoolBusiness().findAllSchoolsByType(getBusiness().getSchoolBusiness().findAllSchoolTypesForChildCare()); if (providers != null) { Iterator iter = providers.iterator(); while (iter.hasNext()) { School element = (School) iter.next(); menu.addMenuElement(element.getPrimaryKey().toString(), element.getSchoolName()); } } form.add(getSmallHeader(localize("child_care.providers","Providers")+":"+Text.NON_BREAKING_SPACE)); form.add(menu); add(form); } }
true
true
public void init(IWContext iwc) throws Exception { Form form = new Form(); form.setEventListener(ChildCareEventListener.class); DropdownMenu menu = new DropdownMenu(getSession().getParameterChildCareID()); menu.addMenuElementFirst("-1", localize("child_care.select_provider","Select provider")); menu.setSelectedElement(getSession().getChildCareID()); menu.setToSubmit(); Collection providers = getBusiness().getSchoolBusiness().findAllSchoolsByType(getBusiness().getSchoolBusiness().findAllSchoolTypesForChildCare()); if (providers != null) { Iterator iter = providers.iterator(); while (iter.hasNext()) { School element = (School) iter.next(); menu.addMenuElement(element.getPrimaryKey().toString(), element.getSchoolName()); } } form.add(getSmallHeader(localize("child_care.providers","Providers")+":"+Text.NON_BREAKING_SPACE)); form.add(menu); add(form); }
public void init(IWContext iwc) throws Exception { Form form = new Form(); form.setEventListener(ChildCareEventListener.class); DropdownMenu menu = (DropdownMenu) getStyledInterface(new DropdownMenu(getSession().getParameterChildCareID())); menu.addMenuElementFirst("-1", localize("child_care.select_provider","Select provider")); menu.setSelectedElement(getSession().getChildCareID()); menu.setToSubmit(); Collection providers = getBusiness().getSchoolBusiness().findAllSchoolsByType(getBusiness().getSchoolBusiness().findAllSchoolTypesForChildCare()); if (providers != null) { Iterator iter = providers.iterator(); while (iter.hasNext()) { School element = (School) iter.next(); menu.addMenuElement(element.getPrimaryKey().toString(), element.getSchoolName()); } } form.add(getSmallHeader(localize("child_care.providers","Providers")+":"+Text.NON_BREAKING_SPACE)); form.add(menu); add(form); }
diff --git a/src/main/java/cz/startnet/utils/pgdiff/PgDiff.java b/src/main/java/cz/startnet/utils/pgdiff/PgDiff.java index 76007a8..747cf50 100644 --- a/src/main/java/cz/startnet/utils/pgdiff/PgDiff.java +++ b/src/main/java/cz/startnet/utils/pgdiff/PgDiff.java @@ -1,174 +1,174 @@ package cz.startnet.utils.pgdiff; import cz.startnet.utils.pgdiff.loader.PgDumpLoader; import cz.startnet.utils.pgdiff.schema.PgDatabase; import cz.startnet.utils.pgdiff.schema.PgSchema; import java.io.InputStream; import java.io.PrintWriter; /** * Creates diff of two database schemas. * * @author fordfrog */ public class PgDiff { /** * Creates a new instance of PgDiff. */ private PgDiff() { } /** * Creates diff on the two database schemas. * * @param writer writer the output should be written to * @param arguments object containing arguments settings */ public static void createDiff(final PrintWriter writer, final PgDiffArguments arguments) { diffDatabaseSchemas(writer, arguments, PgDumpLoader.loadDatabaseSchema(arguments.getOldDumpFile(), arguments.getInCharsetName()), PgDumpLoader.loadDatabaseSchema(arguments.getNewDumpFile(), arguments.getInCharsetName())); } /** * Creates diff on the two database schemas. * * @param writer writer the output should be written to * @param arguments object containing arguments settings * @param oldInputStream input stream of file containing dump of the * original schema * @param newInputStream input stream of file containing dump of the new * schema */ public static void createDiff(final PrintWriter writer, final PgDiffArguments arguments, final InputStream oldInputStream, final InputStream newInputStream) { diffDatabaseSchemas(writer, arguments, PgDumpLoader.loadDatabaseSchema( oldInputStream, arguments.getInCharsetName()), PgDumpLoader.loadDatabaseSchema( newInputStream, arguments.getInCharsetName())); } /** * Creates new schemas (not the objects inside the schemas). * * @param writer writer the output should be written to * @param oldDatabase original database schema * @param newDatabase new database schema */ private static void createNewSchemas(final PrintWriter writer, final PgDatabase oldDatabase, final PgDatabase newDatabase) { for (final PgSchema newSchema : newDatabase.getSchemas()) { if (oldDatabase.getSchema(newSchema.getName()) == null) { writer.println(); writer.println(newSchema.getCreationSQL()); } } } /** * Creates diff from comparison of two database schemas. * * @param writer writer the output should be written to * @param arguments object containing arguments settings * @param oldDatabase original database schema * @param newDatabase new database schema */ private static void diffDatabaseSchemas(final PrintWriter writer, final PgDiffArguments arguments, final PgDatabase oldDatabase, final PgDatabase newDatabase) { if (arguments.isAddTransaction()) { writer.println("START TRANSACTION;"); } dropOldSchemas(writer, oldDatabase, newDatabase); createNewSchemas(writer, oldDatabase, newDatabase); updateSchemas(writer, arguments, oldDatabase, newDatabase); if (arguments.isAddTransaction()) { writer.println(); writer.println("COMMIT TRANSACTION;"); } } /** * Drops old schemas that do not exist anymore. * * @param writer writer the output should be written to * @param oldDatabase original database schema * @param newDatabase new database schema */ private static void dropOldSchemas(final PrintWriter writer, final PgDatabase oldDatabase, final PgDatabase newDatabase) { for (final PgSchema oldSchema : oldDatabase.getSchemas()) { if (newDatabase.getSchema(oldSchema.getName()) == null) { writer.println(); writer.println("DROP SCHEMA " + PgDiffUtils.getQuotedName(oldSchema.getName()) + " CASCADE;"); } } } /** * Updates objects in schemas. * * @param writer writer the output should be written to * @param arguments object containing arguments settings * @param oldDatabase original database schema * @param newDatabase new database schema */ private static void updateSchemas(final PrintWriter writer, final PgDiffArguments arguments, final PgDatabase oldDatabase, final PgDatabase newDatabase) { final boolean setSearchPath = newDatabase.getSchemas().size() > 1 || !newDatabase.getSchemas().get(0).getName().equals("public"); for (final PgSchema newSchema : newDatabase.getSchemas()) { if (setSearchPath) { writer.println(); writer.println("SET search_path = " + PgDiffUtils.getQuotedName(newSchema.getName()) + ", pg_catalog;"); } final PgSchema oldSchema = oldDatabase.getSchema(newSchema.getName()); + PgDiffTriggers.dropTriggers(writer, oldSchema, newSchema); PgDiffFunctions.dropFunctions( writer, arguments, oldSchema, newSchema); - PgDiffTriggers.dropTriggers(writer, oldSchema, newSchema); PgDiffFunctions.createFunctions( writer, arguments, oldSchema, newSchema); PgDiffViews.dropViews(writer, oldSchema, newSchema); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.dropIndexes(writer, oldSchema, newSchema); PgDiffTables.dropClusters(writer, oldSchema, newSchema); PgDiffTables.dropTables(writer, oldSchema, newSchema); PgDiffSequences.dropSequences(writer, oldSchema, newSchema); PgDiffSequences.createSequences(writer, oldSchema, newSchema); PgDiffSequences.alterSequences( writer, arguments, oldSchema, newSchema); PgDiffTables.createTables(writer, oldSchema, newSchema); PgDiffTables.alterTables(writer, arguments, oldSchema, newSchema); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.createIndexes(writer, oldSchema, newSchema); PgDiffTables.createClusters(writer, oldSchema, newSchema); PgDiffTriggers.createTriggers(writer, oldSchema, newSchema); PgDiffViews.createViews(writer, oldSchema, newSchema); } } }
false
true
private static void updateSchemas(final PrintWriter writer, final PgDiffArguments arguments, final PgDatabase oldDatabase, final PgDatabase newDatabase) { final boolean setSearchPath = newDatabase.getSchemas().size() > 1 || !newDatabase.getSchemas().get(0).getName().equals("public"); for (final PgSchema newSchema : newDatabase.getSchemas()) { if (setSearchPath) { writer.println(); writer.println("SET search_path = " + PgDiffUtils.getQuotedName(newSchema.getName()) + ", pg_catalog;"); } final PgSchema oldSchema = oldDatabase.getSchema(newSchema.getName()); PgDiffFunctions.dropFunctions( writer, arguments, oldSchema, newSchema); PgDiffTriggers.dropTriggers(writer, oldSchema, newSchema); PgDiffFunctions.createFunctions( writer, arguments, oldSchema, newSchema); PgDiffViews.dropViews(writer, oldSchema, newSchema); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.dropIndexes(writer, oldSchema, newSchema); PgDiffTables.dropClusters(writer, oldSchema, newSchema); PgDiffTables.dropTables(writer, oldSchema, newSchema); PgDiffSequences.dropSequences(writer, oldSchema, newSchema); PgDiffSequences.createSequences(writer, oldSchema, newSchema); PgDiffSequences.alterSequences( writer, arguments, oldSchema, newSchema); PgDiffTables.createTables(writer, oldSchema, newSchema); PgDiffTables.alterTables(writer, arguments, oldSchema, newSchema); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.createIndexes(writer, oldSchema, newSchema); PgDiffTables.createClusters(writer, oldSchema, newSchema); PgDiffTriggers.createTriggers(writer, oldSchema, newSchema); PgDiffViews.createViews(writer, oldSchema, newSchema); } }
private static void updateSchemas(final PrintWriter writer, final PgDiffArguments arguments, final PgDatabase oldDatabase, final PgDatabase newDatabase) { final boolean setSearchPath = newDatabase.getSchemas().size() > 1 || !newDatabase.getSchemas().get(0).getName().equals("public"); for (final PgSchema newSchema : newDatabase.getSchemas()) { if (setSearchPath) { writer.println(); writer.println("SET search_path = " + PgDiffUtils.getQuotedName(newSchema.getName()) + ", pg_catalog;"); } final PgSchema oldSchema = oldDatabase.getSchema(newSchema.getName()); PgDiffTriggers.dropTriggers(writer, oldSchema, newSchema); PgDiffFunctions.dropFunctions( writer, arguments, oldSchema, newSchema); PgDiffFunctions.createFunctions( writer, arguments, oldSchema, newSchema); PgDiffViews.dropViews(writer, oldSchema, newSchema); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.dropConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.dropIndexes(writer, oldSchema, newSchema); PgDiffTables.dropClusters(writer, oldSchema, newSchema); PgDiffTables.dropTables(writer, oldSchema, newSchema); PgDiffSequences.dropSequences(writer, oldSchema, newSchema); PgDiffSequences.createSequences(writer, oldSchema, newSchema); PgDiffSequences.alterSequences( writer, arguments, oldSchema, newSchema); PgDiffTables.createTables(writer, oldSchema, newSchema); PgDiffTables.alterTables(writer, arguments, oldSchema, newSchema); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, true); PgDiffConstraints.createConstraints( writer, oldSchema, newSchema, false); PgDiffIndexes.createIndexes(writer, oldSchema, newSchema); PgDiffTables.createClusters(writer, oldSchema, newSchema); PgDiffTriggers.createTriggers(writer, oldSchema, newSchema); PgDiffViews.createViews(writer, oldSchema, newSchema); } }
diff --git a/src/main/java/org/helix/mobile/component/tab/TabRenderer.java b/src/main/java/org/helix/mobile/component/tab/TabRenderer.java index cb04299b..8d1eb6da 100644 --- a/src/main/java/org/helix/mobile/component/tab/TabRenderer.java +++ b/src/main/java/org/helix/mobile/component/tab/TabRenderer.java @@ -1,49 +1,52 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.helix.mobile.component.tab; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.renderkit.CoreRenderer; /** * This rendering is invoked by each page, which checks to see if it in a tab bar and, * if so, renders the tab bar. * * @author shallem */ public class TabRenderer extends CoreRenderer { @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { Tab tab = (Tab)component; Boolean isActive = (Boolean)tab.getAttributes().get("active"); ResponseWriter writer = context.getResponseWriter(); writer.startElement("li", component); writer.startElement("a", component); writer.writeAttribute("href", "#" + tab.getPage(), null); writer.writeAttribute("style", "height: 48px", null); //writer.writeAttribute("data-icon", "custom", null); + if (!tab.isCustomIcon()) { + writer.writeAttribute("data-icon", tab.getIcon(), null); + } String styleClass = "ui-icon-" + tab.getIcon(); if (isActive) { writer.writeAttribute("class", styleClass + " ui-btn-active", null); } else { writer.writeAttribute("class", styleClass, null); } if (tab.getName() != null) { //writer.write(tab.getName()); } } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.endElement("a"); writer.endElement("li"); } }
true
true
public void encodeBegin(FacesContext context, UIComponent component) throws IOException { Tab tab = (Tab)component; Boolean isActive = (Boolean)tab.getAttributes().get("active"); ResponseWriter writer = context.getResponseWriter(); writer.startElement("li", component); writer.startElement("a", component); writer.writeAttribute("href", "#" + tab.getPage(), null); writer.writeAttribute("style", "height: 48px", null); //writer.writeAttribute("data-icon", "custom", null); String styleClass = "ui-icon-" + tab.getIcon(); if (isActive) { writer.writeAttribute("class", styleClass + " ui-btn-active", null); } else { writer.writeAttribute("class", styleClass, null); } if (tab.getName() != null) { //writer.write(tab.getName()); } }
public void encodeBegin(FacesContext context, UIComponent component) throws IOException { Tab tab = (Tab)component; Boolean isActive = (Boolean)tab.getAttributes().get("active"); ResponseWriter writer = context.getResponseWriter(); writer.startElement("li", component); writer.startElement("a", component); writer.writeAttribute("href", "#" + tab.getPage(), null); writer.writeAttribute("style", "height: 48px", null); //writer.writeAttribute("data-icon", "custom", null); if (!tab.isCustomIcon()) { writer.writeAttribute("data-icon", tab.getIcon(), null); } String styleClass = "ui-icon-" + tab.getIcon(); if (isActive) { writer.writeAttribute("class", styleClass + " ui-btn-active", null); } else { writer.writeAttribute("class", styleClass, null); } if (tab.getName() != null) { //writer.write(tab.getName()); } }
diff --git a/src/main/java/com/stonetolb/game/module/DemoModule.java b/src/main/java/com/stonetolb/game/module/DemoModule.java index 2bb14b6..ee359a1 100644 --- a/src/main/java/com/stonetolb/game/module/DemoModule.java +++ b/src/main/java/com/stonetolb/game/module/DemoModule.java @@ -1,365 +1,365 @@ package com.stonetolb.game.module; import org.newdawn.slick.SlickException; import org.newdawn.slick.tiled.TiledMap; import com.artemis.Entity; import com.artemis.World; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Table; import com.stonetolb.asset.graphics.Texture; import com.stonetolb.asset.graphics.TextureLoader; import com.stonetolb.engine.component.control.PlayerControl; import com.stonetolb.engine.component.movement.Rotation; import com.stonetolb.engine.component.movement.Velocity; import com.stonetolb.engine.component.physics.DynamicBody; import com.stonetolb.engine.component.physics.StaticBody; import com.stonetolb.engine.component.position.Position; import com.stonetolb.engine.component.render.CameraMount; import com.stonetolb.engine.component.render.RenderComponent; import com.stonetolb.engine.component.render.SpriteControl; import com.stonetolb.engine.profiles.WorldProfile; import com.stonetolb.engine.system.CameraSystem; import com.stonetolb.engine.system.CollisionSystem; import com.stonetolb.engine.system.MovementSystem; import com.stonetolb.engine.system.PlayerControlSystem; import com.stonetolb.engine.system.RenderSystem; import com.stonetolb.engine.system.SpriteControlSystem; import com.stonetolb.render.Animation; import com.stonetolb.render.ImageRenderMode; import com.stonetolb.render.NullDrawable; import com.stonetolb.render.Sprite; import com.stonetolb.render.util.Camera; import com.stonetolb.render.util.FluidVantage; import com.stonetolb.util.Vector2f; /** * Demo module for Kent State University's ACM speaker series. * Giving a talk at Kent's ACM titled "Game Programming : Making the First Jump". * This demo module is the final game I'll be showing. * * @author james.baiera * */ public class DemoModule implements Module { private Texture vaughnTextureSheet; private Texture environmentSheet; private static int VAUGHN_TEXTURE_SHEET_WIDTH = 32; private static int VAUGHN_TEXTURE_SHEET_HEIGHT = 48; private static int TILE = 40; private static Vector2f CAMERA_START = Vector2f.from(46, 554); private World world; private Entity vaughn; private RenderSystem renderSystem; private Sprite worldCeiling; private TiledMap map; /** * {@inheritDoc Module} */ @Override public void init() { System.out.println("Loading Module Resources"); // Camera setup Camera.setVantage(FluidVantage.create(0.04F)); Camera.getInstance().setPosition(CAMERA_START); // Load texture resources try { this.vaughnTextureSheet = TextureLoader.getInstance().getTexture("sprites/Vaughn/world/Vaughn.png"); this.worldCeiling = new Sprite("maps/TheGrotto.png",ImageRenderMode.STANDING); this.environmentSheet = TextureLoader.getInstance().getTexture("maps/TreesRocksGate.gif"); } catch(Exception e) { // TODO : Throw an actual exception System.out.println("BAD THINGS HAPPENED"); e.printStackTrace(); System.exit(1); } // Gotta make a way to procedurally generate this from a file input... // Create the Sprites and Animations first: Table<Integer, Integer, Sprite> vaughnSpriteAtlas = createCharacterAtlas(); Animation.Builder builder = Animation.builder(); Animation toward = builder .addFrame(vaughnSpriteAtlas.get(0, 1), 175) .addFrame(vaughnSpriteAtlas.get(0, 2), 175) .addFrame(vaughnSpriteAtlas.get(0, 3), 175) .addFrame(vaughnSpriteAtlas.get(0, 0), 175) .build(); Animation left = builder .addFrame(vaughnSpriteAtlas.get(1, 1), 175) .addFrame(vaughnSpriteAtlas.get(1, 2), 175) .addFrame(vaughnSpriteAtlas.get(1, 3), 175) .addFrame(vaughnSpriteAtlas.get(1, 0), 175) .build(); Animation right = builder .addFrame(vaughnSpriteAtlas.get(2, 1), 175) .addFrame(vaughnSpriteAtlas.get(2, 2), 175) .addFrame(vaughnSpriteAtlas.get(2, 3), 175) .addFrame(vaughnSpriteAtlas.get(2, 0), 175) .build(); Animation away = builder .addFrame(vaughnSpriteAtlas.get(3, 1), 175) .addFrame(vaughnSpriteAtlas.get(3, 2), 175) .addFrame(vaughnSpriteAtlas.get(3, 3), 175) .addFrame(vaughnSpriteAtlas.get(3, 0), 175) .build(); Sprite tree = new Sprite(environmentSheet.getSubTexture(2*TILE, 0*TILE, 2*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite bush = new Sprite(environmentSheet.getSubTexture(3*TILE, 3*TILE, 3*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite rock = new Sprite(environmentSheet.getSubTexture(4*TILE, 2*TILE, 1*TILE, 1*TILE), ImageRenderMode.STANDING); Sprite spike= new Sprite(environmentSheet.getSubTexture(6*TILE, 0*TILE, 1*TILE, 2*TILE), ImageRenderMode.STANDING); // Processing World initialization world = new World(); renderSystem = new RenderSystem(800,600); world.setSystem(renderSystem, true); world.setSystem(new PlayerControlSystem()); world.setSystem(new MovementSystem()); world.setSystem(new SpriteControlSystem()); world.setSystem(new CameraSystem()); world.setSystem(new CollisionSystem()); world.initialize(); // Component creation Position positionComponent = new Position(1150, 700); CameraMount cameraMount = new CameraMount( VAUGHN_TEXTURE_SHEET_WIDTH/2.0F , VAUGHN_TEXTURE_SHEET_HEIGHT/2.0F ); RenderComponent renderComponent = new RenderComponent(vaughnSpriteAtlas.get(0, 0)); SpriteControl spriteControl = addAnimations( addSprites( new SpriteControl() , vaughnSpriteAtlas.get(0, 0) , vaughnSpriteAtlas.get(3, 0) , vaughnSpriteAtlas.get(2, 0) , vaughnSpriteAtlas.get(1, 0) ) , toward , away , right , left ); DynamicBody body = new DynamicBody( 1150 , 700 , 16 , 12 , 16 , 36 ); // Entity Creation vaughn = world.createEntity(); vaughn.addComponent(positionComponent); vaughn.addComponent(renderComponent); vaughn.addComponent(new Rotation(WorldProfile.WorldDirection.DOWN.getDirection())); vaughn.addComponent(new Velocity(WorldProfile.Speed.STOP.getSpeed())); vaughn.addComponent(new PlayerControl(WorldProfile.Control.ARROWS)); vaughn.addComponent(spriteControl); vaughn.addComponent(Camera.attachTo(cameraMount)); vaughn.addComponent(body); vaughn.addToWorld(); Entity treeEnt = world.createEntity(); treeEnt.addComponent(new Position(28*TILE, 14*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(28*TILE, 14*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(15*TILE, 13*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(15*TILE, 13*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(24*TILE, 19*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(24*TILE, 19*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); Entity rockEnt = world.createEntity(); rockEnt.addComponent(new Position(26*TILE,18*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(26*TILE, 18*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(21*TILE,14*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(21*TILE, 14*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(20*TILE,19*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(20*TILE, 19*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); Entity bushEnt = world.createEntity(); bushEnt.addComponent(new Position(38*TILE, 22*TILE)); bushEnt.addComponent(new RenderComponent(bush)); bushEnt.addComponent(new StaticBody(38*TILE, 22*TILE, 75, 50, 65, 90)); bushEnt.addToWorld(); Entity spireEnt = world.createEntity(); spireEnt.addComponent(new Position(34*TILE,20*TILE)); spireEnt.addComponent(new RenderComponent(spike)); spireEnt.addComponent(new StaticBody(34*TILE, 20*TILE,40, 30, 20, 60)); spireEnt.addToWorld(); // Create Tiled Map try { - map = new TiledMap("maps/grotto.tmx"); + map = new TiledMap("src/main/resources/maps/grotto.tmx"); } catch(SlickException se) { // TODO : Throw an actual exception se.printStackTrace(); System.exit(1); } System.out.println("Load Complete"); } /** * {@inheritDoc Module} */ @Override public void step(long delta) { // Set delta in world object. world.setDelta(delta); // Run system logic over entities world.process(); } /** * {@inheritDoc Module} */ @Override public void render(long delta) { // Clear Screen renderSystem.clearScreen(); // Render the Ground and backdrop map.render(0, 0, 0); map.render(0, 0, 1); // Render Entites renderSystem.process(); // Render the front cliff edge worldCeiling.draw(9*40, 20*40, 50, delta); } @Override public String toString() { // String Identifier return "DemoModule"; } /** * Takes a SpriteControl and adds the character's animation objects to it. * This method will take care of Animation Cloning. * @param sc * @param first - First Animation * @param rest - Array of three more Animations * @return Initialized {@link SpriteControl} Object */ private SpriteControl addAnimations(SpriteControl sc, Animation first, Animation ... rest) { Preconditions.checkArgument(rest.length >= 3, "Incorrect Animation List Size"); return sc .setNoOp(NullDrawable.getInstance()) .addAction( first.clone(), WorldProfile.Speed.WALK.getSpeed(), WorldProfile.WorldDirection.DOWN.getDirection() ) .addAction( rest[0].clone(), WorldProfile.Speed.WALK.getSpeed(), WorldProfile.WorldDirection.UP.getDirection() ) .addAction( rest[1].clone(), WorldProfile.Speed.WALK.getSpeed(), WorldProfile.WorldDirection.RIGHT.getDirection() ) .addAction( rest[2].clone(), WorldProfile.Speed.WALK.getSpeed(), WorldProfile.WorldDirection.LEFT.getDirection() ); } /** * Takes a SpriteControl and adds the character's sprites to it * @param sc * @param first - First sprite * @param rest - Array of three more sprites * @return Initialized {@link SpriteControl} Object */ private SpriteControl addSprites(SpriteControl sc, Sprite first, Sprite ... rest) { Preconditions.checkArgument(rest.length >= 3, "Incorrect Sprite List Size"); return sc .addAction( first, WorldProfile.Speed.STOP.getSpeed(), WorldProfile.WorldDirection.DOWN.getDirection() ) .addAction( rest[0], WorldProfile.Speed.STOP.getSpeed(), WorldProfile.WorldDirection.UP.getDirection() ) .addAction( rest[1], WorldProfile.Speed.STOP.getSpeed(), WorldProfile.WorldDirection.RIGHT.getDirection() ) .addAction( rest[2], WorldProfile.Speed.STOP.getSpeed(), WorldProfile.WorldDirection.LEFT.getDirection() ); } /** * Spin off method to populate a Guava Table with textures for the character sprite sheet. * @return Table representing a sprite atlas. */ private Table<Integer, Integer, Sprite> createCharacterAtlas() { ImmutableTable.Builder<Integer, Integer, Sprite> builder = ImmutableTable.builder(); Sprite sprite = null; for(int row = 0; row < 4; row++) { for(int col = 0; col < 4; col++) { sprite = new Sprite( vaughnTextureSheet.getSubTexture( col*VAUGHN_TEXTURE_SHEET_WIDTH , row*VAUGHN_TEXTURE_SHEET_HEIGHT , VAUGHN_TEXTURE_SHEET_WIDTH , VAUGHN_TEXTURE_SHEET_HEIGHT ) , ImageRenderMode.STANDING ); builder.put(row, col,sprite); } } return builder.build(); } }
true
true
public void init() { System.out.println("Loading Module Resources"); // Camera setup Camera.setVantage(FluidVantage.create(0.04F)); Camera.getInstance().setPosition(CAMERA_START); // Load texture resources try { this.vaughnTextureSheet = TextureLoader.getInstance().getTexture("sprites/Vaughn/world/Vaughn.png"); this.worldCeiling = new Sprite("maps/TheGrotto.png",ImageRenderMode.STANDING); this.environmentSheet = TextureLoader.getInstance().getTexture("maps/TreesRocksGate.gif"); } catch(Exception e) { // TODO : Throw an actual exception System.out.println("BAD THINGS HAPPENED"); e.printStackTrace(); System.exit(1); } // Gotta make a way to procedurally generate this from a file input... // Create the Sprites and Animations first: Table<Integer, Integer, Sprite> vaughnSpriteAtlas = createCharacterAtlas(); Animation.Builder builder = Animation.builder(); Animation toward = builder .addFrame(vaughnSpriteAtlas.get(0, 1), 175) .addFrame(vaughnSpriteAtlas.get(0, 2), 175) .addFrame(vaughnSpriteAtlas.get(0, 3), 175) .addFrame(vaughnSpriteAtlas.get(0, 0), 175) .build(); Animation left = builder .addFrame(vaughnSpriteAtlas.get(1, 1), 175) .addFrame(vaughnSpriteAtlas.get(1, 2), 175) .addFrame(vaughnSpriteAtlas.get(1, 3), 175) .addFrame(vaughnSpriteAtlas.get(1, 0), 175) .build(); Animation right = builder .addFrame(vaughnSpriteAtlas.get(2, 1), 175) .addFrame(vaughnSpriteAtlas.get(2, 2), 175) .addFrame(vaughnSpriteAtlas.get(2, 3), 175) .addFrame(vaughnSpriteAtlas.get(2, 0), 175) .build(); Animation away = builder .addFrame(vaughnSpriteAtlas.get(3, 1), 175) .addFrame(vaughnSpriteAtlas.get(3, 2), 175) .addFrame(vaughnSpriteAtlas.get(3, 3), 175) .addFrame(vaughnSpriteAtlas.get(3, 0), 175) .build(); Sprite tree = new Sprite(environmentSheet.getSubTexture(2*TILE, 0*TILE, 2*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite bush = new Sprite(environmentSheet.getSubTexture(3*TILE, 3*TILE, 3*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite rock = new Sprite(environmentSheet.getSubTexture(4*TILE, 2*TILE, 1*TILE, 1*TILE), ImageRenderMode.STANDING); Sprite spike= new Sprite(environmentSheet.getSubTexture(6*TILE, 0*TILE, 1*TILE, 2*TILE), ImageRenderMode.STANDING); // Processing World initialization world = new World(); renderSystem = new RenderSystem(800,600); world.setSystem(renderSystem, true); world.setSystem(new PlayerControlSystem()); world.setSystem(new MovementSystem()); world.setSystem(new SpriteControlSystem()); world.setSystem(new CameraSystem()); world.setSystem(new CollisionSystem()); world.initialize(); // Component creation Position positionComponent = new Position(1150, 700); CameraMount cameraMount = new CameraMount( VAUGHN_TEXTURE_SHEET_WIDTH/2.0F , VAUGHN_TEXTURE_SHEET_HEIGHT/2.0F ); RenderComponent renderComponent = new RenderComponent(vaughnSpriteAtlas.get(0, 0)); SpriteControl spriteControl = addAnimations( addSprites( new SpriteControl() , vaughnSpriteAtlas.get(0, 0) , vaughnSpriteAtlas.get(3, 0) , vaughnSpriteAtlas.get(2, 0) , vaughnSpriteAtlas.get(1, 0) ) , toward , away , right , left ); DynamicBody body = new DynamicBody( 1150 , 700 , 16 , 12 , 16 , 36 ); // Entity Creation vaughn = world.createEntity(); vaughn.addComponent(positionComponent); vaughn.addComponent(renderComponent); vaughn.addComponent(new Rotation(WorldProfile.WorldDirection.DOWN.getDirection())); vaughn.addComponent(new Velocity(WorldProfile.Speed.STOP.getSpeed())); vaughn.addComponent(new PlayerControl(WorldProfile.Control.ARROWS)); vaughn.addComponent(spriteControl); vaughn.addComponent(Camera.attachTo(cameraMount)); vaughn.addComponent(body); vaughn.addToWorld(); Entity treeEnt = world.createEntity(); treeEnt.addComponent(new Position(28*TILE, 14*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(28*TILE, 14*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(15*TILE, 13*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(15*TILE, 13*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(24*TILE, 19*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(24*TILE, 19*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); Entity rockEnt = world.createEntity(); rockEnt.addComponent(new Position(26*TILE,18*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(26*TILE, 18*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(21*TILE,14*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(21*TILE, 14*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(20*TILE,19*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(20*TILE, 19*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); Entity bushEnt = world.createEntity(); bushEnt.addComponent(new Position(38*TILE, 22*TILE)); bushEnt.addComponent(new RenderComponent(bush)); bushEnt.addComponent(new StaticBody(38*TILE, 22*TILE, 75, 50, 65, 90)); bushEnt.addToWorld(); Entity spireEnt = world.createEntity(); spireEnt.addComponent(new Position(34*TILE,20*TILE)); spireEnt.addComponent(new RenderComponent(spike)); spireEnt.addComponent(new StaticBody(34*TILE, 20*TILE,40, 30, 20, 60)); spireEnt.addToWorld(); // Create Tiled Map try { map = new TiledMap("maps/grotto.tmx"); } catch(SlickException se) { // TODO : Throw an actual exception se.printStackTrace(); System.exit(1); } System.out.println("Load Complete"); }
public void init() { System.out.println("Loading Module Resources"); // Camera setup Camera.setVantage(FluidVantage.create(0.04F)); Camera.getInstance().setPosition(CAMERA_START); // Load texture resources try { this.vaughnTextureSheet = TextureLoader.getInstance().getTexture("sprites/Vaughn/world/Vaughn.png"); this.worldCeiling = new Sprite("maps/TheGrotto.png",ImageRenderMode.STANDING); this.environmentSheet = TextureLoader.getInstance().getTexture("maps/TreesRocksGate.gif"); } catch(Exception e) { // TODO : Throw an actual exception System.out.println("BAD THINGS HAPPENED"); e.printStackTrace(); System.exit(1); } // Gotta make a way to procedurally generate this from a file input... // Create the Sprites and Animations first: Table<Integer, Integer, Sprite> vaughnSpriteAtlas = createCharacterAtlas(); Animation.Builder builder = Animation.builder(); Animation toward = builder .addFrame(vaughnSpriteAtlas.get(0, 1), 175) .addFrame(vaughnSpriteAtlas.get(0, 2), 175) .addFrame(vaughnSpriteAtlas.get(0, 3), 175) .addFrame(vaughnSpriteAtlas.get(0, 0), 175) .build(); Animation left = builder .addFrame(vaughnSpriteAtlas.get(1, 1), 175) .addFrame(vaughnSpriteAtlas.get(1, 2), 175) .addFrame(vaughnSpriteAtlas.get(1, 3), 175) .addFrame(vaughnSpriteAtlas.get(1, 0), 175) .build(); Animation right = builder .addFrame(vaughnSpriteAtlas.get(2, 1), 175) .addFrame(vaughnSpriteAtlas.get(2, 2), 175) .addFrame(vaughnSpriteAtlas.get(2, 3), 175) .addFrame(vaughnSpriteAtlas.get(2, 0), 175) .build(); Animation away = builder .addFrame(vaughnSpriteAtlas.get(3, 1), 175) .addFrame(vaughnSpriteAtlas.get(3, 2), 175) .addFrame(vaughnSpriteAtlas.get(3, 3), 175) .addFrame(vaughnSpriteAtlas.get(3, 0), 175) .build(); Sprite tree = new Sprite(environmentSheet.getSubTexture(2*TILE, 0*TILE, 2*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite bush = new Sprite(environmentSheet.getSubTexture(3*TILE, 3*TILE, 3*TILE, 3*TILE), ImageRenderMode.STANDING); Sprite rock = new Sprite(environmentSheet.getSubTexture(4*TILE, 2*TILE, 1*TILE, 1*TILE), ImageRenderMode.STANDING); Sprite spike= new Sprite(environmentSheet.getSubTexture(6*TILE, 0*TILE, 1*TILE, 2*TILE), ImageRenderMode.STANDING); // Processing World initialization world = new World(); renderSystem = new RenderSystem(800,600); world.setSystem(renderSystem, true); world.setSystem(new PlayerControlSystem()); world.setSystem(new MovementSystem()); world.setSystem(new SpriteControlSystem()); world.setSystem(new CameraSystem()); world.setSystem(new CollisionSystem()); world.initialize(); // Component creation Position positionComponent = new Position(1150, 700); CameraMount cameraMount = new CameraMount( VAUGHN_TEXTURE_SHEET_WIDTH/2.0F , VAUGHN_TEXTURE_SHEET_HEIGHT/2.0F ); RenderComponent renderComponent = new RenderComponent(vaughnSpriteAtlas.get(0, 0)); SpriteControl spriteControl = addAnimations( addSprites( new SpriteControl() , vaughnSpriteAtlas.get(0, 0) , vaughnSpriteAtlas.get(3, 0) , vaughnSpriteAtlas.get(2, 0) , vaughnSpriteAtlas.get(1, 0) ) , toward , away , right , left ); DynamicBody body = new DynamicBody( 1150 , 700 , 16 , 12 , 16 , 36 ); // Entity Creation vaughn = world.createEntity(); vaughn.addComponent(positionComponent); vaughn.addComponent(renderComponent); vaughn.addComponent(new Rotation(WorldProfile.WorldDirection.DOWN.getDirection())); vaughn.addComponent(new Velocity(WorldProfile.Speed.STOP.getSpeed())); vaughn.addComponent(new PlayerControl(WorldProfile.Control.ARROWS)); vaughn.addComponent(spriteControl); vaughn.addComponent(Camera.attachTo(cameraMount)); vaughn.addComponent(body); vaughn.addToWorld(); Entity treeEnt = world.createEntity(); treeEnt.addComponent(new Position(28*TILE, 14*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(28*TILE, 14*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(15*TILE, 13*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(15*TILE, 13*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); treeEnt = world.createEntity(); treeEnt.addComponent(new Position(24*TILE, 19*TILE)); treeEnt.addComponent(new RenderComponent(tree)); treeEnt.addComponent(new StaticBody(24*TILE, 19*TILE, 60, 50, 40, 95)); treeEnt.addToWorld(); Entity rockEnt = world.createEntity(); rockEnt.addComponent(new Position(26*TILE,18*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(26*TILE, 18*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(21*TILE,14*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(21*TILE, 14*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); rockEnt = world.createEntity(); rockEnt.addComponent(new Position(20*TILE,19*TILE)); rockEnt.addComponent(new RenderComponent(rock)); rockEnt.addComponent(new StaticBody(20*TILE, 19*TILE,40, 15, 20, 30)); rockEnt.addToWorld(); Entity bushEnt = world.createEntity(); bushEnt.addComponent(new Position(38*TILE, 22*TILE)); bushEnt.addComponent(new RenderComponent(bush)); bushEnt.addComponent(new StaticBody(38*TILE, 22*TILE, 75, 50, 65, 90)); bushEnt.addToWorld(); Entity spireEnt = world.createEntity(); spireEnt.addComponent(new Position(34*TILE,20*TILE)); spireEnt.addComponent(new RenderComponent(spike)); spireEnt.addComponent(new StaticBody(34*TILE, 20*TILE,40, 30, 20, 60)); spireEnt.addToWorld(); // Create Tiled Map try { map = new TiledMap("src/main/resources/maps/grotto.tmx"); } catch(SlickException se) { // TODO : Throw an actual exception se.printStackTrace(); System.exit(1); } System.out.println("Load Complete"); }
diff --git a/grader/src/com/evllabs/grader/Grader.java b/grader/src/com/evllabs/grader/Grader.java index 5e67e81..194a725 100644 --- a/grader/src/com/evllabs/grader/Grader.java +++ b/grader/src/com/evllabs/grader/Grader.java @@ -1,65 +1,65 @@ package com.evllabs.grader; import java.util.*; import java.util.Map.Entry; import com.evllabs.grader.structures.Histogram; public class Grader { /** * @param args */ public static void main(String[] args) { Scanner input = new Scanner(System.in); int counter = 0; Histogram authors = new Histogram(); Map<String, List<Histogram>> ranks = new HashMap<String, List<Histogram>>(); List<Histogram> currentRanks = new ArrayList<Histogram>(); while(input.hasNext()){ String line = input.nextLine(); if(counter == 0){ authors.add(line); currentRanks = ranks.get(line); if(currentRanks == null){ currentRanks = new ArrayList<Histogram>(); ranks.put(line, currentRanks); } }else if(counter > 5){ if(line.isEmpty()){ continue; }else if(line.equalsIgnoreCase("------------------------")){ counter = 0; continue; } int rank = counter -5; Histogram currentRank; try{ currentRank = currentRanks.get(rank); } catch(IndexOutOfBoundsException e){ currentRank = new Histogram(); currentRanks.add(currentRank); } - currentRank.add(line); + currentRank.add(line.split(" ")[0]); } counter++; } Set<Entry<String,List<Histogram>>> rankEntries = ranks.entrySet(); for(Entry<String, List<Histogram>> entry : rankEntries){ List<Histogram> current = entry.getValue(); System.out.println(entry.getKey()+" "+authors.get(entry.getKey())); for(int i =0; i<current.size();i++){ StringBuilder resultBuilder = new StringBuilder(); resultBuilder.append(i+1); Set<Entry<String, Integer>> rankSet = current.get(i).entrySet(); for(Entry<String, Integer> rankEntry : rankSet){ resultBuilder.append(" ").append(rankEntry.getKey()).append(":").append(rankEntry.getValue()); } System.out.println(resultBuilder.toString()); } System.out.println(); } } }
true
true
public static void main(String[] args) { Scanner input = new Scanner(System.in); int counter = 0; Histogram authors = new Histogram(); Map<String, List<Histogram>> ranks = new HashMap<String, List<Histogram>>(); List<Histogram> currentRanks = new ArrayList<Histogram>(); while(input.hasNext()){ String line = input.nextLine(); if(counter == 0){ authors.add(line); currentRanks = ranks.get(line); if(currentRanks == null){ currentRanks = new ArrayList<Histogram>(); ranks.put(line, currentRanks); } }else if(counter > 5){ if(line.isEmpty()){ continue; }else if(line.equalsIgnoreCase("------------------------")){ counter = 0; continue; } int rank = counter -5; Histogram currentRank; try{ currentRank = currentRanks.get(rank); } catch(IndexOutOfBoundsException e){ currentRank = new Histogram(); currentRanks.add(currentRank); } currentRank.add(line); } counter++; } Set<Entry<String,List<Histogram>>> rankEntries = ranks.entrySet(); for(Entry<String, List<Histogram>> entry : rankEntries){ List<Histogram> current = entry.getValue(); System.out.println(entry.getKey()+" "+authors.get(entry.getKey())); for(int i =0; i<current.size();i++){ StringBuilder resultBuilder = new StringBuilder(); resultBuilder.append(i+1); Set<Entry<String, Integer>> rankSet = current.get(i).entrySet(); for(Entry<String, Integer> rankEntry : rankSet){ resultBuilder.append(" ").append(rankEntry.getKey()).append(":").append(rankEntry.getValue()); } System.out.println(resultBuilder.toString()); } System.out.println(); } }
public static void main(String[] args) { Scanner input = new Scanner(System.in); int counter = 0; Histogram authors = new Histogram(); Map<String, List<Histogram>> ranks = new HashMap<String, List<Histogram>>(); List<Histogram> currentRanks = new ArrayList<Histogram>(); while(input.hasNext()){ String line = input.nextLine(); if(counter == 0){ authors.add(line); currentRanks = ranks.get(line); if(currentRanks == null){ currentRanks = new ArrayList<Histogram>(); ranks.put(line, currentRanks); } }else if(counter > 5){ if(line.isEmpty()){ continue; }else if(line.equalsIgnoreCase("------------------------")){ counter = 0; continue; } int rank = counter -5; Histogram currentRank; try{ currentRank = currentRanks.get(rank); } catch(IndexOutOfBoundsException e){ currentRank = new Histogram(); currentRanks.add(currentRank); } currentRank.add(line.split(" ")[0]); } counter++; } Set<Entry<String,List<Histogram>>> rankEntries = ranks.entrySet(); for(Entry<String, List<Histogram>> entry : rankEntries){ List<Histogram> current = entry.getValue(); System.out.println(entry.getKey()+" "+authors.get(entry.getKey())); for(int i =0; i<current.size();i++){ StringBuilder resultBuilder = new StringBuilder(); resultBuilder.append(i+1); Set<Entry<String, Integer>> rankSet = current.get(i).entrySet(); for(Entry<String, Integer> rankEntry : rankSet){ resultBuilder.append(" ").append(rankEntry.getKey()).append(":").append(rankEntry.getValue()); } System.out.println(resultBuilder.toString()); } System.out.println(); } }
diff --git a/main/src/main/java/com/bloatit/web/linkable/money/AccountChargingProcess.java b/main/src/main/java/com/bloatit/web/linkable/money/AccountChargingProcess.java index 1ffd03312..ed509ac57 100644 --- a/main/src/main/java/com/bloatit/web/linkable/money/AccountChargingProcess.java +++ b/main/src/main/java/com/bloatit/web/linkable/money/AccountChargingProcess.java @@ -1,64 +1,64 @@ // // Copyright (c) 2011 Linkeos. // // This file is part of Elveos.org. // Elveos.org 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. // // Elveos.org 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 Elveos.org. If not, see http://www.gnu.org/licenses/. // package com.bloatit.web.linkable.money; import com.bloatit.framework.webprocessor.PaymentProcess; import com.bloatit.framework.webprocessor.WebProcess; import com.bloatit.framework.webprocessor.annotations.ParamContainer; import com.bloatit.framework.webprocessor.annotations.ParamContainer.Protocol; import com.bloatit.framework.webprocessor.url.Url; import com.bloatit.web.url.AccountChargingPageUrl; import com.bloatit.web.url.AccountChargingProcessUrl; import com.bloatit.web.url.AccountPageUrl; @ParamContainer(value="account/charging/process", protocol=Protocol.HTTPS) public class AccountChargingProcess extends PaymentProcess { @SuppressWarnings("unused") private final AccountChargingProcessUrl url; public AccountChargingProcess(final AccountChargingProcessUrl url) { super(url); this.url = url; } @Override protected Url doProcess() { return new AccountChargingPageUrl(this); } @Override public Url notifyChildClosed(final WebProcess subProcess) { if (subProcess.getClass().equals(PaylineProcess.class)) { final PaylineProcess subPro = (PaylineProcess) subProcess; if (subPro.isSuccessful()) { // Redirects to the contribution action which will perform the // actual contribution return new AccountPageUrl(); } unlock(); - return new AccountPageUrl(); + return new AccountChargingPageUrl(this); } return null; } @Override public void doDoLoad() { // Nothing to do. } }
true
true
public Url notifyChildClosed(final WebProcess subProcess) { if (subProcess.getClass().equals(PaylineProcess.class)) { final PaylineProcess subPro = (PaylineProcess) subProcess; if (subPro.isSuccessful()) { // Redirects to the contribution action which will perform the // actual contribution return new AccountPageUrl(); } unlock(); return new AccountPageUrl(); } return null; }
public Url notifyChildClosed(final WebProcess subProcess) { if (subProcess.getClass().equals(PaylineProcess.class)) { final PaylineProcess subPro = (PaylineProcess) subProcess; if (subPro.isSuccessful()) { // Redirects to the contribution action which will perform the // actual contribution return new AccountPageUrl(); } unlock(); return new AccountChargingPageUrl(this); } return null; }
diff --git a/src/main/java/me/zford/jobs/config/JobConfig.java b/src/main/java/me/zford/jobs/config/JobConfig.java index 9f84927..fbd68f3 100644 --- a/src/main/java/me/zford/jobs/config/JobConfig.java +++ b/src/main/java/me/zford/jobs/config/JobConfig.java @@ -1,516 +1,516 @@ /* * Jobs Plugin for Bukkit * Copyright (C) 2011 Zak Ford <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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 me.zford.jobs.config; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.WeakHashMap; import me.zford.jobs.Jobs; import me.zford.jobs.config.container.DisplayMethod; import me.zford.jobs.config.container.Job; import me.zford.jobs.config.container.JobPermission; import me.zford.jobs.config.container.JobsLivingEntityInfo; import me.zford.jobs.config.container.JobsMaterialInfo; import me.zford.jobs.resources.jfep.Parser; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.material.MaterialData; public class JobConfig { // all of the possible jobs private LinkedHashMap<String, Job> jobs = new LinkedHashMap<String, Job>(); // used slots for each job private WeakHashMap<Job, Integer> usedSlots = new WeakHashMap<Job, Integer>(); private Jobs plugin; public JobConfig(Jobs plugin) { this.plugin = plugin; } public void reload() { // job settings loadJobSettings(); // get slots loadSlots(); } /** * Method to load the jobs configuration * * loads from Jobs/jobConfig.yml */ private void loadJobSettings(){ File f = new File(plugin.getDataFolder(), "jobConfig.yml"); this.jobs.clear(); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { plugin.getLogger().severe("Unable to create jobConfig.yml! No jobs were loaded!"); return; } } YamlConfiguration conf = new YamlConfiguration(); conf.options().pathSeparator('/'); conf.options().header(new StringBuilder() .append("Jobs configuration.").append(System.getProperty("line.separator")) .append(System.getProperty("line.separator")) .append("Stores information about each job.").append(System.getProperty("line.separator")) .append(System.getProperty("line.separator")) .append("For example configurations, visit http://dev.bukkit.org/server-mods/jobs/.").append(System.getProperty("line.separator")) .toString()); try { conf.load(f); } catch (Exception e) { plugin.getServer().getLogger().severe("==================== Jobs ===================="); plugin.getServer().getLogger().severe("Unable to load jobConfig.yml!"); plugin.getServer().getLogger().severe("Check your config for formatting issues!"); plugin.getServer().getLogger().severe("No jobs were loaded!"); plugin.getServer().getLogger().severe("Error: "+e.getMessage()); plugin.getServer().getLogger().severe("=============================================="); return; } ConfigurationSection jobsSection = conf.getConfigurationSection("Jobs"); if (jobsSection == null) { jobsSection = conf.createSection("Jobs"); } for (String jobKey : jobsSection.getKeys(false)) { ConfigurationSection jobSection = jobsSection.getConfigurationSection(jobKey); String jobName = jobSection.getString("fullname"); if (jobName == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid fullname property. Skipping job!"); continue; } Integer maxLevel = jobSection.getInt("max-level", 0); if (maxLevel.intValue() <= 0) { maxLevel = null; } Integer maxSlots = jobSection.getInt("slots", 0); if (maxSlots.intValue() <= 0) { maxSlots = null; } String jobShortName = jobSection.getString("shortname"); if (jobShortName == null) { plugin.getLogger().severe("Job " + jobKey + " is missing the shortname property. Skipping job!"); continue; } ChatColor jobColour; try { jobColour = ChatColor.valueOf(jobSection.getString("ChatColour", "").toUpperCase()); } catch (IllegalArgumentException e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid ChatColour property. Skipping job!"); continue; } String disp = jobSection.getString("chat-display", ""); DisplayMethod displayMethod; if (disp.equalsIgnoreCase("full")) { displayMethod = DisplayMethod.FULL; } else if(disp.equalsIgnoreCase("job")) { displayMethod = DisplayMethod.JOB; } else if(disp.equalsIgnoreCase("title")) { displayMethod = DisplayMethod.TITLE; } else if(disp.equalsIgnoreCase("none")) { displayMethod = DisplayMethod.NONE; } else if(disp.equalsIgnoreCase("shortfull")) { displayMethod = DisplayMethod.SHORT_FULL; } else if(disp.equalsIgnoreCase("shortjob")) { displayMethod = DisplayMethod.SHORT_JOB; } else if(disp.equalsIgnoreCase("shorttitle")) { displayMethod = DisplayMethod.SHORT_TITLE; } else { plugin.getLogger().warning("Job " + jobKey + " has an invalid chat-display property. Defaulting to None!"); displayMethod = DisplayMethod.NONE; } Parser maxExpEquation; String maxExpEquationInput = jobSection.getString("leveling-progression-equation"); try { maxExpEquation = new Parser(maxExpEquationInput); // test equation maxExpEquation.setVariable("numjobs", 1); maxExpEquation.setVariable("joblevel", 1); maxExpEquation.getValue(); } catch(Exception e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid leveling-progression-equation property. Skipping job!"); continue; } Parser incomeEquation; String incomeEquationInput = jobSection.getString("income-progression-equation"); try { incomeEquation = new Parser(incomeEquationInput); // test equation incomeEquation.setVariable("numjobs", 1); incomeEquation.setVariable("joblevel", 1); incomeEquation.setVariable("baseincome", 1); incomeEquation.getValue(); } catch(Exception e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid income-progression-equation property. Skipping job!"); continue; } Parser expEquation; String expEquationInput = jobSection.getString("experience-progression-equation"); try { expEquation = new Parser(expEquationInput); // test equation expEquation.setVariable("numjobs", 1); expEquation.setVariable("joblevel", 1); expEquation.setVariable("baseexperience", 1); expEquation.getValue(); } catch(Exception e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid experience-progression-equation property. Skipping job!"); continue; } // items // break ConfigurationSection breakSection = jobSection.getConfigurationSection("Break"); HashMap<String, JobsMaterialInfo> jobBreakInfo = new HashMap<String, JobsMaterialInfo>(); if (breakSection != null) { for (String breakKey : breakSection.getKeys(false)) { ConfigurationSection breakItem = breakSection.getConfigurationSection(breakKey); String materialType = breakKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if (material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + breakKey + " Break material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = breakItem.getDouble("income", 0.0); Double experience = breakItem.getDouble("experience", 0.0); jobBreakInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // place ConfigurationSection placeSection = jobSection.getConfigurationSection("Place"); HashMap<String, JobsMaterialInfo> jobPlaceInfo = new HashMap<String, JobsMaterialInfo>(); if (placeSection != null) { for (String placeKey : placeSection.getKeys(false)) { ConfigurationSection placeItem = placeSection.getConfigurationSection(placeKey); String materialType = placeKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + placeKey + " Place material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = placeItem.getDouble("income", 0.0); Double experience = placeItem.getDouble("experience", 0.0); jobPlaceInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // craft ConfigurationSection craftSection = jobSection.getConfigurationSection("Craft"); HashMap<String, JobsMaterialInfo> jobCraftInfo = new HashMap<String, JobsMaterialInfo>(); if (craftSection != null) { for (String craftKey : craftSection.getKeys(false)) { ConfigurationSection craftItem = craftSection.getConfigurationSection(craftKey); String materialType = craftKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + craftKey + " Craft material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = craftItem.getDouble("income", 0.0); Double experience = craftItem.getDouble("experience", 0.0); jobCraftInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // smelt ConfigurationSection smeltSection = jobSection.getConfigurationSection("Smelt"); HashMap<String, JobsMaterialInfo> jobSmeltInfo = new HashMap<String, JobsMaterialInfo>(); - if (craftSection != null) { + if (smeltSection != null) { for (String smeltKey : smeltSection.getKeys(false)) { ConfigurationSection smeltItem = smeltSection.getConfigurationSection(smeltKey); String materialType = smeltKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + smeltKey + " Smelt material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = smeltItem.getDouble("income", 0.0); Double experience = smeltItem.getDouble("experience", 0.0); jobSmeltInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // kill ConfigurationSection killSection = jobSection.getConfigurationSection("Kill"); HashMap<String, JobsLivingEntityInfo> jobKillInfo = new HashMap<String, JobsLivingEntityInfo>(); if (killSection != null) { for (String killKey : killSection.getKeys(false)) { ConfigurationSection killItem = killSection.getConfigurationSection(killKey); Class<?> victim; try { victim = Class.forName("org.bukkit.craftbukkit.entity.Craft"+killKey); } catch (ClassNotFoundException e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + killKey + " Kill entity type property. Skipping!"); continue; } Double income = killItem.getDouble("income", 0.0); Double experience = killItem.getDouble("experience", 0.0); jobKillInfo.put(("org.bukkit.craftbukkit.entity.Craft"+killKey).trim(), new JobsLivingEntityInfo(victim, experience, income)); } } // fish ConfigurationSection fishSection = jobSection.getConfigurationSection("Fish"); HashMap<String, JobsMaterialInfo> jobFishInfo = new HashMap<String, JobsMaterialInfo>(); if (fishSection != null) { for (String fishKey : fishSection.getKeys(false)) { ConfigurationSection fishItem = fishSection.getConfigurationSection(fishKey); String materialType = fishKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + fishKey + " Fish material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = fishItem.getDouble("income", 0.0); Double experience = fishItem.getDouble("experience", 0.0); jobFishInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // custom-kill ConfigurationSection customKillSection = jobSection.getConfigurationSection("custom-kill"); if (customKillSection != null) { for (String customKillKey : customKillSection.getKeys(false)) { ConfigurationSection customKillItem = customKillSection.getConfigurationSection(customKillKey); String entityType = customKillKey.toString(); Double income = customKillItem.getDouble("income", 0.0); Double experience = customKillItem.getDouble("experience", 0.0); try { jobKillInfo.put(("org.bukkit.craftbukkit.entity.CraftPlayer:"+entityType).trim(), new JobsLivingEntityInfo(Class.forName("org.bukkit.craftbukkit.entity.CraftPlayer"), experience, income)); } catch (ClassNotFoundException e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + customKillKey + " custom-kill entity type property. Skipping!"); continue; } } } // Permissions ArrayList<JobPermission> jobPermissions = new ArrayList<JobPermission>(); ConfigurationSection permissionsSection = jobSection.getConfigurationSection("permissions"); if(permissionsSection != null) { for(String permissionKey : permissionsSection.getKeys(false)) { ConfigurationSection permissionSection = permissionsSection.getConfigurationSection(permissionKey); String node = permissionKey.toLowerCase(); if (permissionSection == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid permission key" + permissionKey + "!"); continue; } boolean value = permissionSection.getBoolean("value", true); int levelRequirement = permissionSection.getInt("level", 0); jobPermissions.add(new JobPermission(node, value, levelRequirement)); } } boolean isHidden = false; if (jobKey.equalsIgnoreCase("none")) { isHidden = true; } this.jobs.put(jobName.toLowerCase(), new Job(jobBreakInfo, jobPlaceInfo, jobKillInfo, jobFishInfo, jobCraftInfo, jobSmeltInfo, jobPermissions, jobName, jobShortName, jobColour, maxExpEquation, incomeEquation, expEquation, displayMethod, maxLevel, maxSlots, isHidden)); } try { conf.save(f); } catch (IOException e) { e.printStackTrace(); } } /** * Load the slots available */ private void loadSlots() { usedSlots.clear(); for(Job temp: jobs.values()){ usedSlots.put(temp, plugin.getJobsConfiguration().getJobsDAO().getSlotsTaken(temp)); } } /** * Function to return the job information that matches the jobName given * @param jobName - the ame of the job given * @return the job that matches the name */ public Job getJob(String jobName){ return jobs.get(jobName.toLowerCase()); } /** * Get all the jobs loaded in the plugin * @return a collection of the jobs */ public Collection<Job> getJobs() { return Collections.unmodifiableCollection(jobs.values()); } /** * Function to get the number of slots used on the server for this job * @param job - the job * @return the number of slots */ public int getUsedSlots(Job job){ return usedSlots.get(job); } /** * Function to increase the number of used slots for a job * @param job - the job someone is taking */ public void takeSlot(Job job){ usedSlots.put(job, usedSlots.get(job)+1); } /** * Function to decrease the number of used slots for a job * @param job - the job someone is leaving */ public void leaveSlot(Job job){ usedSlots.put(job, usedSlots.get(job)-1); } }
true
true
private void loadJobSettings(){ File f = new File(plugin.getDataFolder(), "jobConfig.yml"); this.jobs.clear(); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { plugin.getLogger().severe("Unable to create jobConfig.yml! No jobs were loaded!"); return; } } YamlConfiguration conf = new YamlConfiguration(); conf.options().pathSeparator('/'); conf.options().header(new StringBuilder() .append("Jobs configuration.").append(System.getProperty("line.separator")) .append(System.getProperty("line.separator")) .append("Stores information about each job.").append(System.getProperty("line.separator")) .append(System.getProperty("line.separator")) .append("For example configurations, visit http://dev.bukkit.org/server-mods/jobs/.").append(System.getProperty("line.separator")) .toString()); try { conf.load(f); } catch (Exception e) { plugin.getServer().getLogger().severe("==================== Jobs ===================="); plugin.getServer().getLogger().severe("Unable to load jobConfig.yml!"); plugin.getServer().getLogger().severe("Check your config for formatting issues!"); plugin.getServer().getLogger().severe("No jobs were loaded!"); plugin.getServer().getLogger().severe("Error: "+e.getMessage()); plugin.getServer().getLogger().severe("=============================================="); return; } ConfigurationSection jobsSection = conf.getConfigurationSection("Jobs"); if (jobsSection == null) { jobsSection = conf.createSection("Jobs"); } for (String jobKey : jobsSection.getKeys(false)) { ConfigurationSection jobSection = jobsSection.getConfigurationSection(jobKey); String jobName = jobSection.getString("fullname"); if (jobName == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid fullname property. Skipping job!"); continue; } Integer maxLevel = jobSection.getInt("max-level", 0); if (maxLevel.intValue() <= 0) { maxLevel = null; } Integer maxSlots = jobSection.getInt("slots", 0); if (maxSlots.intValue() <= 0) { maxSlots = null; } String jobShortName = jobSection.getString("shortname"); if (jobShortName == null) { plugin.getLogger().severe("Job " + jobKey + " is missing the shortname property. Skipping job!"); continue; } ChatColor jobColour; try { jobColour = ChatColor.valueOf(jobSection.getString("ChatColour", "").toUpperCase()); } catch (IllegalArgumentException e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid ChatColour property. Skipping job!"); continue; } String disp = jobSection.getString("chat-display", ""); DisplayMethod displayMethod; if (disp.equalsIgnoreCase("full")) { displayMethod = DisplayMethod.FULL; } else if(disp.equalsIgnoreCase("job")) { displayMethod = DisplayMethod.JOB; } else if(disp.equalsIgnoreCase("title")) { displayMethod = DisplayMethod.TITLE; } else if(disp.equalsIgnoreCase("none")) { displayMethod = DisplayMethod.NONE; } else if(disp.equalsIgnoreCase("shortfull")) { displayMethod = DisplayMethod.SHORT_FULL; } else if(disp.equalsIgnoreCase("shortjob")) { displayMethod = DisplayMethod.SHORT_JOB; } else if(disp.equalsIgnoreCase("shorttitle")) { displayMethod = DisplayMethod.SHORT_TITLE; } else { plugin.getLogger().warning("Job " + jobKey + " has an invalid chat-display property. Defaulting to None!"); displayMethod = DisplayMethod.NONE; } Parser maxExpEquation; String maxExpEquationInput = jobSection.getString("leveling-progression-equation"); try { maxExpEquation = new Parser(maxExpEquationInput); // test equation maxExpEquation.setVariable("numjobs", 1); maxExpEquation.setVariable("joblevel", 1); maxExpEquation.getValue(); } catch(Exception e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid leveling-progression-equation property. Skipping job!"); continue; } Parser incomeEquation; String incomeEquationInput = jobSection.getString("income-progression-equation"); try { incomeEquation = new Parser(incomeEquationInput); // test equation incomeEquation.setVariable("numjobs", 1); incomeEquation.setVariable("joblevel", 1); incomeEquation.setVariable("baseincome", 1); incomeEquation.getValue(); } catch(Exception e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid income-progression-equation property. Skipping job!"); continue; } Parser expEquation; String expEquationInput = jobSection.getString("experience-progression-equation"); try { expEquation = new Parser(expEquationInput); // test equation expEquation.setVariable("numjobs", 1); expEquation.setVariable("joblevel", 1); expEquation.setVariable("baseexperience", 1); expEquation.getValue(); } catch(Exception e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid experience-progression-equation property. Skipping job!"); continue; } // items // break ConfigurationSection breakSection = jobSection.getConfigurationSection("Break"); HashMap<String, JobsMaterialInfo> jobBreakInfo = new HashMap<String, JobsMaterialInfo>(); if (breakSection != null) { for (String breakKey : breakSection.getKeys(false)) { ConfigurationSection breakItem = breakSection.getConfigurationSection(breakKey); String materialType = breakKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if (material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + breakKey + " Break material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = breakItem.getDouble("income", 0.0); Double experience = breakItem.getDouble("experience", 0.0); jobBreakInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // place ConfigurationSection placeSection = jobSection.getConfigurationSection("Place"); HashMap<String, JobsMaterialInfo> jobPlaceInfo = new HashMap<String, JobsMaterialInfo>(); if (placeSection != null) { for (String placeKey : placeSection.getKeys(false)) { ConfigurationSection placeItem = placeSection.getConfigurationSection(placeKey); String materialType = placeKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + placeKey + " Place material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = placeItem.getDouble("income", 0.0); Double experience = placeItem.getDouble("experience", 0.0); jobPlaceInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // craft ConfigurationSection craftSection = jobSection.getConfigurationSection("Craft"); HashMap<String, JobsMaterialInfo> jobCraftInfo = new HashMap<String, JobsMaterialInfo>(); if (craftSection != null) { for (String craftKey : craftSection.getKeys(false)) { ConfigurationSection craftItem = craftSection.getConfigurationSection(craftKey); String materialType = craftKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + craftKey + " Craft material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = craftItem.getDouble("income", 0.0); Double experience = craftItem.getDouble("experience", 0.0); jobCraftInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // smelt ConfigurationSection smeltSection = jobSection.getConfigurationSection("Smelt"); HashMap<String, JobsMaterialInfo> jobSmeltInfo = new HashMap<String, JobsMaterialInfo>(); if (craftSection != null) { for (String smeltKey : smeltSection.getKeys(false)) { ConfigurationSection smeltItem = smeltSection.getConfigurationSection(smeltKey); String materialType = smeltKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + smeltKey + " Smelt material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = smeltItem.getDouble("income", 0.0); Double experience = smeltItem.getDouble("experience", 0.0); jobSmeltInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // kill ConfigurationSection killSection = jobSection.getConfigurationSection("Kill"); HashMap<String, JobsLivingEntityInfo> jobKillInfo = new HashMap<String, JobsLivingEntityInfo>(); if (killSection != null) { for (String killKey : killSection.getKeys(false)) { ConfigurationSection killItem = killSection.getConfigurationSection(killKey); Class<?> victim; try { victim = Class.forName("org.bukkit.craftbukkit.entity.Craft"+killKey); } catch (ClassNotFoundException e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + killKey + " Kill entity type property. Skipping!"); continue; } Double income = killItem.getDouble("income", 0.0); Double experience = killItem.getDouble("experience", 0.0); jobKillInfo.put(("org.bukkit.craftbukkit.entity.Craft"+killKey).trim(), new JobsLivingEntityInfo(victim, experience, income)); } } // fish ConfigurationSection fishSection = jobSection.getConfigurationSection("Fish"); HashMap<String, JobsMaterialInfo> jobFishInfo = new HashMap<String, JobsMaterialInfo>(); if (fishSection != null) { for (String fishKey : fishSection.getKeys(false)) { ConfigurationSection fishItem = fishSection.getConfigurationSection(fishKey); String materialType = fishKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + fishKey + " Fish material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = fishItem.getDouble("income", 0.0); Double experience = fishItem.getDouble("experience", 0.0); jobFishInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // custom-kill ConfigurationSection customKillSection = jobSection.getConfigurationSection("custom-kill"); if (customKillSection != null) { for (String customKillKey : customKillSection.getKeys(false)) { ConfigurationSection customKillItem = customKillSection.getConfigurationSection(customKillKey); String entityType = customKillKey.toString(); Double income = customKillItem.getDouble("income", 0.0); Double experience = customKillItem.getDouble("experience", 0.0); try { jobKillInfo.put(("org.bukkit.craftbukkit.entity.CraftPlayer:"+entityType).trim(), new JobsLivingEntityInfo(Class.forName("org.bukkit.craftbukkit.entity.CraftPlayer"), experience, income)); } catch (ClassNotFoundException e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + customKillKey + " custom-kill entity type property. Skipping!"); continue; } } } // Permissions ArrayList<JobPermission> jobPermissions = new ArrayList<JobPermission>(); ConfigurationSection permissionsSection = jobSection.getConfigurationSection("permissions"); if(permissionsSection != null) { for(String permissionKey : permissionsSection.getKeys(false)) { ConfigurationSection permissionSection = permissionsSection.getConfigurationSection(permissionKey); String node = permissionKey.toLowerCase(); if (permissionSection == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid permission key" + permissionKey + "!"); continue; } boolean value = permissionSection.getBoolean("value", true); int levelRequirement = permissionSection.getInt("level", 0); jobPermissions.add(new JobPermission(node, value, levelRequirement)); } } boolean isHidden = false; if (jobKey.equalsIgnoreCase("none")) { isHidden = true; } this.jobs.put(jobName.toLowerCase(), new Job(jobBreakInfo, jobPlaceInfo, jobKillInfo, jobFishInfo, jobCraftInfo, jobSmeltInfo, jobPermissions, jobName, jobShortName, jobColour, maxExpEquation, incomeEquation, expEquation, displayMethod, maxLevel, maxSlots, isHidden)); } try { conf.save(f); } catch (IOException e) { e.printStackTrace(); } }
private void loadJobSettings(){ File f = new File(plugin.getDataFolder(), "jobConfig.yml"); this.jobs.clear(); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { plugin.getLogger().severe("Unable to create jobConfig.yml! No jobs were loaded!"); return; } } YamlConfiguration conf = new YamlConfiguration(); conf.options().pathSeparator('/'); conf.options().header(new StringBuilder() .append("Jobs configuration.").append(System.getProperty("line.separator")) .append(System.getProperty("line.separator")) .append("Stores information about each job.").append(System.getProperty("line.separator")) .append(System.getProperty("line.separator")) .append("For example configurations, visit http://dev.bukkit.org/server-mods/jobs/.").append(System.getProperty("line.separator")) .toString()); try { conf.load(f); } catch (Exception e) { plugin.getServer().getLogger().severe("==================== Jobs ===================="); plugin.getServer().getLogger().severe("Unable to load jobConfig.yml!"); plugin.getServer().getLogger().severe("Check your config for formatting issues!"); plugin.getServer().getLogger().severe("No jobs were loaded!"); plugin.getServer().getLogger().severe("Error: "+e.getMessage()); plugin.getServer().getLogger().severe("=============================================="); return; } ConfigurationSection jobsSection = conf.getConfigurationSection("Jobs"); if (jobsSection == null) { jobsSection = conf.createSection("Jobs"); } for (String jobKey : jobsSection.getKeys(false)) { ConfigurationSection jobSection = jobsSection.getConfigurationSection(jobKey); String jobName = jobSection.getString("fullname"); if (jobName == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid fullname property. Skipping job!"); continue; } Integer maxLevel = jobSection.getInt("max-level", 0); if (maxLevel.intValue() <= 0) { maxLevel = null; } Integer maxSlots = jobSection.getInt("slots", 0); if (maxSlots.intValue() <= 0) { maxSlots = null; } String jobShortName = jobSection.getString("shortname"); if (jobShortName == null) { plugin.getLogger().severe("Job " + jobKey + " is missing the shortname property. Skipping job!"); continue; } ChatColor jobColour; try { jobColour = ChatColor.valueOf(jobSection.getString("ChatColour", "").toUpperCase()); } catch (IllegalArgumentException e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid ChatColour property. Skipping job!"); continue; } String disp = jobSection.getString("chat-display", ""); DisplayMethod displayMethod; if (disp.equalsIgnoreCase("full")) { displayMethod = DisplayMethod.FULL; } else if(disp.equalsIgnoreCase("job")) { displayMethod = DisplayMethod.JOB; } else if(disp.equalsIgnoreCase("title")) { displayMethod = DisplayMethod.TITLE; } else if(disp.equalsIgnoreCase("none")) { displayMethod = DisplayMethod.NONE; } else if(disp.equalsIgnoreCase("shortfull")) { displayMethod = DisplayMethod.SHORT_FULL; } else if(disp.equalsIgnoreCase("shortjob")) { displayMethod = DisplayMethod.SHORT_JOB; } else if(disp.equalsIgnoreCase("shorttitle")) { displayMethod = DisplayMethod.SHORT_TITLE; } else { plugin.getLogger().warning("Job " + jobKey + " has an invalid chat-display property. Defaulting to None!"); displayMethod = DisplayMethod.NONE; } Parser maxExpEquation; String maxExpEquationInput = jobSection.getString("leveling-progression-equation"); try { maxExpEquation = new Parser(maxExpEquationInput); // test equation maxExpEquation.setVariable("numjobs", 1); maxExpEquation.setVariable("joblevel", 1); maxExpEquation.getValue(); } catch(Exception e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid leveling-progression-equation property. Skipping job!"); continue; } Parser incomeEquation; String incomeEquationInput = jobSection.getString("income-progression-equation"); try { incomeEquation = new Parser(incomeEquationInput); // test equation incomeEquation.setVariable("numjobs", 1); incomeEquation.setVariable("joblevel", 1); incomeEquation.setVariable("baseincome", 1); incomeEquation.getValue(); } catch(Exception e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid income-progression-equation property. Skipping job!"); continue; } Parser expEquation; String expEquationInput = jobSection.getString("experience-progression-equation"); try { expEquation = new Parser(expEquationInput); // test equation expEquation.setVariable("numjobs", 1); expEquation.setVariable("joblevel", 1); expEquation.setVariable("baseexperience", 1); expEquation.getValue(); } catch(Exception e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid experience-progression-equation property. Skipping job!"); continue; } // items // break ConfigurationSection breakSection = jobSection.getConfigurationSection("Break"); HashMap<String, JobsMaterialInfo> jobBreakInfo = new HashMap<String, JobsMaterialInfo>(); if (breakSection != null) { for (String breakKey : breakSection.getKeys(false)) { ConfigurationSection breakItem = breakSection.getConfigurationSection(breakKey); String materialType = breakKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if (material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + breakKey + " Break material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = breakItem.getDouble("income", 0.0); Double experience = breakItem.getDouble("experience", 0.0); jobBreakInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // place ConfigurationSection placeSection = jobSection.getConfigurationSection("Place"); HashMap<String, JobsMaterialInfo> jobPlaceInfo = new HashMap<String, JobsMaterialInfo>(); if (placeSection != null) { for (String placeKey : placeSection.getKeys(false)) { ConfigurationSection placeItem = placeSection.getConfigurationSection(placeKey); String materialType = placeKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + placeKey + " Place material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = placeItem.getDouble("income", 0.0); Double experience = placeItem.getDouble("experience", 0.0); jobPlaceInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // craft ConfigurationSection craftSection = jobSection.getConfigurationSection("Craft"); HashMap<String, JobsMaterialInfo> jobCraftInfo = new HashMap<String, JobsMaterialInfo>(); if (craftSection != null) { for (String craftKey : craftSection.getKeys(false)) { ConfigurationSection craftItem = craftSection.getConfigurationSection(craftKey); String materialType = craftKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + craftKey + " Craft material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = craftItem.getDouble("income", 0.0); Double experience = craftItem.getDouble("experience", 0.0); jobCraftInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // smelt ConfigurationSection smeltSection = jobSection.getConfigurationSection("Smelt"); HashMap<String, JobsMaterialInfo> jobSmeltInfo = new HashMap<String, JobsMaterialInfo>(); if (smeltSection != null) { for (String smeltKey : smeltSection.getKeys(false)) { ConfigurationSection smeltItem = smeltSection.getConfigurationSection(smeltKey); String materialType = smeltKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + smeltKey + " Smelt material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = smeltItem.getDouble("income", 0.0); Double experience = smeltItem.getDouble("experience", 0.0); jobSmeltInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // kill ConfigurationSection killSection = jobSection.getConfigurationSection("Kill"); HashMap<String, JobsLivingEntityInfo> jobKillInfo = new HashMap<String, JobsLivingEntityInfo>(); if (killSection != null) { for (String killKey : killSection.getKeys(false)) { ConfigurationSection killItem = killSection.getConfigurationSection(killKey); Class<?> victim; try { victim = Class.forName("org.bukkit.craftbukkit.entity.Craft"+killKey); } catch (ClassNotFoundException e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + killKey + " Kill entity type property. Skipping!"); continue; } Double income = killItem.getDouble("income", 0.0); Double experience = killItem.getDouble("experience", 0.0); jobKillInfo.put(("org.bukkit.craftbukkit.entity.Craft"+killKey).trim(), new JobsLivingEntityInfo(victim, experience, income)); } } // fish ConfigurationSection fishSection = jobSection.getConfigurationSection("Fish"); HashMap<String, JobsMaterialInfo> jobFishInfo = new HashMap<String, JobsMaterialInfo>(); if (fishSection != null) { for (String fishKey : fishSection.getKeys(false)) { ConfigurationSection fishItem = fishSection.getConfigurationSection(fishKey); String materialType = fishKey.toUpperCase(); String subType = ""; if (materialType.contains("-")) { // uses subType subType = ":" + materialType.split("-")[1]; materialType = materialType.split("-")[0]; } Material material = Material.matchMaterial(materialType); if (material == null) { // try integer method Integer matId = null; try { matId = Integer.decode(materialType); } catch (NumberFormatException e) {} if (matId != null) { material = Material.getMaterial(matId); } } if(material == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + fishKey + " Fish material type property. Skipping!"); continue; } MaterialData materialData = new MaterialData(material); Double income = fishItem.getDouble("income", 0.0); Double experience = fishItem.getDouble("experience", 0.0); jobFishInfo.put(material.toString()+subType, new JobsMaterialInfo(materialData, experience, income)); } } // custom-kill ConfigurationSection customKillSection = jobSection.getConfigurationSection("custom-kill"); if (customKillSection != null) { for (String customKillKey : customKillSection.getKeys(false)) { ConfigurationSection customKillItem = customKillSection.getConfigurationSection(customKillKey); String entityType = customKillKey.toString(); Double income = customKillItem.getDouble("income", 0.0); Double experience = customKillItem.getDouble("experience", 0.0); try { jobKillInfo.put(("org.bukkit.craftbukkit.entity.CraftPlayer:"+entityType).trim(), new JobsLivingEntityInfo(Class.forName("org.bukkit.craftbukkit.entity.CraftPlayer"), experience, income)); } catch (ClassNotFoundException e) { plugin.getLogger().severe("Job " + jobKey + " has an invalid " + customKillKey + " custom-kill entity type property. Skipping!"); continue; } } } // Permissions ArrayList<JobPermission> jobPermissions = new ArrayList<JobPermission>(); ConfigurationSection permissionsSection = jobSection.getConfigurationSection("permissions"); if(permissionsSection != null) { for(String permissionKey : permissionsSection.getKeys(false)) { ConfigurationSection permissionSection = permissionsSection.getConfigurationSection(permissionKey); String node = permissionKey.toLowerCase(); if (permissionSection == null) { plugin.getLogger().severe("Job " + jobKey + " has an invalid permission key" + permissionKey + "!"); continue; } boolean value = permissionSection.getBoolean("value", true); int levelRequirement = permissionSection.getInt("level", 0); jobPermissions.add(new JobPermission(node, value, levelRequirement)); } } boolean isHidden = false; if (jobKey.equalsIgnoreCase("none")) { isHidden = true; } this.jobs.put(jobName.toLowerCase(), new Job(jobBreakInfo, jobPlaceInfo, jobKillInfo, jobFishInfo, jobCraftInfo, jobSmeltInfo, jobPermissions, jobName, jobShortName, jobColour, maxExpEquation, incomeEquation, expEquation, displayMethod, maxLevel, maxSlots, isHidden)); } try { conf.save(f); } catch (IOException e) { e.printStackTrace(); } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/RepositoryTaskDecorator.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/RepositoryTaskDecorator.java index dda80558b..7e0780dc2 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/RepositoryTaskDecorator.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/RepositoryTaskDecorator.java @@ -1,107 +1,107 @@ /******************************************************************************* * 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.tasks.ui; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ILightweightLabelDecorator; import org.eclipse.mylar.context.core.MylarStatusHandler; import org.eclipse.mylar.tasks.core.AbstractQueryHit; import org.eclipse.mylar.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylar.tasks.core.AbstractRepositoryQuery; import org.eclipse.mylar.tasks.core.AbstractRepositoryTask; import org.eclipse.mylar.tasks.core.ITask; import org.eclipse.mylar.tasks.core.TaskRepository; import org.eclipse.mylar.tasks.ui.AbstractRepositoryConnectorUi; import org.eclipse.mylar.tasks.ui.TasksUiPlugin; /** * @author Mik Kersten */ public class RepositoryTaskDecorator implements ILightweightLabelDecorator { public void decorate(Object element, IDecoration decoration) { if (element instanceof AbstractRepositoryQuery) { AbstractRepositoryQuery query = (AbstractRepositoryQuery) element; String repositoryUrl = query.getRepositoryUrl(); if (repositoryUrl != null) { try { URL url = new URL(repositoryUrl); decoration.addSuffix(" [" + url.getHost() + "]"); } catch (MalformedURLException e) { decoration.addSuffix(" [ <unknown host> ]"); } } if (query.isSynchronizing()) { decoration.addOverlay(TaskListImages.OVERLAY_SYNCHRONIZING, IDecoration.TOP_LEFT); } } else if (element instanceof AbstractRepositoryTask) { AbstractRepositoryTask task = (AbstractRepositoryTask) element; AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( task.getRepositoryKind()); AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getRepositoryUi(task.getRepositoryKind()); TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(task.getRepositoryKind(), task.getRepositoryUrl()); if (connectorUi != null) { if (!connectorUi.hasRichEditor()) { decoration.addOverlay(TaskListImages.OVERLAY_WEB, IDecoration.BOTTOM_LEFT); } else if (connector != null && connector.hasRepositoryContext(repository, task)) { - decoration.addOverlay(TaskListImages.OVERLAY_REPOSITORY_CONTEXT, IDecoration.TOP_LEFT); + decoration.addOverlay(TaskListImages.OVERLAY_REPOSITORY_CONTEXT, IDecoration.BOTTOM_LEFT); } else { decoration.addOverlay(TaskListImages.OVERLAY_REPOSITORY, IDecoration.BOTTOM_LEFT); } } else { MylarStatusHandler.log("Could not get icon overlay, connector UI not yet started.", this); } if (task.isSynchronizing()) { decoration.addOverlay(TaskListImages.OVERLAY_SYNCHRONIZING, IDecoration.TOP_LEFT); } } else if (element instanceof AbstractQueryHit) { ITask correspondingTask = ((AbstractQueryHit) element).getCorrespondingTask(); decorate(correspondingTask, decoration); } else if (element instanceof ITask) { String url = ((ITask) element).getUrl(); if (url != null && !url.trim().equals("") && !url.equals("http://")) { decoration.addOverlay(TaskListImages.OVERLAY_WEB, IDecoration.BOTTOM_LEFT); } } else if (element instanceof TaskRepository) { ImageDescriptor overlay = TasksUiPlugin.getDefault().getOverlayIcon(((TaskRepository) element).getKind()); if (overlay != null) { decoration.addOverlay(overlay, IDecoration.BOTTOM_RIGHT); } } } public void addListener(ILabelProviderListener listener) { // ignore } public void dispose() { // ignore } public boolean isLabelProperty(Object element, String property) { return false; } public void removeListener(ILabelProviderListener listener) { // ignore } }
true
true
public void decorate(Object element, IDecoration decoration) { if (element instanceof AbstractRepositoryQuery) { AbstractRepositoryQuery query = (AbstractRepositoryQuery) element; String repositoryUrl = query.getRepositoryUrl(); if (repositoryUrl != null) { try { URL url = new URL(repositoryUrl); decoration.addSuffix(" [" + url.getHost() + "]"); } catch (MalformedURLException e) { decoration.addSuffix(" [ <unknown host> ]"); } } if (query.isSynchronizing()) { decoration.addOverlay(TaskListImages.OVERLAY_SYNCHRONIZING, IDecoration.TOP_LEFT); } } else if (element instanceof AbstractRepositoryTask) { AbstractRepositoryTask task = (AbstractRepositoryTask) element; AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( task.getRepositoryKind()); AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getRepositoryUi(task.getRepositoryKind()); TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(task.getRepositoryKind(), task.getRepositoryUrl()); if (connectorUi != null) { if (!connectorUi.hasRichEditor()) { decoration.addOverlay(TaskListImages.OVERLAY_WEB, IDecoration.BOTTOM_LEFT); } else if (connector != null && connector.hasRepositoryContext(repository, task)) { decoration.addOverlay(TaskListImages.OVERLAY_REPOSITORY_CONTEXT, IDecoration.TOP_LEFT); } else { decoration.addOverlay(TaskListImages.OVERLAY_REPOSITORY, IDecoration.BOTTOM_LEFT); } } else { MylarStatusHandler.log("Could not get icon overlay, connector UI not yet started.", this); } if (task.isSynchronizing()) { decoration.addOverlay(TaskListImages.OVERLAY_SYNCHRONIZING, IDecoration.TOP_LEFT); } } else if (element instanceof AbstractQueryHit) { ITask correspondingTask = ((AbstractQueryHit) element).getCorrespondingTask(); decorate(correspondingTask, decoration); } else if (element instanceof ITask) { String url = ((ITask) element).getUrl(); if (url != null && !url.trim().equals("") && !url.equals("http://")) { decoration.addOverlay(TaskListImages.OVERLAY_WEB, IDecoration.BOTTOM_LEFT); } } else if (element instanceof TaskRepository) { ImageDescriptor overlay = TasksUiPlugin.getDefault().getOverlayIcon(((TaskRepository) element).getKind()); if (overlay != null) { decoration.addOverlay(overlay, IDecoration.BOTTOM_RIGHT); } } }
public void decorate(Object element, IDecoration decoration) { if (element instanceof AbstractRepositoryQuery) { AbstractRepositoryQuery query = (AbstractRepositoryQuery) element; String repositoryUrl = query.getRepositoryUrl(); if (repositoryUrl != null) { try { URL url = new URL(repositoryUrl); decoration.addSuffix(" [" + url.getHost() + "]"); } catch (MalformedURLException e) { decoration.addSuffix(" [ <unknown host> ]"); } } if (query.isSynchronizing()) { decoration.addOverlay(TaskListImages.OVERLAY_SYNCHRONIZING, IDecoration.TOP_LEFT); } } else if (element instanceof AbstractRepositoryTask) { AbstractRepositoryTask task = (AbstractRepositoryTask) element; AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( task.getRepositoryKind()); AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getRepositoryUi(task.getRepositoryKind()); TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(task.getRepositoryKind(), task.getRepositoryUrl()); if (connectorUi != null) { if (!connectorUi.hasRichEditor()) { decoration.addOverlay(TaskListImages.OVERLAY_WEB, IDecoration.BOTTOM_LEFT); } else if (connector != null && connector.hasRepositoryContext(repository, task)) { decoration.addOverlay(TaskListImages.OVERLAY_REPOSITORY_CONTEXT, IDecoration.BOTTOM_LEFT); } else { decoration.addOverlay(TaskListImages.OVERLAY_REPOSITORY, IDecoration.BOTTOM_LEFT); } } else { MylarStatusHandler.log("Could not get icon overlay, connector UI not yet started.", this); } if (task.isSynchronizing()) { decoration.addOverlay(TaskListImages.OVERLAY_SYNCHRONIZING, IDecoration.TOP_LEFT); } } else if (element instanceof AbstractQueryHit) { ITask correspondingTask = ((AbstractQueryHit) element).getCorrespondingTask(); decorate(correspondingTask, decoration); } else if (element instanceof ITask) { String url = ((ITask) element).getUrl(); if (url != null && !url.trim().equals("") && !url.equals("http://")) { decoration.addOverlay(TaskListImages.OVERLAY_WEB, IDecoration.BOTTOM_LEFT); } } else if (element instanceof TaskRepository) { ImageDescriptor overlay = TasksUiPlugin.getDefault().getOverlayIcon(((TaskRepository) element).getKind()); if (overlay != null) { decoration.addOverlay(overlay, IDecoration.BOTTOM_RIGHT); } } }
diff --git a/atlas-data-storage/src/test/java/uk/ac/ebi/gxa/data/StatisticsGenerators.java b/atlas-data-storage/src/test/java/uk/ac/ebi/gxa/data/StatisticsGenerators.java index 977d2d417..d5cd0ccf2 100644 --- a/atlas-data-storage/src/test/java/uk/ac/ebi/gxa/data/StatisticsGenerators.java +++ b/atlas-data-storage/src/test/java/uk/ac/ebi/gxa/data/StatisticsGenerators.java @@ -1,73 +1,73 @@ /* * Copyright 2008-2011 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * 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. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.data; import net.java.quickcheck.Generator; import net.java.quickcheck.generator.PrimitiveGenerators; import static java.util.Arrays.asList; import static net.java.quickcheck.generator.CombinedGenerators.*; import static net.java.quickcheck.generator.PrimitiveGenerators.doubles; /** * @author alf */ public class StatisticsGenerators { public static Generator<Double> validPValues() { return ensureValues(asList(0.0, 0.5, 1.0), doubles(0.0, 1.0)); } public static Generator<Double> validTStats() { return ensureValues( asList(0.0, 0.5, 1.0, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY), doubles(Float.MIN_VALUE, Float.MAX_VALUE)); } public static Generator<Double> invalidPValues() { return ensureValues(asList(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN), oneOf(excludeValues(doubles(-Float.MAX_VALUE, -0.0), +0.0, -0.0)) .add(excludeValues(doubles(1.0, Float.MAX_VALUE), 1.0))); } public static Generator<Double> invalidTStats() { return ensureValues(Double.NaN); } public static Generator<DesignElementStatistics> deCandidates() { final Generator<Double> p = validPValues(); final Generator<Double> t = validTStats(); final Generator<Integer> de = PrimitiveGenerators.integers(); final Generator<Integer> uefv = PrimitiveGenerators.integers(); return new Generator<DesignElementStatistics>() { @Override public DesignElementStatistics next() { return new DesignElementStatistics( p.next().floatValue(), t.next().floatValue(), - de.next(), uefv.next(), getUniqueEFVs(arrayDesign).get(efvIndex)); + de.next(), uefv.next(), null); } }; } }
true
true
public static Generator<DesignElementStatistics> deCandidates() { final Generator<Double> p = validPValues(); final Generator<Double> t = validTStats(); final Generator<Integer> de = PrimitiveGenerators.integers(); final Generator<Integer> uefv = PrimitiveGenerators.integers(); return new Generator<DesignElementStatistics>() { @Override public DesignElementStatistics next() { return new DesignElementStatistics( p.next().floatValue(), t.next().floatValue(), de.next(), uefv.next(), getUniqueEFVs(arrayDesign).get(efvIndex)); } }; }
public static Generator<DesignElementStatistics> deCandidates() { final Generator<Double> p = validPValues(); final Generator<Double> t = validTStats(); final Generator<Integer> de = PrimitiveGenerators.integers(); final Generator<Integer> uefv = PrimitiveGenerators.integers(); return new Generator<DesignElementStatistics>() { @Override public DesignElementStatistics next() { return new DesignElementStatistics( p.next().floatValue(), t.next().floatValue(), de.next(), uefv.next(), null); } }; }
diff --git a/src/Main/java.java b/src/Main/java.java index 3492b49..9a59e24 100644 --- a/src/Main/java.java +++ b/src/Main/java.java @@ -1,19 +1,19 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Main; /** * * @author arjan */ public class java { /** * @param args the command line arguments */ public static void main(String[] args) { - // hallo arjan + // hallo joshua } }
true
true
public static void main(String[] args) { // hallo arjan }
public static void main(String[] args) { // hallo joshua }
diff --git a/ghana-national-core/src/main/java/org/motechproject/ghana/national/repository/AllPatients.java b/ghana-national-core/src/main/java/org/motechproject/ghana/national/repository/AllPatients.java index d63de264..24dd9d12 100644 --- a/ghana-national-core/src/main/java/org/motechproject/ghana/national/repository/AllPatients.java +++ b/ghana-national-core/src/main/java/org/motechproject/ghana/national/repository/AllPatients.java @@ -1,189 +1,190 @@ package org.motechproject.ghana.national.repository; import ch.lambdaj.function.convert.Converter; import org.apache.commons.lang.StringUtils; import org.motechproject.ghana.national.domain.Patient; import org.motechproject.ghana.national.exception.ParentNotFoundException; import org.motechproject.mrs.exception.PatientNotFoundException; import org.motechproject.mrs.model.MRSPatient; import org.motechproject.mrs.model.MRSPerson; import org.motechproject.mrs.services.MRSPatientAdapter; import org.motechproject.openmrs.services.OpenMRSRelationshipAdapter; import org.openmrs.Person; import org.openmrs.Relationship; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import static ch.lambdaj.Lambda.*; import static org.hamcrest.Matchers.containsString; @Repository public class AllPatients { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private MRSPatientAdapter patientAdapter; @Autowired private OpenMRSRelationshipAdapter openMRSRelationshipAdapter; @Autowired DataSource dataSource; public Patient save(Patient patient) throws ParentNotFoundException { MRSPatient mrsPatient = patientAdapter.savePatient(patient.getMrsPatient()); if (StringUtils.isNotEmpty(patient.getParentId())) { Patient mother = getPatientByMotechId(patient.getParentId()); if (mother == null) throw new ParentNotFoundException(); createMotherChildRelationship(mother.getMrsPatient().getPerson(), mrsPatient.getPerson()); } return new Patient(mrsPatient, patient.getParentId()); } public Patient patientByOpenmrsId(String patientId) { MRSPatient mrsPatient = patientAdapter.getPatient(patientId); return (mrsPatient != null) ? new Patient(mrsPatient) : null; } public Patient getPatientByMotechId(String id) { MRSPatient mrsPatient = patientAdapter.getPatientByMotechId(id); if (mrsPatient != null) { Patient patient = new Patient(mrsPatient); Relationship motherRelationship = getMotherRelationship(patient.getMrsPatient().getPerson()); if (motherRelationship != null) { setParentId(patient, motherRelationship); } return patient; } return null; } private void setParentId(Patient patient, Relationship motherRelationship) { Person mother = motherRelationship.getPersonA(); if (mother != null && !mother.getNames().isEmpty()) { List<Patient> patients = search(mother.getNames().iterator().next().getFullName(), null, null); if (patients != null && !patients.isEmpty()) { patient.parentId(getParentId(mother, patients)); } } } private String getParentId(Person mother, List<Patient> patients) { for (Patient patient : patients) { if (patient.getMrsPatient().getPerson().getId().equals(mother.getId().toString())) { return patient.getMrsPatient().getMotechId(); } } return null; } public List<Patient> search(String name, String motechId, String phoneNumber) { List<Patient> patients = convert(patientAdapter.search(name, motechId), new Converter<MRSPatient, Patient>() { @Override public Patient convert(MRSPatient mrsPatient) { return new Patient(mrsPatient); } }); if (StringUtils.isBlank(phoneNumber)) { return patients; } if (StringUtils.isBlank(name) && StringUtils.isBlank(motechId)) { return getPatientsByPhoneNumber(phoneNumber); } return filter(having(on(Patient.class).getPhoneNumber(), containsString(phoneNumber)), patients); } public Integer getAgeOfPersonByMotechId(String motechId) { return patientAdapter.getAgeOfPatientByMotechId(motechId); } public Patient update(Patient patient) { return new Patient(patientAdapter.updatePatient(patient.getMrsPatient())); } public void createMotherChildRelationship(MRSPerson mother, MRSPerson child) { openMRSRelationshipAdapter.createMotherChildRelationship(mother.getId(), child.getId()); } public Relationship getMotherRelationship(MRSPerson person) { return openMRSRelationshipAdapter.getMotherRelationship(person.getId()); } public Relationship updateMotherChildRelationship(MRSPerson mother, MRSPerson child) { return openMRSRelationshipAdapter.updateMotherRelationship(mother.getId(), child.getId()); } public Relationship voidMotherChildRelationship(MRSPerson child) { return openMRSRelationshipAdapter.voidRelationship(child.getId()); } public Patient getMother(String motechId) { Patient patient = getPatientByMotechId(motechId); Relationship motherRelationship = getMotherRelationship(patient.getMrsPatient().getPerson()); if (motherRelationship != null) { return patientByOpenmrsId(motherRelationship.getPersonA().getPersonId().toString()); } return null; } public void deceasePatient(Date dateOfDeath, String patientMotechId, String causeOfDeath, String comment) { try { patientAdapter.deceasePatient(patientMotechId, causeOfDeath, dateOfDeath, comment); } catch (PatientNotFoundException e) { logger.warn(e.getMessage()); } } private List<Patient> getPatientsByPhoneNumber(String phoneNumber) { Connection connection = null; ArrayList<Patient> patients = new ArrayList<Patient>(); try { connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement("select pi.identifier from patient p, person_attribute pa,patient_identifier pi " + "where pa.person_attribute_type_id = 8 " + "and pa.value like ? " + + "and p.voided = 0 " + "and pi.patient_id = p.patient_id " + "and pa.person_id = p.patient_id"); statement.setString(1, "%" + phoneNumber + "%"); ResultSet resultSet = statement.executeQuery(); ArrayList<String> motechIds = new ArrayList<String>(); while (resultSet.next()) { motechIds.add(resultSet.getString(1)); } if (!motechIds.isEmpty()) { for (String motechId : motechIds) { patients.add(getPatientByMotechId(motechId)); } } } catch (SQLException e) { logger.error("Exception in retrieving patients with phone numbers." + phoneNumber, e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { logger.error("Exception in closing the connection.", e); } } } return patients; } }
true
true
private List<Patient> getPatientsByPhoneNumber(String phoneNumber) { Connection connection = null; ArrayList<Patient> patients = new ArrayList<Patient>(); try { connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement("select pi.identifier from patient p, person_attribute pa,patient_identifier pi " + "where pa.person_attribute_type_id = 8 " + "and pa.value like ? " + "and pi.patient_id = p.patient_id " + "and pa.person_id = p.patient_id"); statement.setString(1, "%" + phoneNumber + "%"); ResultSet resultSet = statement.executeQuery(); ArrayList<String> motechIds = new ArrayList<String>(); while (resultSet.next()) { motechIds.add(resultSet.getString(1)); } if (!motechIds.isEmpty()) { for (String motechId : motechIds) { patients.add(getPatientByMotechId(motechId)); } } } catch (SQLException e) { logger.error("Exception in retrieving patients with phone numbers." + phoneNumber, e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { logger.error("Exception in closing the connection.", e); } } } return patients; }
private List<Patient> getPatientsByPhoneNumber(String phoneNumber) { Connection connection = null; ArrayList<Patient> patients = new ArrayList<Patient>(); try { connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement("select pi.identifier from patient p, person_attribute pa,patient_identifier pi " + "where pa.person_attribute_type_id = 8 " + "and pa.value like ? " + "and p.voided = 0 " + "and pi.patient_id = p.patient_id " + "and pa.person_id = p.patient_id"); statement.setString(1, "%" + phoneNumber + "%"); ResultSet resultSet = statement.executeQuery(); ArrayList<String> motechIds = new ArrayList<String>(); while (resultSet.next()) { motechIds.add(resultSet.getString(1)); } if (!motechIds.isEmpty()) { for (String motechId : motechIds) { patients.add(getPatientByMotechId(motechId)); } } } catch (SQLException e) { logger.error("Exception in retrieving patients with phone numbers." + phoneNumber, e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { logger.error("Exception in closing the connection.", e); } } } return patients; }
diff --git a/modules/com.noelios.restlet.ext.httpclient_3.1/src/com/noelios/restlet/ext/httpclient/HttpMethodCall.java b/modules/com.noelios.restlet.ext.httpclient_3.1/src/com/noelios/restlet/ext/httpclient/HttpMethodCall.java index 8483c104d..f30766ad8 100644 --- a/modules/com.noelios.restlet.ext.httpclient_3.1/src/com/noelios/restlet/ext/httpclient/HttpMethodCall.java +++ b/modules/com.noelios.restlet.ext.httpclient_3.1/src/com/noelios/restlet/ext/httpclient/HttpMethodCall.java @@ -1,286 +1,286 @@ /* * Copyright 2005-2007 Noelios Consulting. * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). You may not use this file except in * compliance with the License. * * You can obtain a copy of the license at * http://www.opensource.org/licenses/cddl1.txt See the License for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at http://www.opensource.org/licenses/cddl1.txt If * applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] */ package com.noelios.restlet.ext.httpclient; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import org.apache.commons.httpclient.ConnectMethod; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.URIException; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.EntityEnclosingMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.methods.OptionsMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.TraceMethod; import org.restlet.data.Method; import org.restlet.data.Parameter; import org.restlet.data.Protocol; import org.restlet.data.Request; import org.restlet.data.Status; import org.restlet.resource.Representation; import org.restlet.util.Series; import com.noelios.restlet.http.HttpClientCall; /** * HTTP client connector call based on Apache HTTP Client's HttpMethod class. * * @author Jerome Louvel ([email protected]) */ public class HttpMethodCall extends HttpClientCall { /** The associated HTTP client. */ private HttpClientHelper clientHelper; /** The wrapped HTTP method. */ private HttpMethod httpMethod; /** Indicates if the response headers were added. */ private boolean responseHeadersAdded; /** * Constructor. * * @param helper * The parent HTTP client helper. * @param method * The method name. * @param requestUri * The request URI. * @param hasEntity * Indicates if the call will have an entity to send to the * server. * @throws IOException */ public HttpMethodCall(HttpClientHelper helper, final String method, String requestUri, boolean hasEntity) throws IOException { super(helper, method, requestUri); this.clientHelper = helper; if (requestUri.startsWith("http")) { if (method.equalsIgnoreCase(Method.GET.getName())) { this.httpMethod = new GetMethod(requestUri); } else if (method.equalsIgnoreCase(Method.POST.getName())) { this.httpMethod = new PostMethod(requestUri); } else if (method.equalsIgnoreCase(Method.PUT.getName())) { this.httpMethod = new PutMethod(requestUri); } else if (method.equalsIgnoreCase(Method.HEAD.getName())) { this.httpMethod = new HeadMethod(requestUri); } else if (method.equalsIgnoreCase(Method.DELETE.getName())) { this.httpMethod = new DeleteMethod(requestUri); } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) { HostConfiguration host = new HostConfiguration(); host.setHost(new URI(requestUri, false)); this.httpMethod = new ConnectMethod(host); } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) { this.httpMethod = new OptionsMethod(requestUri); } else if (method.equalsIgnoreCase(Method.TRACE.getName())) { this.httpMethod = new TraceMethod(requestUri); } else { this.httpMethod = new EntityEnclosingMethod(requestUri) { public String getName() { return method; } }; } this.httpMethod.setFollowRedirects(this.clientHelper .isFollowRedirects()); this.httpMethod.setDoAuthentication(false); this.responseHeadersAdded = false; setConfidential(this.httpMethod.getURI().getScheme() .equalsIgnoreCase(Protocol.HTTPS.getSchemeName())); } else { throw new IllegalArgumentException( "Only HTTP or HTTPS resource URIs are allowed here"); } } /** * Returns the HTTP method. * * @return The HTTP method. */ public HttpMethod getHttpMethod() { return this.httpMethod; } /** * Sends the request to the client. Commits the request line, headers and * optional entity and send them over the network. * * @param request * The high-level request. * @return The result status. */ @Override public Status sendRequest(Request request) { Status result = null; try { final Representation entity = request.getEntity(); // Set the request headers for (Parameter header : getRequestHeaders()) { getHttpMethod().setRequestHeader(header.getName(), header.getValue()); } // For those method that accept enclosing entites, provide it if ((entity != null) && (getHttpMethod() instanceof EntityEnclosingMethod)) { EntityEnclosingMethod eem = (EntityEnclosingMethod) getHttpMethod(); eem.setRequestEntity(new RequestEntity() { public long getContentLength() { return entity.getSize(); } public String getContentType() { return (entity.getMediaType() != null) ? entity .getMediaType().toString() : null; } public boolean isRepeatable() { return !entity.isTransient(); } public void writeRequest(OutputStream os) throws IOException { entity.write(os); } }); } - // Ensure that the connections is active + // Ensure that the connection is active this.clientHelper.getHttpClient().executeMethod(getHttpMethod()); // Now we can access the status code, this MUST happen after closing // any open request stream. result = new Status(getStatusCode(), null, getReasonPhrase(), null); // If there is not response body, immediatly release the connection if (getHttpMethod().getResponseBodyAsStream() == null) { getHttpMethod().releaseConnection(); } } catch (IOException ioe) { this.clientHelper .getLogger() .log( Level.WARNING, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status( Status.CONNECTOR_ERROR_COMMUNICATION, "Unable to complete the HTTP call due to a communication error with the remote server. " + ioe.getMessage()); // Release the connection getHttpMethod().releaseConnection(); } return result; } /** * Returns the response address.<br/> Corresponds to the IP address of the * responding server. * * @return The response address. */ public String getServerAddress() { try { return getHttpMethod().getURI().getHost(); } catch (URIException e) { return null; } } /** * Returns the modifiable list of response headers. * * @return The modifiable list of response headers. */ public Series<Parameter> getResponseHeaders() { Series<Parameter> result = super.getResponseHeaders(); if (!this.responseHeadersAdded) { for (Header header : getHttpMethod().getResponseHeaders()) { result.add(header.getName(), header.getValue()); } this.responseHeadersAdded = true; } return result; } /** * Returns the response status code. * * @return The response status code. */ public int getStatusCode() { return getHttpMethod().getStatusCode(); } /** * Returns the response reason phrase. * * @return The response reason phrase. */ public String getReasonPhrase() { return getHttpMethod().getStatusText(); } /** * Returns the response stream if it exists. * * @return The response stream if it exists. */ public InputStream getResponseStream() { InputStream result = null; try { // Return a wrapper filter that will release the connection when // needed result = new FilterInputStream(getHttpMethod() .getResponseBodyAsStream()) { public void close() throws IOException { super.close(); getHttpMethod().releaseConnection(); } }; } catch (IOException ioe) { result = null; } return result; } }
true
true
public Status sendRequest(Request request) { Status result = null; try { final Representation entity = request.getEntity(); // Set the request headers for (Parameter header : getRequestHeaders()) { getHttpMethod().setRequestHeader(header.getName(), header.getValue()); } // For those method that accept enclosing entites, provide it if ((entity != null) && (getHttpMethod() instanceof EntityEnclosingMethod)) { EntityEnclosingMethod eem = (EntityEnclosingMethod) getHttpMethod(); eem.setRequestEntity(new RequestEntity() { public long getContentLength() { return entity.getSize(); } public String getContentType() { return (entity.getMediaType() != null) ? entity .getMediaType().toString() : null; } public boolean isRepeatable() { return !entity.isTransient(); } public void writeRequest(OutputStream os) throws IOException { entity.write(os); } }); } // Ensure that the connections is active this.clientHelper.getHttpClient().executeMethod(getHttpMethod()); // Now we can access the status code, this MUST happen after closing // any open request stream. result = new Status(getStatusCode(), null, getReasonPhrase(), null); // If there is not response body, immediatly release the connection if (getHttpMethod().getResponseBodyAsStream() == null) { getHttpMethod().releaseConnection(); } } catch (IOException ioe) { this.clientHelper .getLogger() .log( Level.WARNING, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status( Status.CONNECTOR_ERROR_COMMUNICATION, "Unable to complete the HTTP call due to a communication error with the remote server. " + ioe.getMessage()); // Release the connection getHttpMethod().releaseConnection(); } return result; }
public Status sendRequest(Request request) { Status result = null; try { final Representation entity = request.getEntity(); // Set the request headers for (Parameter header : getRequestHeaders()) { getHttpMethod().setRequestHeader(header.getName(), header.getValue()); } // For those method that accept enclosing entites, provide it if ((entity != null) && (getHttpMethod() instanceof EntityEnclosingMethod)) { EntityEnclosingMethod eem = (EntityEnclosingMethod) getHttpMethod(); eem.setRequestEntity(new RequestEntity() { public long getContentLength() { return entity.getSize(); } public String getContentType() { return (entity.getMediaType() != null) ? entity .getMediaType().toString() : null; } public boolean isRepeatable() { return !entity.isTransient(); } public void writeRequest(OutputStream os) throws IOException { entity.write(os); } }); } // Ensure that the connection is active this.clientHelper.getHttpClient().executeMethod(getHttpMethod()); // Now we can access the status code, this MUST happen after closing // any open request stream. result = new Status(getStatusCode(), null, getReasonPhrase(), null); // If there is not response body, immediatly release the connection if (getHttpMethod().getResponseBodyAsStream() == null) { getHttpMethod().releaseConnection(); } } catch (IOException ioe) { this.clientHelper .getLogger() .log( Level.WARNING, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status( Status.CONNECTOR_ERROR_COMMUNICATION, "Unable to complete the HTTP call due to a communication error with the remote server. " + ioe.getMessage()); // Release the connection getHttpMethod().releaseConnection(); } return result; }
diff --git a/src/xhl/core/Reader.java b/src/xhl/core/Reader.java index 6d111b7..96dbd91 100644 --- a/src/xhl/core/Reader.java +++ b/src/xhl/core/Reader.java @@ -1,181 +1,181 @@ package xhl.core; import static xhl.core.Token.TokenType.*; import java.io.IOException; import java.io.StringReader; import java.util.*; import xhl.core.Token.TokenType; import xhl.core.elements.*; /** * XHL parser * * Grammar: * * <pre> * program ::= { statement } * statement ::= block | expression LINEEND * block ::= application ':' LINEEND INDENT { statement } DEDENT * * expression ::= application { operator application } * application ::= term { term } * term ::= literal | '(' expression ')' * * literal ::= symbol | string | number | 'true' | 'false' | 'none' * | list | map * list ::= '[]' | '[' expression { ',' expression } ']' * map ::= '{}' | '{' key-value { ',' key-value } '}' * key-value ::= expression ':' expression * </pre> * * @author Sergej Chodarev */ public class Reader { private Lexer lexer; private Token token; private static final Set<TokenType> termH; static { TokenType elements[] = { SYMBOL, STRING, NUMBER, TRUE, FALSE, NONE, BRACKET_OPEN, BRACE_OPEN, PAR_OPEN }; termH = new HashSet<TokenType>(Arrays.asList(elements)); } public List<Statement> read(java.io.Reader input) throws IOException { lexer = new Lexer(input); token = lexer.nextToken(); return program(); } public List<Statement> read(String code) throws IOException { return read(new StringReader(code)); } private List<Statement> program() throws IOException { List<Statement> lists = new LinkedList<Statement>(); while (token != null && token.type != DEDENT) { lists.add(expressionOrStatement(true)); } return lists; } private Statement expressionOrStatement(boolean statement) throws IOException { Expression first = application(); while (token.type == OPERATOR) { CodeList exp = new CodeList(token.position); Symbol op = new Symbol(token.stringValue, token.position); token = lexer.nextToken(); Expression second = application(); exp.add(op); exp.add(first); exp.add(second); first = exp; } if (token.type == LINEEND) token = lexer.nextToken(); else if (token.type == COLON) { token = lexer.nextToken(); // : token = lexer.nextToken(); // \n token = lexer.nextToken(); // INDENT FIXME: Add checks List<Statement> body = program(); token = lexer.nextToken(); // DEDENT FIXME: Add checks Block block = new Block(first, body, first.getPosition()); return block; } return first; } private Expression application() throws IOException { CodeList list = new CodeList(token.position); while (termH.contains(token.type)) { list.add(term()); } if (list.size() == 1) return (Expression) list.head(); else return list; } private DataList datalist() throws IOException { DataList list = new DataList(token.position); token = lexer.nextToken(); // [ if (token.type == BRACKET_CLOSE) { // Empty list token = lexer.nextToken(); // ] return list; } // Non-empty list list.add(term()); while (token.type != TokenType.BRACKET_CLOSE) { token = lexer.nextToken(); // , list.add(term()); } token = lexer.nextToken(); // ] return list; } private LMap map() throws IOException { LMap map = new LMap(token.position); token = lexer.nextToken(); // { if (token.type == BRACE_CLOSE) { // Empty map token = lexer.nextToken(); // } return map; } // Non-empty map keyValue(map); while (token.type != TokenType.BRACE_CLOSE) { token = lexer.nextToken(); // , keyValue(map); } token = lexer.nextToken(); // } return map; } private void keyValue(LMap map) throws IOException { Expression key = term(); token = lexer.nextToken(); // : Expression value = term(); map.put(key, value); } private Expression term() throws IOException { Expression sexp = null; switch (token.type) { case SYMBOL: sexp = new Symbol(token.stringValue, token.position); token = lexer.nextToken(); break; case STRING: sexp = new LString(token.stringValue, token.position); token = lexer.nextToken(); break; case NUMBER: sexp = new LNumber(token.doubleValue, token.position); token = lexer.nextToken(); break; case TRUE: sexp = new LBoolean(true, token.position); token = lexer.nextToken(); break; case FALSE: sexp = new LBoolean(false, token.position); token = lexer.nextToken(); break; case PAR_OPEN: token = lexer.nextToken(); // ( - sexp = application(); + sexp = (Expression) expressionOrStatement(false); token = lexer.nextToken(); // ) break; case BRACKET_OPEN: sexp = datalist(); break; case BRACE_OPEN: sexp = map(); break; } return sexp; } }
true
true
private Expression term() throws IOException { Expression sexp = null; switch (token.type) { case SYMBOL: sexp = new Symbol(token.stringValue, token.position); token = lexer.nextToken(); break; case STRING: sexp = new LString(token.stringValue, token.position); token = lexer.nextToken(); break; case NUMBER: sexp = new LNumber(token.doubleValue, token.position); token = lexer.nextToken(); break; case TRUE: sexp = new LBoolean(true, token.position); token = lexer.nextToken(); break; case FALSE: sexp = new LBoolean(false, token.position); token = lexer.nextToken(); break; case PAR_OPEN: token = lexer.nextToken(); // ( sexp = application(); token = lexer.nextToken(); // ) break; case BRACKET_OPEN: sexp = datalist(); break; case BRACE_OPEN: sexp = map(); break; } return sexp; }
private Expression term() throws IOException { Expression sexp = null; switch (token.type) { case SYMBOL: sexp = new Symbol(token.stringValue, token.position); token = lexer.nextToken(); break; case STRING: sexp = new LString(token.stringValue, token.position); token = lexer.nextToken(); break; case NUMBER: sexp = new LNumber(token.doubleValue, token.position); token = lexer.nextToken(); break; case TRUE: sexp = new LBoolean(true, token.position); token = lexer.nextToken(); break; case FALSE: sexp = new LBoolean(false, token.position); token = lexer.nextToken(); break; case PAR_OPEN: token = lexer.nextToken(); // ( sexp = (Expression) expressionOrStatement(false); token = lexer.nextToken(); // ) break; case BRACKET_OPEN: sexp = datalist(); break; case BRACE_OPEN: sexp = map(); break; } return sexp; }
diff --git a/gerrit-httpd/src/main/java/com/google/gerrit/httpd/GitOverHttpServlet.java b/gerrit-httpd/src/main/java/com/google/gerrit/httpd/GitOverHttpServlet.java index 546ac71c7..dad9b8057 100644 --- a/gerrit-httpd/src/main/java/com/google/gerrit/httpd/GitOverHttpServlet.java +++ b/gerrit-httpd/src/main/java/com/google/gerrit/httpd/GitOverHttpServlet.java @@ -1,354 +1,355 @@ // 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.google.gerrit.httpd; import com.google.common.cache.Cache; import com.google.gerrit.common.data.Capable; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.AccessPath; import com.google.gerrit.server.AnonymousUser; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.cache.CacheModule; import com.google.gerrit.server.git.AsyncReceiveCommits; import com.google.gerrit.server.git.ChangeCache; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.git.ReceiveCommits; import com.google.gerrit.server.git.TagCache; import com.google.gerrit.server.git.TransferConfig; import com.google.gerrit.server.git.VisibleRefFilter; import com.google.gerrit.server.project.NoSuchProjectException; import com.google.gerrit.server.project.ProjectControl; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.http.server.GitServlet; import org.eclipse.jgit.http.server.GitSmartHttpTools; import org.eclipse.jgit.http.server.ServletUtils; import org.eclipse.jgit.http.server.resolver.AsIsFileService; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.ReceivePack; import org.eclipse.jgit.transport.UploadPack; import org.eclipse.jgit.transport.resolver.ReceivePackFactory; import org.eclipse.jgit.transport.resolver.RepositoryResolver; import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException; import org.eclipse.jgit.transport.resolver.ServiceNotEnabledException; import org.eclipse.jgit.transport.resolver.UploadPackFactory; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Serves Git repositories over HTTP. */ @Singleton public class GitOverHttpServlet extends GitServlet { private static final long serialVersionUID = 1L; private static final String ATT_CONTROL = ProjectControl.class.getName(); private static final String ATT_RC = ReceiveCommits.class.getName(); private static final String ID_CACHE = "adv_bases"; public static final String URL_REGEX; static { StringBuilder url = new StringBuilder(); url.append("^(?:/p/|/)(.*/(?:info/refs"); for (String name : GitSmartHttpTools.VALID_SERVICES) { url.append('|').append(name); } url.append("))$"); URL_REGEX = url.toString(); } static class Module extends AbstractModule { @Override protected void configure() { bind(Resolver.class); bind(UploadFactory.class); bind(UploadFilter.class); bind(ReceiveFactory.class); bind(ReceiveFilter.class); install(new CacheModule() { @Override protected void configure() { cache(ID_CACHE, AdvertisedObjectsCacheKey.class, new TypeLiteral<Set<ObjectId>>() {}) .maximumWeight(4096) .expireAfterWrite(10, TimeUnit.MINUTES); } }); } } @Inject GitOverHttpServlet(Resolver resolver, UploadFactory upload, UploadFilter uploadFilter, ReceiveFactory receive, ReceiveFilter receiveFilter) { setRepositoryResolver(resolver); setAsIsFileService(AsIsFileService.DISABLED); setUploadPackFactory(upload); addUploadPackFilter(uploadFilter); setReceivePackFactory(receive); addReceivePackFilter(receiveFilter); } static class Resolver implements RepositoryResolver<HttpServletRequest> { private final GitRepositoryManager manager; private final ProjectControl.Factory projectControlFactory; @Inject Resolver(GitRepositoryManager manager, ProjectControl.Factory projectControlFactory) { this.manager = manager; this.projectControlFactory = projectControlFactory; } @Override public Repository open(HttpServletRequest req, String projectName) throws RepositoryNotFoundException, ServiceNotAuthorizedException, ServiceNotEnabledException { while (projectName.endsWith("/")) { projectName = projectName.substring(0, projectName.length() - 1); } if (projectName.endsWith(".git")) { // Be nice and drop the trailing ".git" suffix, which we never keep // in our database, but clients might mistakenly provide anyway. // projectName = projectName.substring(0, projectName.length() - 4); while (projectName.endsWith("/")) { projectName = projectName.substring(0, projectName.length() - 1); } } final ProjectControl pc; try { pc = projectControlFactory.controlFor(new Project.NameKey(projectName)); } catch (NoSuchProjectException err) { throw new RepositoryNotFoundException(projectName); } CurrentUser user = pc.getCurrentUser(); user.setAccessPath(AccessPath.GIT); if (!pc.isVisible()) { if (user instanceof AnonymousUser) { throw new ServiceNotAuthorizedException(); } else { throw new ServiceNotEnabledException(); } } req.setAttribute(ATT_CONTROL, pc); try { return manager.openRepository(pc.getProject().getNameKey()); } catch (IOException e) { throw new RepositoryNotFoundException( pc.getProject().getNameKey().get(), e); } } } static class UploadFactory implements UploadPackFactory<HttpServletRequest> { private final TransferConfig config; @Inject UploadFactory(TransferConfig tc) { this.config = tc; } @Override public UploadPack create(HttpServletRequest req, Repository repo) { UploadPack up = new UploadPack(repo); up.setPackConfig(config.getPackConfig()); up.setTimeout(config.getTimeout()); return up; } } static class UploadFilter implements Filter { private final Provider<ReviewDb> db; private final TagCache tagCache; private final ChangeCache changeCache; @Inject UploadFilter(Provider<ReviewDb> db, TagCache tagCache, ChangeCache changeCache) { this.db = db; this.tagCache = tagCache; this.changeCache = changeCache; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain next) throws IOException, ServletException { // The Resolver above already checked READ access for us. Repository repo = ServletUtils.getRepository(request); ProjectControl pc = (ProjectControl) request.getAttribute(ATT_CONTROL); UploadPack up = (UploadPack) request.getAttribute(ServletUtils.ATTRIBUTE_HANDLER); if (!pc.canRunUploadPack()) { GitSmartHttpTools.sendError((HttpServletRequest) request, (HttpServletResponse) response, HttpServletResponse.SC_FORBIDDEN, "upload-pack not permitted on this server"); return; } if (!pc.allRefsAreVisible()) { up.setAdvertiseRefsHook(new VisibleRefFilter(tagCache, changeCache, repo, pc, db.get(), true)); } next.doFilter(request, response); } @Override public void init(FilterConfig config) { } @Override public void destroy() { } } static class ReceiveFactory implements ReceivePackFactory<HttpServletRequest> { private final AsyncReceiveCommits.Factory factory; private final TransferConfig config; @Inject ReceiveFactory(AsyncReceiveCommits.Factory factory, TransferConfig config) { this.factory = factory; this.config = config; } @Override public ReceivePack create(HttpServletRequest req, Repository db) throws ServiceNotAuthorizedException { final ProjectControl pc = (ProjectControl) req.getAttribute(ATT_CONTROL); if (!(pc.getCurrentUser() instanceof IdentifiedUser)) { // Anonymous users are not permitted to push. throw new ServiceNotAuthorizedException(); } final IdentifiedUser user = (IdentifiedUser) pc.getCurrentUser(); final ReceiveCommits rc = factory.create(pc, db).getReceiveCommits(); ReceivePack rp = rc.getReceivePack(); rp.setRefLogIdent(user.newRefLogIdent()); rp.setTimeout(config.getTimeout()); rp.setMaxObjectSizeLimit(config.getMaxObjectSizeLimit()); req.setAttribute(ATT_RC, rc); return rp; } } static class ReceiveFilter implements Filter { private final Cache<AdvertisedObjectsCacheKey, Set<ObjectId>> cache; @Inject ReceiveFilter( @Named(ID_CACHE) Cache<AdvertisedObjectsCacheKey, Set<ObjectId>> cache) { this.cache = cache; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean isGet = "GET".equalsIgnoreCase(((HttpServletRequest) request).getMethod()); ReceiveCommits rc = (ReceiveCommits) request.getAttribute(ATT_RC); ReceivePack rp = rc.getReceivePack(); + rp.getAdvertiseRefsHook().advertiseRefs(rp); ProjectControl pc = (ProjectControl) request.getAttribute(ATT_CONTROL); Project.NameKey projectName = pc.getProject().getNameKey(); if (!pc.canRunReceivePack()) { GitSmartHttpTools.sendError((HttpServletRequest) request, (HttpServletResponse) response, HttpServletResponse.SC_FORBIDDEN, "receive-pack not permitted on this server"); return; } final Capable s = rc.canUpload(); if (s != Capable.OK) { GitSmartHttpTools.sendError((HttpServletRequest) request, (HttpServletResponse) response, HttpServletResponse.SC_FORBIDDEN, "\n" + s.getMessage()); return; } if (!rp.isCheckReferencedObjectsAreReachable()) { if (isGet) { rc.advertiseHistory(); } chain.doFilter(request, response); return; } if (!(pc.getCurrentUser() instanceof IdentifiedUser)) { chain.doFilter(request, response); return; } AdvertisedObjectsCacheKey cacheKey = new AdvertisedObjectsCacheKey( ((IdentifiedUser) pc.getCurrentUser()).getAccountId(), projectName); if (isGet) { rc.advertiseHistory(); cache.invalidate(cacheKey); } else { Set<ObjectId> ids = cache.getIfPresent(cacheKey); if (ids != null) { rp.getAdvertisedObjects().addAll(ids); cache.invalidate(cacheKey); } } chain.doFilter(request, response); if (isGet) { cache.put(cacheKey, Collections.unmodifiableSet( new HashSet<ObjectId>(rp.getAdvertisedObjects()))); } } @Override public void init(FilterConfig arg0) { } @Override public void destroy() { } } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean isGet = "GET".equalsIgnoreCase(((HttpServletRequest) request).getMethod()); ReceiveCommits rc = (ReceiveCommits) request.getAttribute(ATT_RC); ReceivePack rp = rc.getReceivePack(); ProjectControl pc = (ProjectControl) request.getAttribute(ATT_CONTROL); Project.NameKey projectName = pc.getProject().getNameKey(); if (!pc.canRunReceivePack()) { GitSmartHttpTools.sendError((HttpServletRequest) request, (HttpServletResponse) response, HttpServletResponse.SC_FORBIDDEN, "receive-pack not permitted on this server"); return; } final Capable s = rc.canUpload(); if (s != Capable.OK) { GitSmartHttpTools.sendError((HttpServletRequest) request, (HttpServletResponse) response, HttpServletResponse.SC_FORBIDDEN, "\n" + s.getMessage()); return; } if (!rp.isCheckReferencedObjectsAreReachable()) { if (isGet) { rc.advertiseHistory(); } chain.doFilter(request, response); return; } if (!(pc.getCurrentUser() instanceof IdentifiedUser)) { chain.doFilter(request, response); return; } AdvertisedObjectsCacheKey cacheKey = new AdvertisedObjectsCacheKey( ((IdentifiedUser) pc.getCurrentUser()).getAccountId(), projectName); if (isGet) { rc.advertiseHistory(); cache.invalidate(cacheKey); } else { Set<ObjectId> ids = cache.getIfPresent(cacheKey); if (ids != null) { rp.getAdvertisedObjects().addAll(ids); cache.invalidate(cacheKey); } } chain.doFilter(request, response); if (isGet) { cache.put(cacheKey, Collections.unmodifiableSet( new HashSet<ObjectId>(rp.getAdvertisedObjects()))); } }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean isGet = "GET".equalsIgnoreCase(((HttpServletRequest) request).getMethod()); ReceiveCommits rc = (ReceiveCommits) request.getAttribute(ATT_RC); ReceivePack rp = rc.getReceivePack(); rp.getAdvertiseRefsHook().advertiseRefs(rp); ProjectControl pc = (ProjectControl) request.getAttribute(ATT_CONTROL); Project.NameKey projectName = pc.getProject().getNameKey(); if (!pc.canRunReceivePack()) { GitSmartHttpTools.sendError((HttpServletRequest) request, (HttpServletResponse) response, HttpServletResponse.SC_FORBIDDEN, "receive-pack not permitted on this server"); return; } final Capable s = rc.canUpload(); if (s != Capable.OK) { GitSmartHttpTools.sendError((HttpServletRequest) request, (HttpServletResponse) response, HttpServletResponse.SC_FORBIDDEN, "\n" + s.getMessage()); return; } if (!rp.isCheckReferencedObjectsAreReachable()) { if (isGet) { rc.advertiseHistory(); } chain.doFilter(request, response); return; } if (!(pc.getCurrentUser() instanceof IdentifiedUser)) { chain.doFilter(request, response); return; } AdvertisedObjectsCacheKey cacheKey = new AdvertisedObjectsCacheKey( ((IdentifiedUser) pc.getCurrentUser()).getAccountId(), projectName); if (isGet) { rc.advertiseHistory(); cache.invalidate(cacheKey); } else { Set<ObjectId> ids = cache.getIfPresent(cacheKey); if (ids != null) { rp.getAdvertisedObjects().addAll(ids); cache.invalidate(cacheKey); } } chain.doFilter(request, response); if (isGet) { cache.put(cacheKey, Collections.unmodifiableSet( new HashSet<ObjectId>(rp.getAdvertisedObjects()))); } }
diff --git a/xfire-core/src/main/org/codehaus/xfire/handler/SoapHandler.java b/xfire-core/src/main/org/codehaus/xfire/handler/SoapHandler.java index 73558c60..31a2853a 100644 --- a/xfire-core/src/main/org/codehaus/xfire/handler/SoapHandler.java +++ b/xfire-core/src/main/org/codehaus/xfire/handler/SoapHandler.java @@ -1,111 +1,110 @@ package org.codehaus.xfire.handler; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.codehaus.xfire.MessageContext; /** * Delegates the SOAP Body and Header to appropriate handlers. * * @author <a href="mailto:[email protected]">Dan Diephouse</a> * @since Oct 28, 2004 */ public class SoapHandler extends AbstractHandler { private Handler bodyHandler; private Handler headerHandler; public SoapHandler( Handler bodyHandler ) { this.bodyHandler = bodyHandler; } public SoapHandler( Handler bodyHandler, Handler headerHandler ) { this.bodyHandler = bodyHandler; this.headerHandler = headerHandler; } /** * Invoke the Header and Body Handlers for the SOAP message. */ public void invoke(MessageContext context, XMLStreamReader reader) throws Exception { XMLStreamWriter writer = null; String encoding = null; boolean end = false; while ( !end && reader.hasNext() ) { int event = reader.next(); switch( event ) { case XMLStreamReader.START_DOCUMENT: encoding = reader.getCharacterEncodingScheme(); break; case XMLStreamReader.END_DOCUMENT: end = true; break; case XMLStreamReader.END_ELEMENT: break; case XMLStreamReader.START_ELEMENT: if( reader.getLocalName().equals("Header") && headerHandler != null ) { writer.writeStartElement("soap", "Header", context.getSoapVersion()); reader.nextTag(); headerHandler.invoke(context, reader); writer.writeEndElement(); } else if ( reader.getLocalName().equals("Body") ) { writer.writeStartElement("soap", "Body", context.getSoapVersion()); - reader.nextTag(); bodyHandler.invoke(context, reader); writer.writeEndElement(); } else if ( reader.getLocalName().equals("Envelope") ) { writer = createResponseEnvelope(context, reader, encoding); } break; default: break; } } writer.writeEndElement(); // Envelope writer.writeEndDocument(); writer.close(); } /** * @param context * @param reader * @throws XMLStreamException */ private XMLStreamWriter createResponseEnvelope(MessageContext context, XMLStreamReader reader, String encoding) throws XMLStreamException { XMLStreamWriter writer = getXMLStreamWriter(context); if ( encoding == null ) writer.writeStartDocument("UTF-8", "1.0"); else writer.writeStartDocument(encoding, "1.0"); String soapVersion = reader.getNamespaceURI(); context.setSoapVersion(soapVersion); writer.setPrefix("soap", soapVersion); writer.writeStartElement("soap", "Envelope", soapVersion); writer.writeNamespace("soap", soapVersion); return writer; } }
true
true
public void invoke(MessageContext context, XMLStreamReader reader) throws Exception { XMLStreamWriter writer = null; String encoding = null; boolean end = false; while ( !end && reader.hasNext() ) { int event = reader.next(); switch( event ) { case XMLStreamReader.START_DOCUMENT: encoding = reader.getCharacterEncodingScheme(); break; case XMLStreamReader.END_DOCUMENT: end = true; break; case XMLStreamReader.END_ELEMENT: break; case XMLStreamReader.START_ELEMENT: if( reader.getLocalName().equals("Header") && headerHandler != null ) { writer.writeStartElement("soap", "Header", context.getSoapVersion()); reader.nextTag(); headerHandler.invoke(context, reader); writer.writeEndElement(); } else if ( reader.getLocalName().equals("Body") ) { writer.writeStartElement("soap", "Body", context.getSoapVersion()); reader.nextTag(); bodyHandler.invoke(context, reader); writer.writeEndElement(); } else if ( reader.getLocalName().equals("Envelope") ) { writer = createResponseEnvelope(context, reader, encoding); } break; default: break; } } writer.writeEndElement(); // Envelope writer.writeEndDocument(); writer.close(); }
public void invoke(MessageContext context, XMLStreamReader reader) throws Exception { XMLStreamWriter writer = null; String encoding = null; boolean end = false; while ( !end && reader.hasNext() ) { int event = reader.next(); switch( event ) { case XMLStreamReader.START_DOCUMENT: encoding = reader.getCharacterEncodingScheme(); break; case XMLStreamReader.END_DOCUMENT: end = true; break; case XMLStreamReader.END_ELEMENT: break; case XMLStreamReader.START_ELEMENT: if( reader.getLocalName().equals("Header") && headerHandler != null ) { writer.writeStartElement("soap", "Header", context.getSoapVersion()); reader.nextTag(); headerHandler.invoke(context, reader); writer.writeEndElement(); } else if ( reader.getLocalName().equals("Body") ) { writer.writeStartElement("soap", "Body", context.getSoapVersion()); bodyHandler.invoke(context, reader); writer.writeEndElement(); } else if ( reader.getLocalName().equals("Envelope") ) { writer = createResponseEnvelope(context, reader, encoding); } break; default: break; } } writer.writeEndElement(); // Envelope writer.writeEndDocument(); writer.close(); }
diff --git a/rtest/src/org/subethamail/smtp/test/WiserFailuresTest.java b/rtest/src/org/subethamail/smtp/test/WiserFailuresTest.java index 989b96d..5058d95 100644 --- a/rtest/src/org/subethamail/smtp/test/WiserFailuresTest.java +++ b/rtest/src/org/subethamail/smtp/test/WiserFailuresTest.java @@ -1,332 +1,333 @@ package org.subethamail.smtp.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import junit.framework.TestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subethamail.wiser.Wiser; import org.subethamail.wiser.WiserMessage; public class WiserFailuresTest extends TestCase { private final static String FROM_ADDRESS = "from-addr@localhost"; private final static String HOST_NAME = "localhost"; private final static String TO_ADDRESS = "to-addr@localhost"; private final static int SMTP_PORT = 1081; private static Logger log = LoggerFactory.getLogger(WiserFailuresTest.class); private BufferedReader input; private PrintWriter output; private Wiser server; private Socket socket; public WiserFailuresTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); server = new Wiser(); server.setPort(SMTP_PORT); server.start(); socket = new Socket(HOST_NAME, SMTP_PORT); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new PrintWriter(socket.getOutputStream(), true); } protected void tearDown() throws Exception { super.tearDown(); try { input.close(); } catch (Exception e){}; try { output.close(); } catch (Exception e){}; try { socket.close(); } catch (Exception e){}; try { server.stop(); } catch (Exception e){}; } /** * See http://sourceforge.net/tracker/index.php?func=detail&aid=1474700&group_id=78413&atid=553186 for discussion * about this bug */ public void testMailFromAfterReset() throws IOException, MessagingException { log.info("testMailFromAfterReset() start"); assertConnect(); sendExtendedHello(HOST_NAME); sendMailFrom(FROM_ADDRESS); sendReceiptTo(TO_ADDRESS); sendReset(); sendMailFrom(FROM_ADDRESS); sendReceiptTo(TO_ADDRESS); sendDataStart(); send(""); send("Body"); sendDataEnd(); sendQuit(); assertEquals(1, server.getMessages().size()); Iterator<WiserMessage> emailIter = server.getMessages().iterator(); WiserMessage email = (WiserMessage)emailIter.next(); assertEquals("Body", email.getMimeMessage().getContent().toString()); } /** * See http://sourceforge.net/tracker/index.php?func=detail&aid=1474700&group_id=78413&atid=553186 for discussion * about this bug */ public void testMailFromWithInitialReset() throws IOException, MessagingException { assertConnect(); sendReset(); sendMailFrom(FROM_ADDRESS); sendReceiptTo(TO_ADDRESS); sendDataStart(); send(""); send("Body"); sendDataEnd(); sendQuit(); assertEquals(1, server.getMessages().size()); Iterator<WiserMessage> emailIter = server.getMessages().iterator(); WiserMessage email = (WiserMessage)emailIter.next(); assertEquals("Body", email.getMimeMessage().getContent().toString()); } public void testSendMessageWithCarriageReturn() throws IOException, MessagingException { String bodyWithCR = "\r\n\r\nKeep these\r\npesky\r\n\r\ncarriage returns\r\n"; try { sendMessage(SMTP_PORT, "[email protected]", "CRTest", bodyWithCR, "[email protected]"); } catch (Exception e) { e.printStackTrace(); fail("Unexpected exception: " + e); } assertEquals(1, server.getMessages().size()); Iterator<WiserMessage> emailIter = server.getMessages().iterator(); WiserMessage email = (WiserMessage)emailIter.next(); assertEquals(email.getMimeMessage().getContent().toString(), bodyWithCR); } public void testSendTwoMessagesSameConnection() throws IOException { try { MimeMessage[] mimeMessages = new MimeMessage[2]; Properties mailProps = getMailProperties(SMTP_PORT); Session session = Session.getInstance(mailProps, null); // session.setDebug(true); mimeMessages[0] = createMessage(session, "[email protected]", "[email protected]", "Doodle1", "Bug1"); mimeMessages[1] = createMessage(session, "[email protected]", "[email protected]", "Doodle2", "Bug2"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", SMTP_PORT, null, null); for (int i = 0; i < mimeMessages.length; i++) { MimeMessage mimeMessage = mimeMessages[i]; transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); } transport.close(); } catch (MessagingException e) { e.printStackTrace(); fail("Unexpected exception: " + e); } assertEquals(2, server.getMessages().size()); } public void testSendTwoMsgsWithLogin() throws MessagingException, IOException { try { String From = "[email protected]"; String To = "[email protected]"; String Subject = "Test"; String body = "Test Body"; Session session = Session.getInstance(getMailProperties(SMTP_PORT), null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(From)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To, false)); msg.setSubject(Subject); msg.setText(body); msg.setHeader("X-Mailer", "musala"); msg.setSentDate(new Date()); Transport transport = null; try { transport = session.getTransport("smtp"); transport.connect(HOST_NAME, SMTP_PORT, "ddd", "ddd"); assertEquals(0, server.getMessages().size()); transport.sendMessage(msg, InternetAddress.parse(To, false)); assertEquals(1, server.getMessages().size()); transport.sendMessage(msg, InternetAddress.parse("[email protected]", false)); assertEquals(2, server.getMessages().size()); } catch (javax.mail.MessagingException me) { me.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (transport != null) transport.close(); } } catch (Exception e) { e.printStackTrace(); } Iterator<WiserMessage> emailIter = server.getMessages().iterator(); WiserMessage email = (WiserMessage)emailIter.next(); - assertTrue(email.getMimeMessage().getHeader("Subject")[0].equals("Test")); - assertTrue(email.getMimeMessage().getContent().toString().equals("Test Body")); + MimeMessage mime = email.getMimeMessage(); + assertTrue(mime.getHeader("Subject")[0].equals("Test")); + assertTrue(mime.getContent().toString().equals("Test Body")); } private Properties getMailProperties(int port) { Properties mailProps = new Properties(); mailProps.setProperty("mail.smtp.host", "localhost"); mailProps.setProperty("mail.smtp.port", "" + port); mailProps.setProperty("mail.smtp.sendpartial", "true"); return mailProps; } private void sendMessage(int port, String from, String subject, String body, String to) throws MessagingException, IOException { Properties mailProps = getMailProperties(SMTP_PORT); Session session = Session.getInstance(mailProps, null); //session.setDebug(true); MimeMessage msg = createMessage(session, from, to, subject, body); Transport.send(msg); } private MimeMessage createMessage(Session session, String from, String to, String subject, String body) throws MessagingException, IOException { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(body); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); return msg; } private void assertConnect() throws IOException { String response = readInput(); assertTrue(response, response.startsWith("220")); } private void sendDataEnd() throws IOException { send("."); String response = readInput(); assertTrue(response, response.startsWith("250")); } private void sendDataStart() throws IOException { send("DATA"); String response = readInput(); assertTrue(response, response.startsWith("354")); } private void sendExtendedHello(String hostName) throws IOException { send("EHLO " + hostName); String response = readInput(); assertTrue(response, response.startsWith("250")); } private void sendMailFrom(String fromAddress) throws IOException { send("MAIL FROM:<" + fromAddress + ">"); String response = readInput(); assertTrue(response, response.startsWith("250")); } private void sendQuit() throws IOException { send("QUIT"); String response = readInput(); assertTrue(response, response.startsWith("221")); } private void sendReceiptTo(String toAddress) throws IOException { send("RCPT TO:<" + toAddress + ">"); String response = readInput(); assertTrue(response, response.startsWith("250")); } private void sendReset() throws IOException { send("RSET"); String response = readInput(); assertTrue(response, response.startsWith("250")); } private void send(String msg) throws IOException { // Force \r\n since println() behaves differently on different platforms output.print(msg + "\r\n"); output.flush(); } private String readInput() { StringBuffer sb = new StringBuffer(); try { do { sb.append(input.readLine()).append("\n"); } while (input.ready()); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } }
true
true
public void testSendTwoMsgsWithLogin() throws MessagingException, IOException { try { String From = "[email protected]"; String To = "[email protected]"; String Subject = "Test"; String body = "Test Body"; Session session = Session.getInstance(getMailProperties(SMTP_PORT), null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(From)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To, false)); msg.setSubject(Subject); msg.setText(body); msg.setHeader("X-Mailer", "musala"); msg.setSentDate(new Date()); Transport transport = null; try { transport = session.getTransport("smtp"); transport.connect(HOST_NAME, SMTP_PORT, "ddd", "ddd"); assertEquals(0, server.getMessages().size()); transport.sendMessage(msg, InternetAddress.parse(To, false)); assertEquals(1, server.getMessages().size()); transport.sendMessage(msg, InternetAddress.parse("[email protected]", false)); assertEquals(2, server.getMessages().size()); } catch (javax.mail.MessagingException me) { me.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (transport != null) transport.close(); } } catch (Exception e) { e.printStackTrace(); } Iterator<WiserMessage> emailIter = server.getMessages().iterator(); WiserMessage email = (WiserMessage)emailIter.next(); assertTrue(email.getMimeMessage().getHeader("Subject")[0].equals("Test")); assertTrue(email.getMimeMessage().getContent().toString().equals("Test Body")); }
public void testSendTwoMsgsWithLogin() throws MessagingException, IOException { try { String From = "[email protected]"; String To = "[email protected]"; String Subject = "Test"; String body = "Test Body"; Session session = Session.getInstance(getMailProperties(SMTP_PORT), null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(From)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(To, false)); msg.setSubject(Subject); msg.setText(body); msg.setHeader("X-Mailer", "musala"); msg.setSentDate(new Date()); Transport transport = null; try { transport = session.getTransport("smtp"); transport.connect(HOST_NAME, SMTP_PORT, "ddd", "ddd"); assertEquals(0, server.getMessages().size()); transport.sendMessage(msg, InternetAddress.parse(To, false)); assertEquals(1, server.getMessages().size()); transport.sendMessage(msg, InternetAddress.parse("[email protected]", false)); assertEquals(2, server.getMessages().size()); } catch (javax.mail.MessagingException me) { me.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (transport != null) transport.close(); } } catch (Exception e) { e.printStackTrace(); } Iterator<WiserMessage> emailIter = server.getMessages().iterator(); WiserMessage email = (WiserMessage)emailIter.next(); MimeMessage mime = email.getMimeMessage(); assertTrue(mime.getHeader("Subject")[0].equals("Test")); assertTrue(mime.getContent().toString().equals("Test Body")); }
diff --git a/SeapalAndroidApp/src/de/htwg/seapal/aview/gui/activity/BoatActivity.java b/SeapalAndroidApp/src/de/htwg/seapal/aview/gui/activity/BoatActivity.java index 403951f..3eb87b3 100644 --- a/SeapalAndroidApp/src/de/htwg/seapal/aview/gui/activity/BoatActivity.java +++ b/SeapalAndroidApp/src/de/htwg/seapal/aview/gui/activity/BoatActivity.java @@ -1,117 +1,117 @@ package de.htwg.seapal.aview.gui.activity; import java.util.UUID; import roboguice.activity.RoboActivity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.View; import com.google.inject.Inject; import de.htwg.seapal.R; import de.htwg.seapal.aview.gui.fragment.BoatDetailFragment; import de.htwg.seapal.aview.gui.fragment.BoatListFragment; import de.htwg.seapal.controller.impl.BoatController; import de.htwg.seapal.utils.observer.Event; import de.htwg.seapal.utils.observer.IObserver; public class BoatActivity extends RoboActivity implements IObserver, BoatListFragment.ListSelectedCallback { @Inject private BoatController controller; private BoatListFragment fragmentList; private BoatDetailFragment fragmentDetail; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.boat); controller.addObserver(this); if (savedInstanceState == null) { fragmentList = new BoatListFragment(); fragmentList.setController(controller); FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction .add(R.id.frame_list, fragmentList, BoatListFragment.TAG); View v = this.findViewById(R.id.linearLayout_xlarge); if (v != null) { // tablet -> FragmentDetail fragmentDetail = new BoatDetailFragment(); fragmentDetail.setController(controller); transaction.add(R.id.frame_detail, fragmentDetail, BoatDetailFragment.TAG); } transaction.commit(); } } @Override public void selected(UUID boat) { // Clickes an ListItem View v = this.findViewById(R.id.linearLayout_xlarge); if (v != null) { // Tablet scenario // fragmentDetail = (BoatDetailFragment) getFragmentManager() // .findFragmentByTag(BoatDetailFragment.TAG); fragmentDetail.setController(controller); fragmentDetail.refresh(boat); } else { // Smartphone fragmentDetail = new BoatDetailFragment(); fragmentDetail.setController(controller); fragmentDetail.setBoat(boat); FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.replace(R.id.frame_list, fragmentDetail); transaction.addToBackStack(null); transaction.commit(); } } @Override public void update(Event event) { - if (this.findViewById(R.id.boatlist) != null) { + if (this.findViewById(R.id.boatlistheader) != null) { if (this.findViewById(R.id.linearLayout_xlarge) != null && controller.getAllBoats().size() < fragmentList .getBoatListSize()) { // tablet -> delete button called -> clear FragmentDetailView FragmentTransaction tr = getFragmentManager() .beginTransaction(); fragmentDetail = new BoatDetailFragment(); fragmentDetail.setController(controller); tr.replace(R.id.frame_detail, fragmentDetail); tr.commit(); } // new Element fragmentList.onConfigurationChanged(null); } else { if (controller.getAllBoats().size() != fragmentList .getBoatListSize()) { FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.remove(fragmentDetail); transaction.remove(fragmentList); transaction.commit(); FragmentManager manager = getFragmentManager(); manager.popBackStack(); } } } }
true
true
public void update(Event event) { if (this.findViewById(R.id.boatlist) != null) { if (this.findViewById(R.id.linearLayout_xlarge) != null && controller.getAllBoats().size() < fragmentList .getBoatListSize()) { // tablet -> delete button called -> clear FragmentDetailView FragmentTransaction tr = getFragmentManager() .beginTransaction(); fragmentDetail = new BoatDetailFragment(); fragmentDetail.setController(controller); tr.replace(R.id.frame_detail, fragmentDetail); tr.commit(); } // new Element fragmentList.onConfigurationChanged(null); } else { if (controller.getAllBoats().size() != fragmentList .getBoatListSize()) { FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.remove(fragmentDetail); transaction.remove(fragmentList); transaction.commit(); FragmentManager manager = getFragmentManager(); manager.popBackStack(); } } }
public void update(Event event) { if (this.findViewById(R.id.boatlistheader) != null) { if (this.findViewById(R.id.linearLayout_xlarge) != null && controller.getAllBoats().size() < fragmentList .getBoatListSize()) { // tablet -> delete button called -> clear FragmentDetailView FragmentTransaction tr = getFragmentManager() .beginTransaction(); fragmentDetail = new BoatDetailFragment(); fragmentDetail.setController(controller); tr.replace(R.id.frame_detail, fragmentDetail); tr.commit(); } // new Element fragmentList.onConfigurationChanged(null); } else { if (controller.getAllBoats().size() != fragmentList .getBoatListSize()) { FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.remove(fragmentDetail); transaction.remove(fragmentList); transaction.commit(); FragmentManager manager = getFragmentManager(); manager.popBackStack(); } } }
diff --git a/patchtool/src/net/snowbound/patchtool/Main.java b/patchtool/src/net/snowbound/patchtool/Main.java index acdad17..a4c51e8 100644 --- a/patchtool/src/net/snowbound/patchtool/Main.java +++ b/patchtool/src/net/snowbound/patchtool/Main.java @@ -1,146 +1,146 @@ /* * patchtool - opensource tool to manipulate PTPatch files. * This is the first in a set of tools to aide modders in * creating PTPatch formatted binary patches. Used mainly for * the development and research of mods for Minecraft Pocket Edition * * */ package net.snowbound.patchtool; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { public static void main(String[] args){ if(args.length == 0){ return; } if(args[0].equals("-cl")){//combine legacy int num_patches = (args.length - 1); String[] patches = new String[num_patches]; for(int i = 0; i < num_patches; i++){ patches[i] = args[i + 1]; } try { combine_legacy(num_patches, patches); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void combine_legacy(int num, String[] patches) throws IOException{ byte[][] patch_array = new byte[num][]; //int final_size = 0; //int header = (6 +(num * 4)); for(int i = 0; i < num; i++){ try { patch_array[i] = readPatch(i, patches); //final_size += patch_array[i].length; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //final_size += header; File out = new File("patch.mod"); out.delete(); OutputStream os= new FileOutputStream(out); writeMagic(os); writeVersionCode(0, os); writeNumberPatches(num, os); os.write(generateIndices(num, patch_array)); os.write(mergeAndStripHeaderData(num, patch_array)); os.close(); } public static void writeMagic(OutputStream os) throws IOException{ byte[] magic = {(byte) 0xFF, 0x50, 0x54,0x50 }; os.write(magic); } public static void writeVersionCode(int vc, OutputStream os) throws IOException{ os.write(vc); } public static void writeNumberPatches(int num, OutputStream os) throws IOException{ os.write(num); } public static byte[] generateIndices(int num, byte[][] patchData){ byte[] ret = new byte[num * 4]; int headerSize = (6 + (num * 4)); int bloat = 0; for(int i = 0; i < num; i++){ int temp = headerSize; byte[] data = new byte[4]; if(i == 0){ - bloat += patchData[i].length; + bloat += patchData[i].length - 5; data = intToByteArray(temp); ret[i * 4] = data[0]; ret[(i * 4) + 1] = data[1]; ret[(i * 4) + 2] = data[2]; ret[(i * 4) + 3] = data[3]; }else{ temp += bloat; data = intToByteArray(temp); ret[i * 4] = data[0]; ret[(i * 4) + 1] = data[1]; ret[(i * 4) + 2] = data[2]; ret[(i * 4) + 3] = data[3]; - bloat += patchData[i].length; + bloat += patchData[i].length - 5; } } return ret; } public static byte[] mergeAndStripHeaderData(int num, byte[][] patchData){ int size = 0; for(int i = 0; i < num; i++){ size += (patchData[i].length - 5); } byte[] ret = new byte[size]; int count = 0; for(int i = 0, i2 = 0; i < num; i++){ for(i2 = 0; i2 < (patchData[i].length - 5);i2++){ ret[count] = patchData[i][i2 + 5]; count++; } } return ret; } public static byte[] readPatch(int index, String[] patches) throws IOException{ File patch = new File(patches[index]); byte[] ret = new byte[(int) patch.length()]; InputStream is = new FileInputStream(patches[index]); is.read(ret, 0, ret.length); is.close(); return ret; } public static final byte[] intToByteArray(int value) { return new byte[] { (byte)(value >>> 24), (byte)(value >>> 16), (byte)(value >>> 8), (byte)value}; } }
false
true
public static byte[] generateIndices(int num, byte[][] patchData){ byte[] ret = new byte[num * 4]; int headerSize = (6 + (num * 4)); int bloat = 0; for(int i = 0; i < num; i++){ int temp = headerSize; byte[] data = new byte[4]; if(i == 0){ bloat += patchData[i].length; data = intToByteArray(temp); ret[i * 4] = data[0]; ret[(i * 4) + 1] = data[1]; ret[(i * 4) + 2] = data[2]; ret[(i * 4) + 3] = data[3]; }else{ temp += bloat; data = intToByteArray(temp); ret[i * 4] = data[0]; ret[(i * 4) + 1] = data[1]; ret[(i * 4) + 2] = data[2]; ret[(i * 4) + 3] = data[3]; bloat += patchData[i].length; } } return ret; }
public static byte[] generateIndices(int num, byte[][] patchData){ byte[] ret = new byte[num * 4]; int headerSize = (6 + (num * 4)); int bloat = 0; for(int i = 0; i < num; i++){ int temp = headerSize; byte[] data = new byte[4]; if(i == 0){ bloat += patchData[i].length - 5; data = intToByteArray(temp); ret[i * 4] = data[0]; ret[(i * 4) + 1] = data[1]; ret[(i * 4) + 2] = data[2]; ret[(i * 4) + 3] = data[3]; }else{ temp += bloat; data = intToByteArray(temp); ret[i * 4] = data[0]; ret[(i * 4) + 1] = data[1]; ret[(i * 4) + 2] = data[2]; ret[(i * 4) + 3] = data[3]; bloat += patchData[i].length - 5; } } return ret; }
diff --git a/src/de/thm/ateam/memory/game/Memory.java b/src/de/thm/ateam/memory/game/Memory.java index 5c79e22..68f8081 100644 --- a/src/de/thm/ateam/memory/game/Memory.java +++ b/src/de/thm/ateam/memory/game/Memory.java @@ -1,249 +1,252 @@ package de.thm.ateam.memory.game; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import de.thm.ateam.memory.ImageAdapter; import de.thm.ateam.memory.Theme; import de.thm.ateam.memory.engine.type.Player; public class Memory extends Game{ /*environement stuff*/ private static final String TAG = Memory.class.getSimpleName(); private MemoryAttributes attr; private GridView mainView; private Theme theme; private ImageAdapter imageAdapter; private UpdateCardsHandler handler; private static Object lock = new Object(); //sperrobjekt private Activity envActivity; /*game function related stuff*/ private int ROW_COUNT; private int COL_COUNT; private int left; //how many cards are left private int card = -1; //should better be an object of card private Player current; public Memory(Context ctx, MemoryAttributes attr){ super(ctx,attr); this.attr = attr; this.envActivity = (Activity)ctx; // just a funny cast, that will let us access more functionality handler = new UpdateCardsHandler(); } public void newGame(){ ROW_COUNT = attr.getRows(); COL_COUNT = attr.getColumns(); left = ROW_COUNT * COL_COUNT; current = turn(); } public View assembleLayout(){ newGame(); for(Player p :attr.getPlayers()){ Log.i("demo", p.nick); } imageAdapter = new ImageAdapter(ctx, ROW_COUNT, COL_COUNT); theme = imageAdapter.getTheme(); mainView = new GridView(ctx); //mainView.setLayoutParams(new GridView.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); mainView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mainView.setNumColumns(attr.getColumns()); mainView.getLayoutParams().width = imageAdapter.maxSize(); mainView.setAdapter(imageAdapter); mainView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { /* * simple recognition of hits or misses, * must be overridden by a round-based player system * */ synchronized (lock) { //just to avoid unwanted behaviour if(card == -1){ flip(position); card = position; //Toast.makeText(ctx,"select " +position+ " first move", Toast.LENGTH_SHORT).show(); }else{ if(card != position) { flip(position); if(imageAdapter.getItemId(card) == imageAdapter.getItemId(position)){ delete(position, card); //Toast.makeText(ctx,"card "+ " select " +position+ " hit, next player", Toast.LENGTH_SHORT).show(); card = -1; current.hit(); left -= 2; if(left<=0){ Memory.this.getWinner(); String victoryMsg = ""; for(Player p : attr.getPlayers()){ if(p.roundWin) victoryMsg += p.nick + ","; } - Log.i("TEst", victoryMsg); - // deletes last comma - victoryMsg = victoryMsg.substring(0, victoryMsg.length()-1); - victoryMsg += " has won!!!"; + // deletes last comma if there is a winner + if(!victoryMsg.equals("")){ + victoryMsg = victoryMsg.substring(0, victoryMsg.length()-1); + victoryMsg += " has won!!!"; + }else{ + victoryMsg = "Last round was a draw."; + } Thread t = new Thread(new StatsUpdate(envActivity.getApplicationContext())); t.run(); for (Player p : attr.getPlayers()) { Log.i(TAG,p.nick+" turns: "+p.roundTurns+" hits: "+p.roundHits); } - envActivity.setResult(envActivity.RESULT_OK, envActivity.getIntent().putExtra("msg", victoryMsg)); + envActivity.setResult(Activity.RESULT_OK, envActivity.getIntent().putExtra("msg", victoryMsg)); envActivity.finish(); } }else{ //Toast.makeText(ctx,"card "+ " select " +position+ "miss, next player", Toast.LENGTH_SHORT).show(); reset(position); reset(card); card = -1; //current.turn(); current = turn(); } } } } } }); LinearLayout linLay = new LinearLayout(envActivity.getApplicationContext()); linLay.setOrientation(LinearLayout.HORIZONTAL); linLay.addView(mainView); //linLay.addView(new Button(envActivity.getApplicationContext())); return linLay; } /** * * Function which flips the card on the position * * @param position */ public void flip(int position) { ImageView clicked = (ImageView) imageAdapter.getItem(position); clicked.setImageBitmap(theme.getPicture(clicked.getId())); } public void onDestroy() { for(int i = 0; i < theme.getCount(); i++) { if(theme.getPicture(i) != null) theme.getPicture(i).recycle(); } } /** * * Function which resets the card on the position to the backside * note: added a Timed Task to make everything look a bit cooler * * @param position */ public void reset(int position) { /* * clicked.setImageBitmap(theme.getBackSide()); * is now in the Handler that receives a message from the TimedTask */ ResetTask task = new ResetTask(position); Timer t = new Timer(false); t.schedule(task, 1000); } public void delete(int pos1, int pos2) { ImageView clicked = (ImageView) imageAdapter.getItem(pos1); ImageView clicked2 = (ImageView) imageAdapter.getItem(pos2); clicked.setImageBitmap(null); clicked.setEnabled(false); clicked2.setImageBitmap(null); clicked2.setEnabled(false); } class ResetTask extends TimerTask { private int pos; public ResetTask(int pos) { this.pos = pos; } @Override public void run() { Bundle data = new Bundle(); data.putInt("pos", pos); Message msg = new Message(); msg.setData(data); handler.sendMessage(msg); } } class UpdateCardsHandler extends Handler{ @Override public void handleMessage(Message msg) { synchronized (lock) { doJob(msg); } } public void doJob(Message msg){ ImageView clicked = (ImageView) imageAdapter.getItem(msg.getData().getInt("pos")); clicked.setImageBitmap(theme.getBackSide()); } } }
false
true
public View assembleLayout(){ newGame(); for(Player p :attr.getPlayers()){ Log.i("demo", p.nick); } imageAdapter = new ImageAdapter(ctx, ROW_COUNT, COL_COUNT); theme = imageAdapter.getTheme(); mainView = new GridView(ctx); //mainView.setLayoutParams(new GridView.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); mainView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mainView.setNumColumns(attr.getColumns()); mainView.getLayoutParams().width = imageAdapter.maxSize(); mainView.setAdapter(imageAdapter); mainView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { /* * simple recognition of hits or misses, * must be overridden by a round-based player system * */ synchronized (lock) { //just to avoid unwanted behaviour if(card == -1){ flip(position); card = position; //Toast.makeText(ctx,"select " +position+ " first move", Toast.LENGTH_SHORT).show(); }else{ if(card != position) { flip(position); if(imageAdapter.getItemId(card) == imageAdapter.getItemId(position)){ delete(position, card); //Toast.makeText(ctx,"card "+ " select " +position+ " hit, next player", Toast.LENGTH_SHORT).show(); card = -1; current.hit(); left -= 2; if(left<=0){ Memory.this.getWinner(); String victoryMsg = ""; for(Player p : attr.getPlayers()){ if(p.roundWin) victoryMsg += p.nick + ","; } Log.i("TEst", victoryMsg); // deletes last comma victoryMsg = victoryMsg.substring(0, victoryMsg.length()-1); victoryMsg += " has won!!!"; Thread t = new Thread(new StatsUpdate(envActivity.getApplicationContext())); t.run(); for (Player p : attr.getPlayers()) { Log.i(TAG,p.nick+" turns: "+p.roundTurns+" hits: "+p.roundHits); } envActivity.setResult(envActivity.RESULT_OK, envActivity.getIntent().putExtra("msg", victoryMsg)); envActivity.finish(); } }else{ //Toast.makeText(ctx,"card "+ " select " +position+ "miss, next player", Toast.LENGTH_SHORT).show(); reset(position); reset(card); card = -1; //current.turn(); current = turn(); } } } } } }); LinearLayout linLay = new LinearLayout(envActivity.getApplicationContext()); linLay.setOrientation(LinearLayout.HORIZONTAL); linLay.addView(mainView); //linLay.addView(new Button(envActivity.getApplicationContext())); return linLay; }
public View assembleLayout(){ newGame(); for(Player p :attr.getPlayers()){ Log.i("demo", p.nick); } imageAdapter = new ImageAdapter(ctx, ROW_COUNT, COL_COUNT); theme = imageAdapter.getTheme(); mainView = new GridView(ctx); //mainView.setLayoutParams(new GridView.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); mainView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mainView.setNumColumns(attr.getColumns()); mainView.getLayoutParams().width = imageAdapter.maxSize(); mainView.setAdapter(imageAdapter); mainView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { /* * simple recognition of hits or misses, * must be overridden by a round-based player system * */ synchronized (lock) { //just to avoid unwanted behaviour if(card == -1){ flip(position); card = position; //Toast.makeText(ctx,"select " +position+ " first move", Toast.LENGTH_SHORT).show(); }else{ if(card != position) { flip(position); if(imageAdapter.getItemId(card) == imageAdapter.getItemId(position)){ delete(position, card); //Toast.makeText(ctx,"card "+ " select " +position+ " hit, next player", Toast.LENGTH_SHORT).show(); card = -1; current.hit(); left -= 2; if(left<=0){ Memory.this.getWinner(); String victoryMsg = ""; for(Player p : attr.getPlayers()){ if(p.roundWin) victoryMsg += p.nick + ","; } // deletes last comma if there is a winner if(!victoryMsg.equals("")){ victoryMsg = victoryMsg.substring(0, victoryMsg.length()-1); victoryMsg += " has won!!!"; }else{ victoryMsg = "Last round was a draw."; } Thread t = new Thread(new StatsUpdate(envActivity.getApplicationContext())); t.run(); for (Player p : attr.getPlayers()) { Log.i(TAG,p.nick+" turns: "+p.roundTurns+" hits: "+p.roundHits); } envActivity.setResult(Activity.RESULT_OK, envActivity.getIntent().putExtra("msg", victoryMsg)); envActivity.finish(); } }else{ //Toast.makeText(ctx,"card "+ " select " +position+ "miss, next player", Toast.LENGTH_SHORT).show(); reset(position); reset(card); card = -1; //current.turn(); current = turn(); } } } } } }); LinearLayout linLay = new LinearLayout(envActivity.getApplicationContext()); linLay.setOrientation(LinearLayout.HORIZONTAL); linLay.addView(mainView); //linLay.addView(new Button(envActivity.getApplicationContext())); return linLay; }
diff --git a/jzy3d-api/src/api/org/jzy3d/io/obj/OBJFile.java b/jzy3d-api/src/api/org/jzy3d/io/obj/OBJFile.java index cdd30da..3f17813 100644 --- a/jzy3d-api/src/api/org/jzy3d/io/obj/OBJFile.java +++ b/jzy3d-api/src/api/org/jzy3d/io/obj/OBJFile.java @@ -1,389 +1,392 @@ package org.jzy3d.io.obj; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.jzy3d.maths.BoundingBox3d; /** * Translated from C++ Version: nvModel.h - Model support class * * The nvModel class implements an interface for a multipurpose model object. * This class is useful for loading and formatting meshes for use by OpenGL. It * can compute face normals, tangents, and adjacency information. The class * supports the obj file format. * * Author: Evan Hart Email: [email protected] * * Copyright (c) NVIDIA Corporation. All rights reserved. */ public class OBJFile { /** Enumeration of primitive types */ public enum PrimType { eptNone(0x0), eptPoints(0x1), eptEdges(0x2), eptTriangles(0x4), eptTrianglesWithAdjacency(0x8), eptAll(0xf); PrimType(int val) { m_iVal = val; } int m_iVal = 0; }; public static final int NumPrimTypes = 4; /* * public Model CreateModel() { return new Model(); } */ public OBJFile() { posSize_ = 0; pOffset_ = -1; nOffset_ = -1; vtxSize_ = 0; openEdges_ = 0; } public class IdxSet { Integer pIndex = 0; Integer nIndex = 0; boolean lessThan(IdxSet rhs) { if (pIndex < rhs.pIndex) return true; else if (pIndex == rhs.pIndex) { if (nIndex < rhs.nIndex) return true; } return false; } }; /** * This function attempts to determine the type of the filename passed as a * parameter. If it understands that file type, it attempts to parse and * load the file into its raw data structures. If the file type is * recognized and successfully parsed, the function returns true, otherwise * it returns false. */ public boolean loadModelFromFile(String file) { URL fileURL = getClass().getClassLoader().getResource(File.separator + file); if (fileURL != null) { BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(fileURL.openStream())); String line = null; float[] val = new float[4]; int[][] idx = new int[3][3]; boolean hasNormals = false; while ((line = input.readLine()) != null) { + if(line.isEmpty()){ + continue; + } switch (line.charAt(0)) { case '#': break; case 'v': switch (line.charAt(1)) { case ' ': line = line.substring(line.indexOf(" ") + 1); // vertex, 3 or 4 components val[0] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[1] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[2] = Float.valueOf(line); positions_.add(val[0]); positions_.add(val[1]); positions_.add(val[2]); break; case 'n': // normal, 3 components line = line.substring(line.indexOf(" ") + 1); val[0] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[1] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[2] = Float.valueOf(line); normals_.add(val[0]); normals_.add(val[1]); normals_.add(val[2]); break; } break; case 'f': // face line = line.substring(line.indexOf(" ") + 2); idx[0][0] = Integer.valueOf(line.substring(0, line.indexOf("//"))).intValue(); line = line.substring(line.indexOf("//") + 2); idx[0][1] = Integer.valueOf(line.substring(0, line.indexOf(" "))).intValue(); { // This face has vertex and normal indices // in .obj, f v1 .... the vertex index used start // from 1, so -1 here // remap them to the right spot idx[0][0] = (idx[0][0] > 0) ? (idx[0][0] - 1) : ((int) positions_.size() - idx[0][0]); idx[0][1] = (idx[0][1] > 0) ? (idx[0][1] - 1) : ((int) normals_.size() - idx[0][1]); // grab the second vertex to prime line = line.substring(line.indexOf(" ") + 1); idx[1][0] = Integer.valueOf(line.substring(0, line.indexOf("//"))); line = line.substring(line.indexOf("//") + 2); idx[1][1] = Integer.valueOf(line.substring(0, line.indexOf(" "))); // remap them to the right spot idx[1][0] = (idx[1][0] > 0) ? (idx[1][0] - 1) : ((int) positions_.size() - idx[1][0]); idx[1][1] = (idx[1][1] > 0) ? (idx[1][1] - 1) : ((int) normals_.size() - idx[1][1]); // grab the third vertex to prime line = line.substring(line.indexOf(" ") + 1); idx[2][0] = Integer.valueOf(line.substring(0, line.indexOf("//"))); line = line.substring(line.indexOf("//") + 2); idx[2][1] = Integer.valueOf(line); { // remap them to the right spot idx[2][0] = (idx[2][0] > 0) ? (idx[2][0] - 1) : ((int) positions_.size() - idx[2][0]); idx[2][1] = (idx[2][1] > 0) ? (idx[2][1] - 1) : ((int) normals_.size() - idx[2][1]); // add the indices for (int ii = 0; ii < 3; ii++) { pIndex_.add(idx[ii][0]); nIndex_.add(idx[ii][1]); } // prepare for the next iteration, the num 0 // does not change. idx[1][0] = idx[2][0]; idx[1][1] = idx[2][1]; } hasNormals = true; } break; default: break; } ; } // post-process data // free anything that ended up being unused if (!hasNormals) { normals_.clear(); nIndex_.clear(); } posSize_ = 3; return true; } catch (FileNotFoundException kFNF) { System.err.println("Unable to find the shader file " + file); } catch (IOException kIO) { System.err.println("Problem reading the shader file " + file); } catch (NumberFormatException kIO) { System.err.println("Problem reading the shader file " + file); } finally { try { if (input != null) { input.close(); } } catch (IOException closee) { } } } return false; } /** * This function takes the raw model data in the internal * structures, and attempts to bring it to a format directly * accepted for vertex array style rendering. This means that * a unique compiled vertex will exist for each unique * combination of position, normal, tex coords, etc that are * used in the model. The prim parameter, tells the model * what type of index list to compile. By default it compiles * a simple triangle mesh with no connectivity. */ public void compileModel() { boolean needsTriangles = true; HashMap<IdxSet, Integer> pts = new HashMap<IdxSet, Integer>(); vertices_ = FloatBuffer.allocate((pIndex_.size() + nIndex_.size()) * 3); indices_ = IntBuffer.allocate(pIndex_.size()); for (int i = 0; i < pIndex_.size(); i++) { IdxSet idx = new IdxSet(); idx.pIndex = pIndex_.get(i); if (normals_.size() > 0) idx.nIndex = nIndex_.get(i); else idx.nIndex = 0; if (!pts.containsKey(idx)) { if (needsTriangles) indices_.put(pts.size()); pts.put(idx, pts.size()); // position, vertices_.put(positions_.get(idx.pIndex * posSize_)); vertices_.put(positions_.get(idx.pIndex * posSize_ + 1)); vertices_.put(positions_.get(idx.pIndex * posSize_ + 2)); // normal if (normals_.size() > 0) { vertices_.put(normals_.get(idx.nIndex * 3)); vertices_.put(normals_.get(idx.nIndex * 3 + 1)); vertices_.put(normals_.get(idx.nIndex * 3 + 2)); } } else { if (needsTriangles) indices_.put(pts.get(idx)); } } // create selected prim // set the offsets and vertex size pOffset_ = 0; // always first vtxSize_ = posSize_; if (hasNormals()) { nOffset_ = vtxSize_; vtxSize_ += 3; } else { nOffset_ = -1; } vertices_.rewind(); indices_.rewind(); } /** * Returns the points defining the axis-aligned bounding box containing the model. */ public BoundingBox3d computeBoundingBox() { float[] minVal = new float[3]; float[] maxVal = new float[3]; if (positions_.isEmpty()) return null; for (int i = 0; i < 3; i++) { minVal[i] = 1e10f; maxVal[i] = -1e10f; } for (int i = 0; i < positions_.size(); i += 3) { float x = positions_.get(i); float y = positions_.get(i + 1); float z = positions_.get(i + 2); minVal[0] = Math.min(minVal[0], x); minVal[1] = Math.min(minVal[1], y); minVal[2] = Math.min(minVal[2], z); maxVal[0] = Math.max(maxVal[0], x); maxVal[1] = Math.max(maxVal[1], y); maxVal[2] = Math.max(maxVal[2], z); } return new BoundingBox3d(minVal[0], maxVal[0], minVal[1], maxVal[1], minVal[2], maxVal[2]); } public void clearNormals() { normals_.clear(); nIndex_.clear(); } public boolean hasNormals() { return normals_.size() > 0; } public int getPositionSize() { return posSize_; } public int getNormalSize() { return 3; } public List<Float> getPositions() { return (positions_.size() > 0) ? positions_ : null; } public List<Float> getNormals() { return (normals_.size() > 0) ? normals_ : null; } public List<Integer> getPositionIndices() { return (pIndex_.size() > 0) ? pIndex_ : null; } public List<Integer> getNormalIndices() { return (nIndex_.size() > 0) ? nIndex_ : null; } public int getPositionCount() { return (posSize_ > 0) ? (int) positions_.size() / posSize_ : 0; } public int getNormalCount() { return (int) normals_.size() / 3; } public int getIndexCount() { return pIndex_.size(); } public FloatBuffer getCompiledVertices() { return vertices_; } public IntBuffer getCompiledIndices() { return indices_; } public int getCompiledPositionOffset() { return pOffset_; } public int getCompiledNormalOffset() { return nOffset_; } public int getCompiledVertexSize() { return vtxSize_; } public int getCompiledVertexCount() { return ((pIndex_.size() + nIndex_.size()) * 3); } public int getOpenEdgeCount() { return openEdges_; } protected List<Float> positions_ = new ArrayList<Float>(); protected List<Float> normals_ = new ArrayList<Float>(); protected int posSize_; protected List<Integer> pIndex_ = new ArrayList<Integer>(); protected List<Integer> nIndex_ = new ArrayList<Integer>(); // data structures optimized for rendering, compiled model protected IntBuffer indices_ = null; protected FloatBuffer vertices_ = null; protected int pOffset_; protected int nOffset_; protected int vtxSize_ = 0; protected int openEdges_; };
true
true
public boolean loadModelFromFile(String file) { URL fileURL = getClass().getClassLoader().getResource(File.separator + file); if (fileURL != null) { BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(fileURL.openStream())); String line = null; float[] val = new float[4]; int[][] idx = new int[3][3]; boolean hasNormals = false; while ((line = input.readLine()) != null) { switch (line.charAt(0)) { case '#': break; case 'v': switch (line.charAt(1)) { case ' ': line = line.substring(line.indexOf(" ") + 1); // vertex, 3 or 4 components val[0] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[1] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[2] = Float.valueOf(line); positions_.add(val[0]); positions_.add(val[1]); positions_.add(val[2]); break; case 'n': // normal, 3 components line = line.substring(line.indexOf(" ") + 1); val[0] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[1] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[2] = Float.valueOf(line); normals_.add(val[0]); normals_.add(val[1]); normals_.add(val[2]); break; } break; case 'f': // face line = line.substring(line.indexOf(" ") + 2); idx[0][0] = Integer.valueOf(line.substring(0, line.indexOf("//"))).intValue(); line = line.substring(line.indexOf("//") + 2); idx[0][1] = Integer.valueOf(line.substring(0, line.indexOf(" "))).intValue(); { // This face has vertex and normal indices // in .obj, f v1 .... the vertex index used start // from 1, so -1 here // remap them to the right spot idx[0][0] = (idx[0][0] > 0) ? (idx[0][0] - 1) : ((int) positions_.size() - idx[0][0]); idx[0][1] = (idx[0][1] > 0) ? (idx[0][1] - 1) : ((int) normals_.size() - idx[0][1]); // grab the second vertex to prime line = line.substring(line.indexOf(" ") + 1); idx[1][0] = Integer.valueOf(line.substring(0, line.indexOf("//"))); line = line.substring(line.indexOf("//") + 2); idx[1][1] = Integer.valueOf(line.substring(0, line.indexOf(" "))); // remap them to the right spot idx[1][0] = (idx[1][0] > 0) ? (idx[1][0] - 1) : ((int) positions_.size() - idx[1][0]); idx[1][1] = (idx[1][1] > 0) ? (idx[1][1] - 1) : ((int) normals_.size() - idx[1][1]); // grab the third vertex to prime line = line.substring(line.indexOf(" ") + 1); idx[2][0] = Integer.valueOf(line.substring(0, line.indexOf("//"))); line = line.substring(line.indexOf("//") + 2); idx[2][1] = Integer.valueOf(line); { // remap them to the right spot idx[2][0] = (idx[2][0] > 0) ? (idx[2][0] - 1) : ((int) positions_.size() - idx[2][0]); idx[2][1] = (idx[2][1] > 0) ? (idx[2][1] - 1) : ((int) normals_.size() - idx[2][1]); // add the indices for (int ii = 0; ii < 3; ii++) { pIndex_.add(idx[ii][0]); nIndex_.add(idx[ii][1]); } // prepare for the next iteration, the num 0 // does not change. idx[1][0] = idx[2][0]; idx[1][1] = idx[2][1]; } hasNormals = true; } break; default: break; } ; } // post-process data // free anything that ended up being unused if (!hasNormals) { normals_.clear(); nIndex_.clear(); } posSize_ = 3; return true; } catch (FileNotFoundException kFNF) { System.err.println("Unable to find the shader file " + file); } catch (IOException kIO) { System.err.println("Problem reading the shader file " + file); } catch (NumberFormatException kIO) { System.err.println("Problem reading the shader file " + file); } finally { try { if (input != null) { input.close(); } } catch (IOException closee) { } } } return false; }
public boolean loadModelFromFile(String file) { URL fileURL = getClass().getClassLoader().getResource(File.separator + file); if (fileURL != null) { BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(fileURL.openStream())); String line = null; float[] val = new float[4]; int[][] idx = new int[3][3]; boolean hasNormals = false; while ((line = input.readLine()) != null) { if(line.isEmpty()){ continue; } switch (line.charAt(0)) { case '#': break; case 'v': switch (line.charAt(1)) { case ' ': line = line.substring(line.indexOf(" ") + 1); // vertex, 3 or 4 components val[0] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[1] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[2] = Float.valueOf(line); positions_.add(val[0]); positions_.add(val[1]); positions_.add(val[2]); break; case 'n': // normal, 3 components line = line.substring(line.indexOf(" ") + 1); val[0] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[1] = Float.valueOf(line.substring(0, line.indexOf(" "))); line = line.substring(line.indexOf(" ") + 1); val[2] = Float.valueOf(line); normals_.add(val[0]); normals_.add(val[1]); normals_.add(val[2]); break; } break; case 'f': // face line = line.substring(line.indexOf(" ") + 2); idx[0][0] = Integer.valueOf(line.substring(0, line.indexOf("//"))).intValue(); line = line.substring(line.indexOf("//") + 2); idx[0][1] = Integer.valueOf(line.substring(0, line.indexOf(" "))).intValue(); { // This face has vertex and normal indices // in .obj, f v1 .... the vertex index used start // from 1, so -1 here // remap them to the right spot idx[0][0] = (idx[0][0] > 0) ? (idx[0][0] - 1) : ((int) positions_.size() - idx[0][0]); idx[0][1] = (idx[0][1] > 0) ? (idx[0][1] - 1) : ((int) normals_.size() - idx[0][1]); // grab the second vertex to prime line = line.substring(line.indexOf(" ") + 1); idx[1][0] = Integer.valueOf(line.substring(0, line.indexOf("//"))); line = line.substring(line.indexOf("//") + 2); idx[1][1] = Integer.valueOf(line.substring(0, line.indexOf(" "))); // remap them to the right spot idx[1][0] = (idx[1][0] > 0) ? (idx[1][0] - 1) : ((int) positions_.size() - idx[1][0]); idx[1][1] = (idx[1][1] > 0) ? (idx[1][1] - 1) : ((int) normals_.size() - idx[1][1]); // grab the third vertex to prime line = line.substring(line.indexOf(" ") + 1); idx[2][0] = Integer.valueOf(line.substring(0, line.indexOf("//"))); line = line.substring(line.indexOf("//") + 2); idx[2][1] = Integer.valueOf(line); { // remap them to the right spot idx[2][0] = (idx[2][0] > 0) ? (idx[2][0] - 1) : ((int) positions_.size() - idx[2][0]); idx[2][1] = (idx[2][1] > 0) ? (idx[2][1] - 1) : ((int) normals_.size() - idx[2][1]); // add the indices for (int ii = 0; ii < 3; ii++) { pIndex_.add(idx[ii][0]); nIndex_.add(idx[ii][1]); } // prepare for the next iteration, the num 0 // does not change. idx[1][0] = idx[2][0]; idx[1][1] = idx[2][1]; } hasNormals = true; } break; default: break; } ; } // post-process data // free anything that ended up being unused if (!hasNormals) { normals_.clear(); nIndex_.clear(); } posSize_ = 3; return true; } catch (FileNotFoundException kFNF) { System.err.println("Unable to find the shader file " + file); } catch (IOException kIO) { System.err.println("Problem reading the shader file " + file); } catch (NumberFormatException kIO) { System.err.println("Problem reading the shader file " + file); } finally { try { if (input != null) { input.close(); } } catch (IOException closee) { } } } return false; }
diff --git a/de.xwic.cube/src/de/xwic/cube/functions/LastLeafFunction.java b/de.xwic.cube/src/de/xwic/cube/functions/LastLeafFunction.java index e8b3733..272077b 100644 --- a/de.xwic.cube/src/de/xwic/cube/functions/LastLeafFunction.java +++ b/de.xwic.cube/src/de/xwic/cube/functions/LastLeafFunction.java @@ -1,117 +1,120 @@ /** * */ package de.xwic.cube.functions; import java.util.List; import de.xwic.cube.ICell; import de.xwic.cube.ICube; import de.xwic.cube.IDimension; import de.xwic.cube.IDimensionElement; import de.xwic.cube.IMeasure; import de.xwic.cube.IMeasureFunction; import de.xwic.cube.Key; /** * This function returns the data of the last leaf element for the specified Dimension. * * Sample: If setup for the Time dimension, a query to the key * [GEO:EMEA][JobCategorye:PSE][Time:2010/Q1] will return the value for * [GEO:EMEA][JobCategorye:PSE][Time:2010/Q1/Mar] * * The function is searching for the last leaf combination that has data, looking up the childs in reverse order. * * @author lippisch */ public class LastLeafFunction implements IMeasureFunction { private IDimension forceLeafDim; private IMeasure baseMeasure; private int dimIdx = -1; private int measureIdx = -1; private class Result { Double value = null;; boolean found = false; } /** * @param forceLeafDim */ public LastLeafFunction(IDimension forceLeafDim, IMeasure baseMeasure) { super(); this.forceLeafDim = forceLeafDim; this.baseMeasure = baseMeasure; } /* (non-Javadoc) * @see de.xwic.cube.IMeasureFunction#computeValue(de.xwic.cube.ICube, de.xwic.cube.Key, de.xwic.cube.ICell, de.xwic.cube.IMeasure) */ public Double computeValue(ICube cube, Key key, ICell cell, IMeasure measure) { if (dimIdx == -1) { dimIdx = cube.getDimensionIndex(forceLeafDim); measureIdx = cube.getMeasureIndex(baseMeasure); } IDimensionElement elm = key.getDimensionElement(dimIdx); if (elm.isLeaf()) { return cell != null ? cell.getValue(measureIdx) : null; } // search the last leaf that has a value Key searchKey = key.clone(); // reset all other dimensions (i.e. make a [GEO:*] out of a [GEO:EMEA] for (int i = 0, size = key.getDimensionElements().size(); i < size; i++) { if (i != dimIdx) { searchKey.setDimensionElement(i, searchKey.getDimensionElement(i).getDimension() ); } } return findLastLeaf(cube, key.clone(), searchKey, elm).value; } /** * This method searches for the last leaf. This is done by clearing out the other * dimensions, to find the last dimension element that is not "empty" at all. This * way we make sure that the last element is the same for all keys. * @param cube * @param key * @param searchKey * @param elm */ private Result findLastLeaf(ICube cube, Key key, Key searchKey, IDimensionElement elm) { Result result = new Result(); List<IDimensionElement> childs = elm.getDimensionElements(); for (int i = childs.size() - 1; i >= 0; i--) { IDimensionElement child = childs.get(i); if (child.isLeaf()) { searchKey.setDimensionElement(dimIdx, child); ICell cell = cube.getCell(searchKey); Double value = cell != null ? cell.getValue(measureIdx) : null; //RPF: added second null check -> caused nullpointer on different views! if (value != null) { key.setDimensionElement(dimIdx, child); - if (cube.getCell(key) != null) { - result.value = cube.getCell(key).getValue(measureIdx); - result.found = true; + ICell valueCell = cube.getCell(key); + if (valueCell != null) { + result.value = valueCell.getValue(measureIdx); + } else { + result.value = null; } + result.found = true; } } else { result = findLastLeaf(cube, key, searchKey, child); } if (result.found) { break; } } return result; } }
false
true
private Result findLastLeaf(ICube cube, Key key, Key searchKey, IDimensionElement elm) { Result result = new Result(); List<IDimensionElement> childs = elm.getDimensionElements(); for (int i = childs.size() - 1; i >= 0; i--) { IDimensionElement child = childs.get(i); if (child.isLeaf()) { searchKey.setDimensionElement(dimIdx, child); ICell cell = cube.getCell(searchKey); Double value = cell != null ? cell.getValue(measureIdx) : null; //RPF: added second null check -> caused nullpointer on different views! if (value != null) { key.setDimensionElement(dimIdx, child); if (cube.getCell(key) != null) { result.value = cube.getCell(key).getValue(measureIdx); result.found = true; } } } else { result = findLastLeaf(cube, key, searchKey, child); } if (result.found) { break; } } return result; }
private Result findLastLeaf(ICube cube, Key key, Key searchKey, IDimensionElement elm) { Result result = new Result(); List<IDimensionElement> childs = elm.getDimensionElements(); for (int i = childs.size() - 1; i >= 0; i--) { IDimensionElement child = childs.get(i); if (child.isLeaf()) { searchKey.setDimensionElement(dimIdx, child); ICell cell = cube.getCell(searchKey); Double value = cell != null ? cell.getValue(measureIdx) : null; //RPF: added second null check -> caused nullpointer on different views! if (value != null) { key.setDimensionElement(dimIdx, child); ICell valueCell = cube.getCell(key); if (valueCell != null) { result.value = valueCell.getValue(measureIdx); } else { result.value = null; } result.found = true; } } else { result = findLastLeaf(cube, key, searchKey, child); } if (result.found) { break; } } return result; }
diff --git a/sc-web/src/main/java/dk/sst/snomedcave/controllers/DrugController.java b/sc-web/src/main/java/dk/sst/snomedcave/controllers/DrugController.java index 9a6a700..1fb59c1 100644 --- a/sc-web/src/main/java/dk/sst/snomedcave/controllers/DrugController.java +++ b/sc-web/src/main/java/dk/sst/snomedcave/controllers/DrugController.java @@ -1,114 +1,119 @@ package dk.sst.snomedcave.controllers; import com.google.gson.*; import dk.sst.snomedcave.dao.ConceptRepository; import dk.sst.snomedcave.dao.DrugRepository; import dk.sst.snomedcave.model.Concept; import dk.sst.snomedcave.model.ConceptRelation; import dk.sst.snomedcave.model.Drug; import org.apache.commons.collections15.CollectionUtils; import org.apache.commons.collections15.IteratorUtils; import org.apache.commons.collections15.Predicate; import org.apache.log4j.Logger; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.traversal.Evaluators; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.graphdb.traversal.Traverser; import org.neo4j.kernel.Traversal; import org.springframework.data.neo4j.support.Neo4jTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import static org.neo4j.graphdb.DynamicRelationshipType.withName; @Controller @RequestMapping("/drugs/") public class DrugController { private final static Logger logger = Logger.getLogger(DrugController.class); @Inject DrugRepository drugRepository; @Inject ConceptRepository conceptRepository; @Inject Neo4jTemplate neo4jTemplate; Gson gson = new GsonBuilder().create(); private static Concept causativeAgentAttribute; @RequestMapping(value = "search", produces = "application/json;charset=utf-8") public ResponseEntity<String> search(@RequestParam("q") String drugQuery) { List<Drug> drugs = drugRepository.findByNameLike(String.format("*%s*", drugQuery)); if (drugs.isEmpty()) { return new ResponseEntity<String>(HttpStatus.NOT_FOUND); } JsonArray response = new JsonArray(); for (Drug drug : drugs) { response.add(new JsonPrimitive(String.format("%s", drug.getName()))); } return new ResponseEntity<String>(gson.toJson(response), HttpStatus.OK); } @RequestMapping(value = "concepttree", produces = "application/json;charset=utf-8") public ResponseEntity<String> tree(@RequestParam("name") String drugName) { final List<Drug> drugs = drugRepository.findByNameLike("\"" + drugName.replace("\"", "\\\"") + "\""); if (drugs.size() > 1) { logger.warn("Found more than one drug for drugName=" + drugName + ", count=" + drugs.size()); } Concept refersTo = drugs.get(0).getRefersTo(); Concept concept = null; Concept drugAllergy = conceptRepository.getByConceptId("416098002"); Node drugAllergyNode = neo4jTemplate.getNode(drugAllergy.getNodeId()); final TraversalDescription td = Traversal.description().depthFirst().relationships(withName("childs"), Direction.INCOMING).relationships(withName("child"), Direction.INCOMING).evaluator(Evaluators.returnWhereEndNodeIs(drugAllergyNode)); List<ConceptRelation> causativesDrugAllergy = new ArrayList<ConceptRelation>(CollectionUtils.select(refersTo.getChilds(), new Predicate<ConceptRelation>() { @Override public boolean evaluate(ConceptRelation relation) { if (conceptRepository.findOne(relation.getType().getNodeId()).getNodeId().equals(causativeAgentId())) { Node childNode = neo4jTemplate.getNode(relation.getChild().getNodeId()); + Concept child = conceptRepository.findOne(childNode.getId()); + if (child.getStatus() != 0) { + logger.debug("Filtered out child with status=" + child.getStatus() + " for " + child.getTerm()); + return false; + } Traverser paths = td.traverse(childNode); List<Path> pathList = IteratorUtils.toList(paths.iterator()); if (pathList.size() > 0) { logger.info("found " + pathList.size() + " paths to Drug Allergy"); } return pathList.size() > 0; } return false; } })); if (causativesDrugAllergy.size() > 1) { logger.warn("Found more than one causative agent"); for (ConceptRelation conceptRelation : causativesDrugAllergy) { Concept child = conceptRepository.findOne(conceptRelation.getChild().getNodeId()); logger.warn("conceptId=" + child.getConceptId() + ", name=" + child.getFullyspecifiedName()); } } if (causativesDrugAllergy.size() == 0) { return new ResponseEntity<String>(HttpStatus.NOT_FOUND); } concept = conceptRepository.findOne(causativesDrugAllergy.get(0).getChild().getNodeId()); return new ResponseEntity<String>(gson.toJson(concept.getConceptId()), HttpStatus.OK); } private long causativeAgentId() { if (causativeAgentAttribute == null) { causativeAgentAttribute = conceptRepository.getByConceptId("246075003"); } return causativeAgentAttribute.getNodeId(); } }
true
true
public ResponseEntity<String> tree(@RequestParam("name") String drugName) { final List<Drug> drugs = drugRepository.findByNameLike("\"" + drugName.replace("\"", "\\\"") + "\""); if (drugs.size() > 1) { logger.warn("Found more than one drug for drugName=" + drugName + ", count=" + drugs.size()); } Concept refersTo = drugs.get(0).getRefersTo(); Concept concept = null; Concept drugAllergy = conceptRepository.getByConceptId("416098002"); Node drugAllergyNode = neo4jTemplate.getNode(drugAllergy.getNodeId()); final TraversalDescription td = Traversal.description().depthFirst().relationships(withName("childs"), Direction.INCOMING).relationships(withName("child"), Direction.INCOMING).evaluator(Evaluators.returnWhereEndNodeIs(drugAllergyNode)); List<ConceptRelation> causativesDrugAllergy = new ArrayList<ConceptRelation>(CollectionUtils.select(refersTo.getChilds(), new Predicate<ConceptRelation>() { @Override public boolean evaluate(ConceptRelation relation) { if (conceptRepository.findOne(relation.getType().getNodeId()).getNodeId().equals(causativeAgentId())) { Node childNode = neo4jTemplate.getNode(relation.getChild().getNodeId()); Traverser paths = td.traverse(childNode); List<Path> pathList = IteratorUtils.toList(paths.iterator()); if (pathList.size() > 0) { logger.info("found " + pathList.size() + " paths to Drug Allergy"); } return pathList.size() > 0; } return false; } })); if (causativesDrugAllergy.size() > 1) { logger.warn("Found more than one causative agent"); for (ConceptRelation conceptRelation : causativesDrugAllergy) { Concept child = conceptRepository.findOne(conceptRelation.getChild().getNodeId()); logger.warn("conceptId=" + child.getConceptId() + ", name=" + child.getFullyspecifiedName()); } } if (causativesDrugAllergy.size() == 0) { return new ResponseEntity<String>(HttpStatus.NOT_FOUND); } concept = conceptRepository.findOne(causativesDrugAllergy.get(0).getChild().getNodeId()); return new ResponseEntity<String>(gson.toJson(concept.getConceptId()), HttpStatus.OK); }
public ResponseEntity<String> tree(@RequestParam("name") String drugName) { final List<Drug> drugs = drugRepository.findByNameLike("\"" + drugName.replace("\"", "\\\"") + "\""); if (drugs.size() > 1) { logger.warn("Found more than one drug for drugName=" + drugName + ", count=" + drugs.size()); } Concept refersTo = drugs.get(0).getRefersTo(); Concept concept = null; Concept drugAllergy = conceptRepository.getByConceptId("416098002"); Node drugAllergyNode = neo4jTemplate.getNode(drugAllergy.getNodeId()); final TraversalDescription td = Traversal.description().depthFirst().relationships(withName("childs"), Direction.INCOMING).relationships(withName("child"), Direction.INCOMING).evaluator(Evaluators.returnWhereEndNodeIs(drugAllergyNode)); List<ConceptRelation> causativesDrugAllergy = new ArrayList<ConceptRelation>(CollectionUtils.select(refersTo.getChilds(), new Predicate<ConceptRelation>() { @Override public boolean evaluate(ConceptRelation relation) { if (conceptRepository.findOne(relation.getType().getNodeId()).getNodeId().equals(causativeAgentId())) { Node childNode = neo4jTemplate.getNode(relation.getChild().getNodeId()); Concept child = conceptRepository.findOne(childNode.getId()); if (child.getStatus() != 0) { logger.debug("Filtered out child with status=" + child.getStatus() + " for " + child.getTerm()); return false; } Traverser paths = td.traverse(childNode); List<Path> pathList = IteratorUtils.toList(paths.iterator()); if (pathList.size() > 0) { logger.info("found " + pathList.size() + " paths to Drug Allergy"); } return pathList.size() > 0; } return false; } })); if (causativesDrugAllergy.size() > 1) { logger.warn("Found more than one causative agent"); for (ConceptRelation conceptRelation : causativesDrugAllergy) { Concept child = conceptRepository.findOne(conceptRelation.getChild().getNodeId()); logger.warn("conceptId=" + child.getConceptId() + ", name=" + child.getFullyspecifiedName()); } } if (causativesDrugAllergy.size() == 0) { return new ResponseEntity<String>(HttpStatus.NOT_FOUND); } concept = conceptRepository.findOne(causativesDrugAllergy.get(0).getChild().getNodeId()); return new ResponseEntity<String>(gson.toJson(concept.getConceptId()), HttpStatus.OK); }
diff --git a/ignition-ui/src/main/java/com/github/ignition/ui/widgets/HorizontalPagerControl.java b/ignition-ui/src/main/java/com/github/ignition/ui/widgets/HorizontalPagerControl.java index 6d515a3..8d6e7bd 100644 --- a/ignition-ui/src/main/java/com/github/ignition/ui/widgets/HorizontalPagerControl.java +++ b/ignition-ui/src/main/java/com/github/ignition/ui/widgets/HorizontalPagerControl.java @@ -1,179 +1,182 @@ package com.github.ignition.ui.widgets; /* * Copyright (C) 2010 Deez Apps! * * 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 android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.LinearInterpolator; import com.github.ignition.ui.R; /** * Kindly donated to the ignition project by Jean Guy. * * User: [email protected] Date: Aug 11, 2010 */ public class HorizontalPagerControl extends View { private static final int DEFAULT_BAR_COLOR = 0xaa777777; private static final int DEFAULT_HIGHLIGHT_COLOR = 0xaa999999; private static final int DEFAULT_FADE_DELAY = 2000; private static final int DEFAULT_FADE_DURATION = 500; private int numPages, currentPage, position; private Paint barPaint, highlightPaint; private int fadeDelay, fadeDuration; private float ovalRadius; private Animation fadeOutAnimation; public HorizontalPagerControl(Context context, AttributeSet attrs) { this(context, attrs, 0); } public HorizontalPagerControl(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.com_github_ignition_ui_widgets_PagerControl); - int barColor = a.getColor(R.styleable.com_github_ignition_ui_widgets_PagerControl_barColor, + R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl); + int barColor = a.getColor( + R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_barColor, DEFAULT_BAR_COLOR); int highlightColor = a.getColor( - R.styleable.com_github_ignition_ui_widgets_PagerControl_highlightColor, + R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_highlightColor, DEFAULT_HIGHLIGHT_COLOR); - fadeDelay = a.getInteger(R.styleable.com_github_ignition_ui_widgets_PagerControl_fadeDelay, + fadeDelay = a.getInteger( + R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_fadeDelay, DEFAULT_FADE_DELAY); fadeDuration = a.getInteger( - R.styleable.com_github_ignition_ui_widgets_PagerControl_fadeDuration, + R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_fadeDuration, DEFAULT_FADE_DURATION); ovalRadius = a.getDimension( - R.styleable.com_github_ignition_ui_widgets_PagerControl_roundRectRadius, 0f); + R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_roundRectRadius, + 0f); a.recycle(); barPaint = new Paint(); barPaint.setColor(barColor); highlightPaint = new Paint(); highlightPaint.setColor(highlightColor); fadeOutAnimation = new AlphaAnimation(1f, 0f); fadeOutAnimation.setDuration(fadeDuration); fadeOutAnimation.setRepeatCount(0); fadeOutAnimation.setInterpolator(new LinearInterpolator()); fadeOutAnimation.setFillEnabled(true); fadeOutAnimation.setFillAfter(true); } /** * * @return current number of pages */ public int getNumPages() { return numPages; } /** * * @param numPages * must be positive number */ public void setNumPages(int numPages) { if (numPages <= 0) { throw new IllegalArgumentException("numPages must be positive"); } this.numPages = numPages; invalidate(); fadeOut(); } private void fadeOut() { if (fadeDuration > 0) { clearAnimation(); fadeOutAnimation.setStartTime(AnimationUtils.currentAnimationTimeMillis() + fadeDelay); setAnimation(fadeOutAnimation); } } /** * 0 to numPages-1 * * @return */ public int getCurrentPage() { return currentPage; } /** * * @param currentPage * 0 to numPages-1 */ public void setCurrentPage(int currentPage) { if (currentPage < 0 || currentPage >= numPages) { throw new IllegalArgumentException("currentPage parameter out of bounds"); } if (this.currentPage != currentPage) { this.currentPage = currentPage; this.position = currentPage * getPageWidth(); invalidate(); fadeOut(); } } /** * Equivalent to the width of the view divided by the current number of * pages. * * @return page width, in pixels */ public int getPageWidth() { return getWidth() / numPages; } /** * * @param position * can be -pageWidth to pageWidth*(numPages+1) */ public void setPosition(int position) { if (this.position != position) { this.position = position; invalidate(); fadeOut(); } } /** * * @param canvas */ @Override protected void onDraw(Canvas canvas) { canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), ovalRadius, ovalRadius, barPaint); canvas.drawRoundRect( new RectF(position, 0, position + (getWidth() / numPages), getHeight()), ovalRadius, ovalRadius, highlightPaint); } }
false
true
public HorizontalPagerControl(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.com_github_ignition_ui_widgets_PagerControl); int barColor = a.getColor(R.styleable.com_github_ignition_ui_widgets_PagerControl_barColor, DEFAULT_BAR_COLOR); int highlightColor = a.getColor( R.styleable.com_github_ignition_ui_widgets_PagerControl_highlightColor, DEFAULT_HIGHLIGHT_COLOR); fadeDelay = a.getInteger(R.styleable.com_github_ignition_ui_widgets_PagerControl_fadeDelay, DEFAULT_FADE_DELAY); fadeDuration = a.getInteger( R.styleable.com_github_ignition_ui_widgets_PagerControl_fadeDuration, DEFAULT_FADE_DURATION); ovalRadius = a.getDimension( R.styleable.com_github_ignition_ui_widgets_PagerControl_roundRectRadius, 0f); a.recycle(); barPaint = new Paint(); barPaint.setColor(barColor); highlightPaint = new Paint(); highlightPaint.setColor(highlightColor); fadeOutAnimation = new AlphaAnimation(1f, 0f); fadeOutAnimation.setDuration(fadeDuration); fadeOutAnimation.setRepeatCount(0); fadeOutAnimation.setInterpolator(new LinearInterpolator()); fadeOutAnimation.setFillEnabled(true); fadeOutAnimation.setFillAfter(true); }
public HorizontalPagerControl(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl); int barColor = a.getColor( R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_barColor, DEFAULT_BAR_COLOR); int highlightColor = a.getColor( R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_highlightColor, DEFAULT_HIGHLIGHT_COLOR); fadeDelay = a.getInteger( R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_fadeDelay, DEFAULT_FADE_DELAY); fadeDuration = a.getInteger( R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_fadeDuration, DEFAULT_FADE_DURATION); ovalRadius = a.getDimension( R.styleable.com_github_ignition_ui_widgets_HorizontalPagerControl_roundRectRadius, 0f); a.recycle(); barPaint = new Paint(); barPaint.setColor(barColor); highlightPaint = new Paint(); highlightPaint.setColor(highlightColor); fadeOutAnimation = new AlphaAnimation(1f, 0f); fadeOutAnimation.setDuration(fadeDuration); fadeOutAnimation.setRepeatCount(0); fadeOutAnimation.setInterpolator(new LinearInterpolator()); fadeOutAnimation.setFillEnabled(true); fadeOutAnimation.setFillAfter(true); }
diff --git a/org/xbill/DNS/ZoneTransferIn.java b/org/xbill/DNS/ZoneTransferIn.java index 7fad554..8a19992 100644 --- a/org/xbill/DNS/ZoneTransferIn.java +++ b/org/xbill/DNS/ZoneTransferIn.java @@ -1,680 +1,680 @@ // Copyright (c) 2003-2004 Brian Wellington ([email protected]) // Parts of this are derived from lib/dns/xfrin.c from BIND 9; its copyright // notice follows. /* * Copyright (C) 1999-2001 Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package org.xbill.DNS; import java.io.*; import java.net.*; import java.util.*; /** * An incoming DNS Zone Transfer. To use this class, first initialize an * object, then call the run() method. If run() doesn't throw an exception * the result will either be an IXFR-style response, an AXFR-style response, * or an indication that the zone is up to date. * * @author Brian Wellington */ public class ZoneTransferIn { private static final int INITIALSOA = 0; private static final int FIRSTDATA = 1; private static final int IXFR_DELSOA = 2; private static final int IXFR_DEL = 3; private static final int IXFR_ADDSOA = 4; private static final int IXFR_ADD = 5; private static final int AXFR = 6; private static final int END = 7; private Name zname; private int qtype; private int dclass; private long ixfr_serial; private boolean want_fallback; private ZoneTransferHandler handler; private SocketAddress localAddress; private SocketAddress address; private TCPClient client; private TSIG tsig; private TSIG.StreamVerifier verifier; private long timeout = 900 * 1000; private int state; private long end_serial; private long current_serial; private Record initialsoa; private int rtype; public static class Delta { /** * All changes between two versions of a zone in an IXFR response. */ /** The starting serial number of this delta. */ public long start; /** The ending serial number of this delta. */ public long end; /** A list of records added between the start and end versions */ public List adds; /** A list of records deleted between the start and end versions */ public List deletes; private Delta() { adds = new ArrayList(); deletes = new ArrayList(); } } public static interface ZoneTransferHandler { /** * Handles a Zone Transfer. */ /** * Called when an AXFR transfer begins. */ public void startAXFR() throws ZoneTransferException; /** * Called when an IXFR transfer begins. */ public void startIXFR() throws ZoneTransferException; /** * Called when a series of IXFR deletions begins. * @param soa The starting SOA. */ public void startIXFRDeletes(Record soa) throws ZoneTransferException; /** * Called when a series of IXFR adds begins. * @param soa The starting SOA. */ public void startIXFRAdds(Record soa) throws ZoneTransferException; /** * Called for each content record in an AXFR. * @param r The DNS record. */ public void handleRecord(Record r) throws ZoneTransferException; }; private static class BasicHandler implements ZoneTransferHandler { private List axfr; private List ixfr; public void startAXFR() { axfr = new ArrayList(); } public void startIXFR() { ixfr = new ArrayList(); } public void startIXFRDeletes(Record soa) { Delta delta = new Delta(); delta.deletes.add(soa); delta.start = getSOASerial(soa); ixfr.add(delta); } public void startIXFRAdds(Record soa) { Delta delta = (Delta) ixfr.get(ixfr.size() - 1); delta.adds.add(soa); delta.end = getSOASerial(soa); } public void handleRecord(Record r) { List list; if (ixfr != null) { Delta delta = (Delta) ixfr.get(ixfr.size() - 1); if (delta.adds.size() > 0) list = delta.adds; else list = delta.deletes; } else list = axfr; list.add(r); } }; private ZoneTransferIn() {} private ZoneTransferIn(Name zone, int xfrtype, long serial, boolean fallback, SocketAddress address, TSIG key) { this.address = address; this.tsig = key; if (zone.isAbsolute()) zname = zone; else { try { zname = Name.concatenate(zone, Name.root); } catch (NameTooLongException e) { throw new IllegalArgumentException("ZoneTransferIn: " + "name too long"); } } qtype = xfrtype; dclass = DClass.IN; ixfr_serial = serial; want_fallback = fallback; state = INITIALSOA; } /** * Instantiates a ZoneTransferIn object to do an AXFR (full zone transfer). * @param zone The zone to transfer. * @param address The host/port from which to transfer the zone. * @param key The TSIG key used to authenticate the transfer, or null. * @return The ZoneTransferIn object. * @throws UnknownHostException The host does not exist. */ public static ZoneTransferIn newAXFR(Name zone, SocketAddress address, TSIG key) { return new ZoneTransferIn(zone, Type.AXFR, 0, false, address, key); } /** * Instantiates a ZoneTransferIn object to do an AXFR (full zone transfer). * @param zone The zone to transfer. * @param host The host from which to transfer the zone. * @param port The port to connect to on the server, or 0 for the default. * @param key The TSIG key used to authenticate the transfer, or null. * @return The ZoneTransferIn object. * @throws UnknownHostException The host does not exist. */ public static ZoneTransferIn newAXFR(Name zone, String host, int port, TSIG key) throws UnknownHostException { if (port == 0) port = SimpleResolver.DEFAULT_PORT; return newAXFR(zone, new InetSocketAddress(host, port), key); } /** * Instantiates a ZoneTransferIn object to do an AXFR (full zone transfer). * @param zone The zone to transfer. * @param host The host from which to transfer the zone. * @param key The TSIG key used to authenticate the transfer, or null. * @return The ZoneTransferIn object. * @throws UnknownHostException The host does not exist. */ public static ZoneTransferIn newAXFR(Name zone, String host, TSIG key) throws UnknownHostException { return newAXFR(zone, host, 0, key); } /** * Instantiates a ZoneTransferIn object to do an IXFR (incremental zone * transfer). * @param zone The zone to transfer. * @param serial The existing serial number. * @param fallback If true, fall back to AXFR if IXFR is not supported. * @param address The host/port from which to transfer the zone. * @param key The TSIG key used to authenticate the transfer, or null. * @return The ZoneTransferIn object. * @throws UnknownHostException The host does not exist. */ public static ZoneTransferIn newIXFR(Name zone, long serial, boolean fallback, SocketAddress address, TSIG key) { return new ZoneTransferIn(zone, Type.IXFR, serial, fallback, address, key); } /** * Instantiates a ZoneTransferIn object to do an IXFR (incremental zone * transfer). * @param zone The zone to transfer. * @param serial The existing serial number. * @param fallback If true, fall back to AXFR if IXFR is not supported. * @param host The host from which to transfer the zone. * @param port The port to connect to on the server, or 0 for the default. * @param key The TSIG key used to authenticate the transfer, or null. * @return The ZoneTransferIn object. * @throws UnknownHostException The host does not exist. */ public static ZoneTransferIn newIXFR(Name zone, long serial, boolean fallback, String host, int port, TSIG key) throws UnknownHostException { if (port == 0) port = SimpleResolver.DEFAULT_PORT; return newIXFR(zone, serial, fallback, new InetSocketAddress(host, port), key); } /** * Instantiates a ZoneTransferIn object to do an IXFR (incremental zone * transfer). * @param zone The zone to transfer. * @param serial The existing serial number. * @param fallback If true, fall back to AXFR if IXFR is not supported. * @param host The host from which to transfer the zone. * @param key The TSIG key used to authenticate the transfer, or null. * @return The ZoneTransferIn object. * @throws UnknownHostException The host does not exist. */ public static ZoneTransferIn newIXFR(Name zone, long serial, boolean fallback, String host, TSIG key) throws UnknownHostException { return newIXFR(zone, serial, fallback, host, 0, key); } /** * Gets the name of the zone being transferred. */ public Name getName() { return zname; } /** * Gets the type of zone transfer (either AXFR or IXFR). */ public int getType() { return qtype; } /** * Sets a timeout on this zone transfer. The default is 900 seconds (15 * minutes). * @param secs The maximum amount of time that this zone transfer can take. */ public void setTimeout(int secs) { if (secs < 0) throw new IllegalArgumentException("timeout cannot be " + "negative"); timeout = 1000L * secs; } /** * Sets an alternate DNS class for this zone transfer. * @param dclass The class to use instead of class IN. */ public void setDClass(int dclass) { DClass.check(dclass); this.dclass = dclass; } /** * Sets the local address to bind to when sending messages. * @param addr The local address to send messages from. */ public void setLocalAddress(SocketAddress addr) { this.localAddress = addr; } private void openConnection() throws IOException { long endTime = System.currentTimeMillis() + timeout; client = new TCPClient(endTime); if (localAddress != null) client.bind(localAddress); client.connect(address); } private void sendQuery() throws IOException { Record question = Record.newRecord(zname, qtype, dclass); Message query = new Message(); query.getHeader().setOpcode(Opcode.QUERY); query.addRecord(question, Section.QUESTION); if (qtype == Type.IXFR) { Record soa = new SOARecord(zname, dclass, 0, Name.root, Name.root, ixfr_serial, 0, 0, 0, 0); query.addRecord(soa, Section.AUTHORITY); } if (tsig != null) { tsig.apply(query, null); verifier = new TSIG.StreamVerifier(tsig, query.getTSIG()); } byte [] out = query.toWire(Message.MAXLENGTH); client.send(out); } private static long getSOASerial(Record rec) { SOARecord soa = (SOARecord) rec; return soa.getSerial(); } private void logxfr(String s) { if (Options.check("verbose")) System.out.println(zname + ": " + s); } private void fail(String s) throws ZoneTransferException { throw new ZoneTransferException(s); } private void fallback() throws ZoneTransferException { if (!want_fallback) fail("server doesn't support IXFR"); logxfr("falling back to AXFR"); qtype = Type.AXFR; state = INITIALSOA; } private void parseRR(Record rec) throws ZoneTransferException { int type = rec.getType(); Delta delta; switch (state) { case INITIALSOA: if (type != Type.SOA) fail("missing initial SOA"); initialsoa = rec; // Remember the serial number in the initial SOA; we need it // to recognize the end of an IXFR. end_serial = getSOASerial(rec); if (qtype == Type.IXFR && Serial.compare(end_serial, ixfr_serial) <= 0) { logxfr("up to date"); state = END; break; } state = FIRSTDATA; break; case FIRSTDATA: // If the transfer begins with 1 SOA, it's an AXFR. // If it begins with 2 SOAs, it's an IXFR. if (qtype == Type.IXFR && type == Type.SOA && getSOASerial(rec) == ixfr_serial) { rtype = Type.IXFR; handler.startIXFR(); logxfr("got incremental response"); state = IXFR_DELSOA; } else { - rtype = Type.IXFR; + rtype = Type.AXFR; handler.startAXFR(); handler.handleRecord(initialsoa); logxfr("got nonincremental response"); state = AXFR; } parseRR(rec); // Restart... return; case IXFR_DELSOA: handler.startIXFRDeletes(rec); state = IXFR_DEL; break; case IXFR_DEL: if (type == Type.SOA) { current_serial = getSOASerial(rec); state = IXFR_ADDSOA; parseRR(rec); // Restart... return; } handler.handleRecord(rec); break; case IXFR_ADDSOA: handler.startIXFRAdds(rec); state = IXFR_ADD; break; case IXFR_ADD: if (type == Type.SOA) { long soa_serial = getSOASerial(rec); if (soa_serial == end_serial) { state = END; break; } else if (soa_serial != current_serial) { fail("IXFR out of sync: expected serial " + current_serial + " , got " + soa_serial); } else { state = IXFR_DELSOA; parseRR(rec); // Restart... return; } } handler.handleRecord(rec); break; case AXFR: // Old BINDs sent cross class A records for non IN classes. if (type == Type.A && rec.getDClass() != dclass) break; handler.handleRecord(rec); if (type == Type.SOA) { state = END; } break; case END: fail("extra data"); break; default: fail("invalid state"); break; } } private void closeConnection() { try { if (client != null) client.cleanup(); } catch (IOException e) { } } private Message parseMessage(byte [] b) throws WireParseException { try { return new Message(b); } catch (IOException e) { if (e instanceof WireParseException) throw (WireParseException) e; throw new WireParseException("Error parsing message"); } } private void doxfr() throws IOException, ZoneTransferException { sendQuery(); while (state != END) { byte [] in = client.recv(); Message response = parseMessage(in); if (response.getHeader().getRcode() == Rcode.NOERROR && verifier != null) { TSIGRecord tsigrec = response.getTSIG(); int error = verifier.verify(response, in); if (error != Rcode.NOERROR) fail("TSIG failure"); } Record [] answers = response.getSectionArray(Section.ANSWER); if (state == INITIALSOA) { int rcode = response.getRcode(); if (rcode != Rcode.NOERROR) { if (qtype == Type.IXFR && rcode == Rcode.NOTIMP) { fallback(); doxfr(); return; } fail(Rcode.string(rcode)); } Record question = response.getQuestion(); if (question != null && question.getType() != qtype) { fail("invalid question section"); } if (answers.length == 0 && qtype == Type.IXFR) { fallback(); doxfr(); return; } } for (int i = 0; i < answers.length; i++) { parseRR(answers[i]); } if (state == END && verifier != null && !response.isVerified()) fail("last message must be signed"); } } /** * Does the zone transfer. * @param handler The callback object that handles the zone transfer data. * @throws IOException The zone transfer failed to due an IO problem. * @throws ZoneTransferException The zone transfer failed to due a problem * with the zone transfer itself. */ public void run(ZoneTransferHandler handler) throws IOException, ZoneTransferException { this.handler = handler; try { openConnection(); doxfr(); } finally { closeConnection(); } } /** * Does the zone transfer. * @return A list, which is either an AXFR-style response (List of Records), * and IXFR-style response (List of Deltas), or null, which indicates that * an IXFR was performed and the zone is up to date. * @throws IOException The zone transfer failed to due an IO problem. * @throws ZoneTransferException The zone transfer failed to due a problem * with the zone transfer itself. */ public List run() throws IOException, ZoneTransferException { BasicHandler handler = new BasicHandler(); run(handler); if (handler.axfr != null) return handler.axfr; return handler.ixfr; } private BasicHandler getBasicHandler() throws IllegalArgumentException { if (handler instanceof BasicHandler) return (BasicHandler) handler; throw new IllegalArgumentException("ZoneTransferIn used callback " + "interface"); } /** * Returns true if the response is an AXFR-style response (List of Records). * This will be true if either an IXFR was performed, an IXFR was performed * and the server provided a full zone transfer, or an IXFR failed and * fallback to AXFR occurred. */ public boolean isAXFR() { return (rtype == Type.AXFR); } /** * Gets the AXFR-style response. * @throws IllegalArgumentException The transfer used the callback interface, * so the response was not stored. */ public List getAXFR() { BasicHandler handler = getBasicHandler(); return handler.axfr; } /** * Returns true if the response is an IXFR-style response (List of Deltas). * This will be true only if an IXFR was performed and the server provided * an incremental zone transfer. */ public boolean isIXFR() { return (rtype == Type.IXFR); } /** * Gets the IXFR-style response. * @throws IllegalArgumentException The transfer used the callback interface, * so the response was not stored. */ public List getIXFR() { BasicHandler handler = getBasicHandler(); return handler.ixfr; } /** * Returns true if the response indicates that the zone is up to date. * This will be true only if an IXFR was performed. * @throws IllegalArgumentException The transfer used the callback interface, * so the response was not stored. */ public boolean isCurrent() { BasicHandler handler = getBasicHandler(); return (handler.axfr == null && handler.ixfr == null); } }
true
true
private void parseRR(Record rec) throws ZoneTransferException { int type = rec.getType(); Delta delta; switch (state) { case INITIALSOA: if (type != Type.SOA) fail("missing initial SOA"); initialsoa = rec; // Remember the serial number in the initial SOA; we need it // to recognize the end of an IXFR. end_serial = getSOASerial(rec); if (qtype == Type.IXFR && Serial.compare(end_serial, ixfr_serial) <= 0) { logxfr("up to date"); state = END; break; } state = FIRSTDATA; break; case FIRSTDATA: // If the transfer begins with 1 SOA, it's an AXFR. // If it begins with 2 SOAs, it's an IXFR. if (qtype == Type.IXFR && type == Type.SOA && getSOASerial(rec) == ixfr_serial) { rtype = Type.IXFR; handler.startIXFR(); logxfr("got incremental response"); state = IXFR_DELSOA; } else { rtype = Type.IXFR; handler.startAXFR(); handler.handleRecord(initialsoa); logxfr("got nonincremental response"); state = AXFR; } parseRR(rec); // Restart... return; case IXFR_DELSOA: handler.startIXFRDeletes(rec); state = IXFR_DEL; break; case IXFR_DEL: if (type == Type.SOA) { current_serial = getSOASerial(rec); state = IXFR_ADDSOA; parseRR(rec); // Restart... return; } handler.handleRecord(rec); break; case IXFR_ADDSOA: handler.startIXFRAdds(rec); state = IXFR_ADD; break; case IXFR_ADD: if (type == Type.SOA) { long soa_serial = getSOASerial(rec); if (soa_serial == end_serial) { state = END; break; } else if (soa_serial != current_serial) { fail("IXFR out of sync: expected serial " + current_serial + " , got " + soa_serial); } else { state = IXFR_DELSOA; parseRR(rec); // Restart... return; } } handler.handleRecord(rec); break; case AXFR: // Old BINDs sent cross class A records for non IN classes. if (type == Type.A && rec.getDClass() != dclass) break; handler.handleRecord(rec); if (type == Type.SOA) { state = END; } break; case END: fail("extra data"); break; default: fail("invalid state"); break; } }
private void parseRR(Record rec) throws ZoneTransferException { int type = rec.getType(); Delta delta; switch (state) { case INITIALSOA: if (type != Type.SOA) fail("missing initial SOA"); initialsoa = rec; // Remember the serial number in the initial SOA; we need it // to recognize the end of an IXFR. end_serial = getSOASerial(rec); if (qtype == Type.IXFR && Serial.compare(end_serial, ixfr_serial) <= 0) { logxfr("up to date"); state = END; break; } state = FIRSTDATA; break; case FIRSTDATA: // If the transfer begins with 1 SOA, it's an AXFR. // If it begins with 2 SOAs, it's an IXFR. if (qtype == Type.IXFR && type == Type.SOA && getSOASerial(rec) == ixfr_serial) { rtype = Type.IXFR; handler.startIXFR(); logxfr("got incremental response"); state = IXFR_DELSOA; } else { rtype = Type.AXFR; handler.startAXFR(); handler.handleRecord(initialsoa); logxfr("got nonincremental response"); state = AXFR; } parseRR(rec); // Restart... return; case IXFR_DELSOA: handler.startIXFRDeletes(rec); state = IXFR_DEL; break; case IXFR_DEL: if (type == Type.SOA) { current_serial = getSOASerial(rec); state = IXFR_ADDSOA; parseRR(rec); // Restart... return; } handler.handleRecord(rec); break; case IXFR_ADDSOA: handler.startIXFRAdds(rec); state = IXFR_ADD; break; case IXFR_ADD: if (type == Type.SOA) { long soa_serial = getSOASerial(rec); if (soa_serial == end_serial) { state = END; break; } else if (soa_serial != current_serial) { fail("IXFR out of sync: expected serial " + current_serial + " , got " + soa_serial); } else { state = IXFR_DELSOA; parseRR(rec); // Restart... return; } } handler.handleRecord(rec); break; case AXFR: // Old BINDs sent cross class A records for non IN classes. if (type == Type.A && rec.getDClass() != dclass) break; handler.handleRecord(rec); if (type == Type.SOA) { state = END; } break; case END: fail("extra data"); break; default: fail("invalid state"); break; } }
diff --git a/appinventor/appengine/src/com/google/appinventor/client/explorer/commands/ShowBarcodeCommand.java b/appinventor/appengine/src/com/google/appinventor/client/explorer/commands/ShowBarcodeCommand.java index 39ca0de6..5a64fdd9 100644 --- a/appinventor/appengine/src/com/google/appinventor/client/explorer/commands/ShowBarcodeCommand.java +++ b/appinventor/appengine/src/com/google/appinventor/client/explorer/commands/ShowBarcodeCommand.java @@ -1,109 +1,109 @@ // -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt package com.google.appinventor.client.explorer.commands; import com.google.appinventor.client.Ode; import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.output.OdeLog; import com.google.appinventor.shared.rpc.ServerLayout; import com.google.appinventor.shared.rpc.project.ProjectNode; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.VerticalPanel; /** * Command for displaying a barcode for the target of a project. * * <p/>This command is often chained with SaveAllEditorsCommand and BuildCommand. * * @author [email protected] (Mark Friedman) */ public class ShowBarcodeCommand extends ChainableCommand { private static final String CHARTSERVER_BARCODE_URI = "http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl="; // The build target private String target; /** * Creates a new command for showing a barcode for the target of a project. * * @param target the build target */ public ShowBarcodeCommand(String target) { // Since we don't know when the barcode dialog is finished, we can't // support a command after this one. super(null); // no next command this.target = target; } @Override public boolean willCallExecuteNextCommand() { return false; } @Override public void execute(final ProjectNode node) { // Display a barcode for an url pointing at our server's download servlet String barcodeUrl = CHARTSERVER_BARCODE_URI + GWT.getModuleBaseURL() + ServerLayout.genRelativeDownloadPath(node.getProjectId(), target); OdeLog.log("Barcode url is: " + barcodeUrl); new BarcodeDialogBox(node.getName(), barcodeUrl).center(); } static class BarcodeDialogBox extends DialogBox { BarcodeDialogBox(String projectName, String appInstallUrl) { super(false, true); setStylePrimaryName("ode-DialogBox"); setText(MESSAGES.barcodeTitle(projectName)); ClickHandler buttonHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); } }; Button cancelButton = new Button(MESSAGES.cancelButton()); cancelButton.addClickHandler(buttonHandler); Button okButton = new Button(MESSAGES.okButton()); okButton.addClickHandler(buttonHandler); Image barcodeImage = new Image(appInstallUrl); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER); HTML warningLabel = new HTML(MESSAGES.barcodeWarning( Ode.getInstance().getUser().getUserEmail(), - "<a href=\"" + Ode.APP_INVENTOR_DOCS_URL + - "/learn/userfaq.html\" target=\"_blank\">", + "<a href=\"" + "http://appinventor.mit.edu/explore/ai2/share.html" + + "\" target=\"_blank\">", "</a>")); warningLabel.setWordWrap(true); warningLabel.setWidth("200px"); // set width to get the text to wrap HorizontalPanel warningPanel = new HorizontalPanel(); warningPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_LEFT); warningPanel.add(warningLabel); // The cancel button is removed from the panel since it has no meaning in this // context. But the logic is still here in case we want to restore it, and as // an example of how to code this stuff in GWT. // buttonPanel.add(cancelButton); buttonPanel.add(okButton); buttonPanel.setSize("100%", "24px"); VerticalPanel contentPanel = new VerticalPanel(); contentPanel.add(barcodeImage); contentPanel.add(buttonPanel); contentPanel.add(warningPanel); // contentPanel.setSize("320px", "100%"); add(contentPanel); } } }
true
true
BarcodeDialogBox(String projectName, String appInstallUrl) { super(false, true); setStylePrimaryName("ode-DialogBox"); setText(MESSAGES.barcodeTitle(projectName)); ClickHandler buttonHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); } }; Button cancelButton = new Button(MESSAGES.cancelButton()); cancelButton.addClickHandler(buttonHandler); Button okButton = new Button(MESSAGES.okButton()); okButton.addClickHandler(buttonHandler); Image barcodeImage = new Image(appInstallUrl); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER); HTML warningLabel = new HTML(MESSAGES.barcodeWarning( Ode.getInstance().getUser().getUserEmail(), "<a href=\"" + Ode.APP_INVENTOR_DOCS_URL + "/learn/userfaq.html\" target=\"_blank\">", "</a>")); warningLabel.setWordWrap(true); warningLabel.setWidth("200px"); // set width to get the text to wrap HorizontalPanel warningPanel = new HorizontalPanel(); warningPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_LEFT); warningPanel.add(warningLabel); // The cancel button is removed from the panel since it has no meaning in this // context. But the logic is still here in case we want to restore it, and as // an example of how to code this stuff in GWT. // buttonPanel.add(cancelButton); buttonPanel.add(okButton); buttonPanel.setSize("100%", "24px"); VerticalPanel contentPanel = new VerticalPanel(); contentPanel.add(barcodeImage); contentPanel.add(buttonPanel); contentPanel.add(warningPanel); // contentPanel.setSize("320px", "100%"); add(contentPanel); }
BarcodeDialogBox(String projectName, String appInstallUrl) { super(false, true); setStylePrimaryName("ode-DialogBox"); setText(MESSAGES.barcodeTitle(projectName)); ClickHandler buttonHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); } }; Button cancelButton = new Button(MESSAGES.cancelButton()); cancelButton.addClickHandler(buttonHandler); Button okButton = new Button(MESSAGES.okButton()); okButton.addClickHandler(buttonHandler); Image barcodeImage = new Image(appInstallUrl); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER); HTML warningLabel = new HTML(MESSAGES.barcodeWarning( Ode.getInstance().getUser().getUserEmail(), "<a href=\"" + "http://appinventor.mit.edu/explore/ai2/share.html" + "\" target=\"_blank\">", "</a>")); warningLabel.setWordWrap(true); warningLabel.setWidth("200px"); // set width to get the text to wrap HorizontalPanel warningPanel = new HorizontalPanel(); warningPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_LEFT); warningPanel.add(warningLabel); // The cancel button is removed from the panel since it has no meaning in this // context. But the logic is still here in case we want to restore it, and as // an example of how to code this stuff in GWT. // buttonPanel.add(cancelButton); buttonPanel.add(okButton); buttonPanel.setSize("100%", "24px"); VerticalPanel contentPanel = new VerticalPanel(); contentPanel.add(barcodeImage); contentPanel.add(buttonPanel); contentPanel.add(warningPanel); // contentPanel.setSize("320px", "100%"); add(contentPanel); }
diff --git a/src/tconstruct/util/config/PHConstruct.java b/src/tconstruct/util/config/PHConstruct.java index a1c2552f8..5858e9b50 100644 --- a/src/tconstruct/util/config/PHConstruct.java +++ b/src/tconstruct/util/config/PHConstruct.java @@ -1,732 +1,732 @@ package tconstruct.util.config; import java.io.File; import java.io.IOException; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.Property; import tconstruct.TConstruct; import tconstruct.library.tools.AbilityHelper; public class PHConstruct { public static void initProps (File location) { /* Here we will set up the config file for the mod * First: Create a folder inside the config folder * Second: Create the actual config file * Note: Configs are a pain, but absolutely necessary for every mod. */ File newFile = new File(location + "/TinkersWorkshop.txt"); /* Some basic debugging will go a long way */ try { newFile.createNewFile(); } catch (IOException e) { TConstruct.logger.severe("Could not create configuration file for TConstruct. Reason:"); TConstruct.logger.severe(e.getLocalizedMessage()); } /* [Forge] Configuration class, used as config method */ Configuration config = new Configuration(newFile); cfglocation = location; /* Load the configuration file */ config.load(); /* Define the mod's IDs. * Avoid values below 4096 for items and in the 250-450 range for blocks */ superfunWorld = config.get("Superfun", "All the world is Superfun", false).getBoolean(false); keepHunger = config.get("Difficulty Changes", "Keep hunger on death", true).getBoolean(true); keepLevels = config.get("Difficulty Changes", "Keep levels on death", true).getBoolean(true); beginnerBook = config.get("Difficulty Changes", "Spawn beginner book", true).getBoolean(true); enableTWood = config.get("Difficulty Changes", "Enable mod wooden tools", true).getBoolean(true); enableTStone = config.get("Difficulty Changes", "Enable mod stone tools", true).getBoolean(true); enableTCactus = config.get("Difficulty Changes", "Enable mod cactus tools", true).getBoolean(true); enableTBone = config.get("Difficulty Changes", "Enable mod bone tools", true).getBoolean(true); enableTFlint = config.get("Difficulty Changes", "Enable mod flint tools", true).getBoolean(true); enableTNetherrack = config.get("Difficulty Changes", "Enable mod netherrack tools", true).getBoolean(true); enableTSlime = config.get("Difficulty Changes", "Enable mod slime tools", true).getBoolean(true); enableTPaper = config.get("Difficulty Changes", "Enable mod paper tools", true).getBoolean(true); enableTBlueSlime = config.get("Difficulty Changes", "Enable mod blue slime tools", true).getBoolean(true); craftMetalTools = config.get("Difficulty Changes", "Craft metals with Wood Patterns", false).getBoolean(false); vanillaMetalBlocks = config.get("Difficulty Changes", "Craft vanilla metal blocks", true).getBoolean(true); lavaFortuneInteraction = config.get("Difficulty Changes", "Enable Auto-Smelt and Fortune interaction", true).getBoolean(true); removeVanillaToolRecipes = config.get("Difficulty Changes", "Remove Vanilla Tool Recipes", false).getBoolean(false); stencilTableCrafting = config.get("Difficulty Changes", "Craft Stencil Tables", true).getBoolean(true); miningLevelIncrease = config.get("Difficulty Changes", "Modifiers increase Mining Level", true).getBoolean(true); denyMattock = config.get("Difficulty Changes", "Deny creation of non-metal mattocks", false).getBoolean(false); ingotsPerOre = config.get("Smeltery Output Modification", "Ingots per ore", 2, "Number of ingots returned from smelting ores in the smeltery").getInt(2); - ingotsBronzeAlloy = config.get("Smeltery Output Modification", "Bronze ingot return", 4, "Number of ingots returned from smelting Bronze in the smeltery").getInt(4); + ingotsBronzeAlloy = config.get("Smeltery Output Modification", "Bronze ingot return", 3, "Number of ingots returned from smelting Bronze in the smeltery").getInt(3); ingotsAluminumBrassAlloy = config.get("Smeltery Output Modification", "Aluminum Brass ingot return", 4, "Number of ingots returned from smelting Aluminum Brass in the smeltery").getInt(4); ingotsAlumiteAlloy = config.get("Smeltery Output Modification", "Alumite ingot return", 3, "Number of ingots returned from smelting Alumite in the smeltery").getInt(3); ingotsManyullynAlloy = config.get("Smeltery Output Modification", "Manyullyn ingot return", 1, "Number of ingots returned from smelting Manyullyn in the smeltery").getInt(1); //1467-1489 woodStation = config.getBlock("Wood Tool Station", 1471).getInt(1471); heldItemBlock = config.getBlock("Held Item Block", 1472).getInt(1472); lavaTank = config.getBlock("Lava Tank", 1473).getInt(1473); smeltery = config.getBlock("Smeltery", 1474).getInt(1474); oreSlag = config.getBlock("Ores Slag", 1475).getInt(1475); craftedSoil = config.getBlock("Special Soil", 1476).getInt(1476); searedTable = config.getBlock("Seared Table", 1477).getInt(1477); metalBlock = config.getBlock("Metal Storage", 1478).getInt(1478); /*metalFlowing = config.getBlock("Liquid Metal Flowing", 1479).getInt(1479); metalStill = config.getBlock("Liquid Metal Still", 1480).getInt(1480);*/ multiBrick = config.getBlock("Multi Brick", 1481).getInt(1481); stoneTorch = config.getBlock("Stone Torch", 1484).getInt(1484); stoneLadder = config.getBlock("Stone Ladder", 1479).getInt(1479); oreBerry = config.getBlock("Ore Berry One", 1485).getInt(1485); oreBerrySecond = config.getBlock("Ore Berry Two", 1486).getInt(1486); oreGravel = config.getBlock("Ores Gravel", 1488).getInt(1488); speedBlock = config.getBlock("Speed Block", 1489).getInt(1489); landmine = config.getBlock("Landmine", 1470).getInt(1470); toolForge = config.getBlock("Tool Forge", 1468).getInt(1468); multiBrickFancy = config.getBlock("Multi Brick Fancy", 1467).getInt(1467); barricadeOak = config.getBlock("Oak Barricade", 1469).getInt(1469); barricadeSpruce = config.getBlock("Spruce Barricade", 1482).getInt(1482); barricadeBirch = config.getBlock("Birch Barricade", 1483).getInt(1483); barricadeJungle = config.getBlock("Jungle Barricade", 1487).getInt(1487); slimeChannel = config.getBlock("Slime Channel", 3190).getInt(3190); slimePad = config.getBlock("Slime Pad", 3191).getInt(3191); furnaceSlab = config.getBlock("Furnace Slab", 3192).getInt(3192); //Thermal Expansion moltenSilver = config.getBlock("Molten Silver", 3195).getInt(3195); moltenLead = config.getBlock("Molten Lead", 3196).getInt(3196); moltenNickel = config.getBlock("Molten Nickel", 3197).getInt(3197); moltenShiny = config.getBlock("Molten Platinum", 3198).getInt(3198); moltenInvar = config.getBlock("Molten Invar", 3199).getInt(3199); moltenElectrum = config.getBlock("Molten Electrum", 3200).getInt(3200); moltenIron = config.getBlock("Molten Iron", 3201).getInt(3201); moltenGold = config.getBlock("Molten Gold", 3202).getInt(3202); moltenCopper = config.getBlock("Molten Copper", 3203).getInt(3203); moltenTin = config.getBlock("Molten Tin", 3204).getInt(3204); moltenAluminum = config.getBlock("Molten Aluminum", 3205).getInt(3205); moltenCobalt = config.getBlock("Molten Cobalt", 3206).getInt(3206); moltenArdite = config.getBlock("Molten Ardite", 3207).getInt(3207); moltenBronze = config.getBlock("Molten Bronze", 3208).getInt(3208); moltenAlubrass = config.getBlock("Molten Aluminum Brass", 3209).getInt(3209); moltenManyullyn = config.getBlock("Molten Manyullyn", 3210).getInt(3210); moltenAlumite = config.getBlock("Molten Alumite", 3211).getInt(3211); moltenObsidian = config.getBlock("Molten Obsidian", 3212).getInt(3212); moltenSteel = config.getBlock("Molten Steel", 3213).getInt(3213); moltenGlass = config.getBlock("Molten Glass", 3214).getInt(3214); moltenStone = config.getBlock("Molten Stone", 3215).getInt(3215); moltenEmerald = config.getBlock("Molten Emerald", 3216).getInt(3216); blood = config.getBlock("Liquid Cow", 3217).getInt(3217); moltenEnder = config.getBlock("Molten Ender", 3218).getInt(3218); // signalBus = config.getBlock("Signal Bus", 3221).getInt(3221); // signalTerminal = config.getBlock("Signal Terminal", 3222).getInt(3222); glass = config.getBlock("Clear Glass", 3223).getInt(3223); stainedGlass = config.getBlock("Stained Glass", 3224).getInt(3224); stainedGlassClear = config.getBlock("Clear Stained Glass", 3225).getInt(3225); // redstoneMachine = config.getBlock("Redstone Machines", 3226).getInt(3226); // Migrated to TMechworks dryingRack = config.getBlock("Drying Rack", 3227).getInt(3227); glassPane = config.getBlock("Glass Pane", 3228).getInt(3228); stainedGlassClearPane = config.getBlock("Clear Stained Glass Pane", 3229).getInt(3229); searedSlab = config.getBlock("Seared Slab", 3230).getInt(3230); speedSlab = config.getBlock("Speed Slab", 3231).getInt(3231); punji = config.getBlock("Punji", 3232).getInt(3232); woodCrafter = config.getBlock("Crafting Station", 3233).getInt(3233); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); //3246 castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); airTank = config.getBlock("Air Tank", 3246).getInt(3246); slimeExplosive = config.getBlock("SDX", 3247).getInt(3247); castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); woodenRail = config.getBlock("Wooden Rail", 3250).getInt(3250); //3251+ belongs to Natura. Go backwards! manual = config.getItem("Patterns and Misc", "Tinker's Manual", 14018).getInt(14018); blankPattern = config.getItem("Patterns and Misc", "Blank Patterns", 14019).getInt(14019); materials = config.getItem("Patterns and Misc", "Materials", 14020).getInt(14020); toolRod = config.getItem("Patterns and Misc", "Tool Rod", 14021).getInt(14021); toolShard = config.getItem("Patterns and Misc", "Tool Shard", 14022).getInt(14022); woodPattern = config.getItem("Patterns and Misc", "Wood Pattern", 14023).getInt(14023); metalPattern = config.getItem("Patterns and Misc", "Metal Pattern", 14024).getInt(14024); armorPattern = config.getItem("Patterns and Misc", "Armor Pattern", 14025).getInt(14025); pickaxeHead = config.getItem("Tool Parts", "Pickaxe Head", 14026).getInt(14026); shovelHead = config.getItem("Tool Parts", "Shovel Head", 14027).getInt(14027); axeHead = config.getItem("Tool Parts", "Axe Head", 14028).getInt(14028); hoeHead = config.getItem("Tool Parts", "Hoe Head", 14029).getInt(14029); swordBlade = config.getItem("Tool Parts", "Sword Blade", 14030).getInt(14030); largeGuard = config.getItem("Tool Parts", "Large Guard", 14031).getInt(14031); medGuard = config.getItem("Tool Parts", "Medium Guard", 14032).getInt(14032); crossbar = config.getItem("Tool Parts", "Crossbar", 14033).getInt(14033); binding = config.getItem("Tool Parts", "Tool Binding", 14034).getInt(14034); frypanHead = config.getItem("Tool Parts", "Frypan Head", 14035).getInt(14035); signHead = config.getItem("Tool Parts", "Sign Head", 14036).getInt(14036); lumberHead = config.getItem("Tool Parts", "Lumber Axe Head", 14037).getInt(14037); knifeBlade = config.getItem("Tool Parts", "Knife Blade", 14038).getInt(14038); chiselHead = config.getItem("Tool Parts", "Chisel Head", 14039).getInt(14039); scytheBlade = config.getItem("Tool Parts", "Scythe Head", 14040).getInt(14040); toughBinding = config.getItem("Tool Parts", "Tough Binding", 14041).getInt(14041); toughRod = config.getItem("Tool Parts", "Tough Rod", 14042).getInt(14042); largeSwordBlade = config.getItem("Tool Parts", "Large Sword Blade", 14043).getInt(14043); largePlate = config.getItem("Tool Parts", "Large Plate", 14044).getInt(14044); excavatorHead = config.getItem("Tool Parts", "Excavator Head", 14045).getInt(14045); hammerHead = config.getItem("Tool Parts", "Hammer Head", 14046).getInt(14046); fullGuard = config.getItem("Tool Parts", "Full Guard", 14047).getInt(14047); bowstring = config.getItem("Tool Parts", "Bowstring", 14048).getInt(14048); arrowhead = config.getItem("Tool Parts", "Arrowhead", 14049).getInt(14049); fletching = config.getItem("Tool Parts", "Fletching", 14050).getInt(14050); pickaxe = config.getItem("Tools", "Pickaxe", 14051).getInt(14051); shovel = config.getItem("Tools", "Shovel", 14052).getInt(14052); axe = config.getItem("Tools", "Axe", 14053).getInt(14053); hoe = config.getItem("Tools", "Hoe", 14054).getInt(14054); broadsword = config.getItem("Tools", "Broadsword", 14055).getInt(14055); rapier = config.getItem("Tools", "Rapier", 14057).getInt(14057); longsword = config.getItem("Tools", "Longsword", 14056).getInt(14056); dagger = config.getItem("Tools", "Dagger", 14065).getInt(14065); frypan = config.getItem("Tools", "Frying Pan", 14058).getInt(14058); battlesign = config.getItem("Tools", "Battlesign", 14059).getInt(14059); mattock = config.getItem("Tools", "Mattock", 14060).getInt(14060); lumberaxe = config.getItem("Tools", "Lumber Axe", 14061).getInt(14061); longbow = config.getItem("Tools", "Longbow", 14062).getInt(14062); shortbow = config.getItem("Tools", "Shortbow", 14063).getInt(14063); potionLauncher = config.getItem("Tools", "Potion Launcher", 14064).getInt(14064); chisel = config.getItem("Tools", "Chisel", 14066).getInt(14066); scythe = config.getItem("Tools", "Scythe", 14067).getInt(14067); cleaver = config.getItem("Tools", "Cleaver", 14068).getInt(14068); excavator = config.getItem("Tools", "Excavator", 14069).getInt(14069); hammer = config.getItem("Tools", "Hammer", 14070).getInt(14070); battleaxe = config.getItem("Tools", "Battleaxe", 14071).getInt(14071); cutlass = config.getItem("Tools", "Cutlass", 14072).getInt(14072); arrow = config.getItem("Tools", "Arrow", 14073).getInt(14073); buckets = config.getItem("Patterns and Misc", "Buckets", 14101).getInt(14101); uselessItem = config.getItem("Patterns and Misc", "Title Icon", 14102).getInt(14102); slimefood = config.getItem("Patterns and Misc", "Strange Food", 14103).getInt(14103); oreChunks = config.getItem("Patterns and Misc", "Ore Chunks", 14104).getInt(14104); heartCanister = config.getItem("Equipables", "Heart Canister", 14105).getInt(14105); diamondApple = config.getItem("Patterns and Misc", "Jeweled Apple", 14107).getInt(14107); woodHelmet = config.getItem("Equipables", "Wooden Helmet", 14106).getInt(14106); woodChestplate = config.getItem("Equipables", "Wooden Chestplate", 14108).getInt(14108); woodPants = config.getItem("Equipables", "Wooden Pants", 14109).getInt(14109); woodBoots = config.getItem("Equipables", "Wooden Boots", 14110).getInt(14110); glove = config.getItem("Equipables", "Gloves", 14111).getInt(14111); knapsack = config.getItem("Equipables", "Knapsack", 14112).getInt(14112); goldHead = config.getItem("Patterns and Misc", "Golden Head", 14113).getInt(14113); jerky = config.getItem("Patterns and Misc", "Jerky", 14115).getInt(14115); // spoolWire = config.getItem("Logic", "SpoolWire", 14120).getInt(14120); // lengthWire = config.getItem("Logic", "LengthWire", 14121).getInt(14121); boolean ic2 = true; boolean xycraft = true; try { Class c = Class.forName("ic2.core.IC2"); ic2 = false; } catch (Exception e) { } try { Class c = Class.forName("soaryn.xycraft.core.XyCraft"); xycraft = false; } catch (Exception e) { } generateCopper = config.get("Worldgen Disabler", "Generate Copper", ic2).getBoolean(ic2); generateTin = config.get("Worldgen Disabler", "Generate Tin", ic2).getBoolean(ic2); generateAluminum = config.get("Worldgen Disabler", "Generate Aluminum", xycraft).getBoolean(xycraft); generateNetherOres = config.get("Worldgen Disabler", "Generate Cobalt and Ardite", true).getBoolean(true); generateIronSurface = config.get("Worldgen Disabler", "Generate Surface Iron", true).getBoolean(true); generateGoldSurface = config.get("Worldgen Disabler", "Generate Surface Gold", true).getBoolean(true); generateCopperSurface = config.get("Worldgen Disabler", "Generate Surface Copper", true).getBoolean(true); generateTinSurface = config.get("Worldgen Disabler", "Generate Surface Tin", true).getBoolean(true); generateAluminumSurface = config.get("Worldgen Disabler", "Generate Surface Aluminum", true).getBoolean(true); generateIronBush = config.get("Worldgen Disabler", "Generate Iron Bushes", true).getBoolean(true); generateGoldBush = config.get("Worldgen Disabler", "Generate Gold Bushes", true).getBoolean(true); generateCopperBush = config.get("Worldgen Disabler", "Generate Copper Bushes", true).getBoolean(true); generateTinBush = config.get("Worldgen Disabler", "Generate Tin Bushes", true).getBoolean(true); generateAluminumBush = config.get("Worldgen Disabler", "Generate Aluminum Bushes", true).getBoolean(true); generateEssenceBush = config.get("Worldgen Disabler", "Generate Essence Bushes", true).getBoolean(true); addToVillages = config.get("Worldgen Disabler", "Add Village Generation", true).getBoolean(true); copperuDensity = config.get("Worldgen", "Copper Underground Density", 2, "Density: Chances per chunk").getInt(2); tinuDensity = config.get("Worldgen", "Tin Underground Density", 2).getInt(2); aluminumuDensity = config.get("Worldgen", "Aluminum Underground Density", 3).getInt(3); netherDensity = config.get("Worldgen", "Nether Ores Density", 8).getInt(8); copperuMinY = config.get("Worldgen", "Copper Underground Min Y", 20).getInt(20); copperuMaxY = config.get("Worldgen", "Copper Underground Max Y", 60).getInt(60); tinuMinY = config.get("Worldgen", "Tin Underground Min Y", 0).getInt(0); tinuMaxY = config.get("Worldgen", "Tin Underground Max Y", 40).getInt(40); aluminumuMinY = config.get("Worldgen", "Aluminum Underground Min Y", 0).getInt(0); aluminumuMaxY = config.get("Worldgen", "Aluminum Underground Max Y", 64).getInt(64); ironsRarity = config.get("Worldgen", "Iron Surface Rarity", 400).getInt(400); goldsRarity = config.get("Worldgen", "Gold Surface Rarity", 900).getInt(900); coppersRarity = config.get("Worldgen", "Copper Surface Rarity", 100, "Rarity: 1/num to generate in chunk").getInt(100); tinsRarity = config.get("Worldgen", "Tin Surface Rarity", 100).getInt(100); aluminumsRarity = config.get("Worldgen", "Aluminum Surface Rarity", 50).getInt(50); cobaltsRarity = config.get("Worldgen", "Cobalt Surface Rarity", 2000).getInt(2000); ironBushDensity = config.get("Worldgen", "Iron Bush Density", 1).getInt(1); goldBushDensity = config.get("Worldgen", "Gold Bush Density", 1).getInt(1); copperBushDensity = config.get("Worldgen", "Copper Bush Density", 2).getInt(2); tinBushDensity = config.get("Worldgen", "Tin Bush Density", 2).getInt(2); aluminumBushDensity = config.get("Worldgen", "Aluminum Bush Density", 2).getInt(2); silverBushDensity = config.get("Worldgen", "Silver Bush Density", 1).getInt(1); ironBushRarity = config.get("Worldgen", "Iron Bush Rarity", 5).getInt(5); goldBushRarity = config.get("Worldgen", "Gold Bush Rarity", 8).getInt(8); copperBushRarity = config.get("Worldgen", "Copper Bush Rarity", 3).getInt(3); tinBushRarity = config.get("Worldgen", "Tin Bush Rarity", 3).getInt(3); aluminumBushRarity = config.get("Worldgen", "Aluminum Bush Rarity", 2).getInt(2); essenceBushRarity = config.get("Worldgen", "Essence Bush Rarity", 6).getInt(6); copperBushMinY = config.get("Worldgen", "Copper Bush Min Y", 20).getInt(20); copperBushMaxY = config.get("Worldgen", "Copper Bush Max Y", 60).getInt(60); tinBushMinY = config.get("Worldgen", "Tin Bush Min Y", 0).getInt(0); tinBushMaxY = config.get("Worldgen", "Tin Bush Max Y", 40).getInt(40); aluminumBushMinY = config.get("Worldgen", "Aluminum Bush Min Y", 0).getInt(0); aluminumBushMaxY = config.get("Worldgen", "Aluminum Bush Max Y", 60).getInt(60); seaLevel = config.get("general", "Sea level", 64).getInt(64); enableHealthRegen = config.get("Ultra Hardcore Changes", "Passive Health Regen", true).getBoolean(true); goldAppleRecipe = config.get("Ultra Hardcore Changes", "Change Crafting Recipes", false, "Makes recipes for gold apples, carrots, and melon potions more expensive").getBoolean(false); dropPlayerHeads = config.get("Ultra Hardcore Changes", "Players drop heads on death", false).getBoolean(false); uhcGhastDrops = config.get("Ultra Hardcore Changes", "Change Ghast drops to Gold Ingots", false).getBoolean(false); worldBorder = config.get("Ultra Hardcore Changes", "Add World Border", false).getBoolean(false); worldBorderSize = config.get("Ultra Hardcore Changes", "World Border Radius", 1000).getInt(1000); freePatterns = config.get("Ultra Hardcore Changes", "Add Patterns to Pattern Chests", false, "Gives all tier 1 patterns when pattern chest is placed").getBoolean(false); AbilityHelper.necroticUHS = config.get("Ultra Hardcore Changes", "Necrotic modifier only heals on hostile mob kills", false).getBoolean(false); //Slime pools islandRarity = config.get("Worldgen", "Slime Island Rarity", 1450).getInt(1450); //Looks Property conTexMode = config.get("Looks", "Connected Textures Enabled", true); conTexMode.comment = "0 = disabled, 1 = enabled, 2 = enabled + ignore stained glass meta"; connectedTexturesMode = conTexMode.getInt(2); //dimension blacklist cfgDimBlackList = config.get("DimBlackList", "SlimeIslandDimBlacklist", new int[] {}, "Add dimension ID's to prevent slime islands from generating in them").getIntList(); slimeIslGenDim0Only = config.get("DimBlackList", "GenerateSlimeIslandInDim0Only", false, "True: slime islands wont generate in any ages other than overworld(if enabled); False: will generate in all non-blackisted ages").getBoolean(false); slimeIslGenDim0 = config.get("DimBlackList", "slimeIslGenDim0", true, "True: slime islands generate in overworld; False they do not generate").getBoolean(true); genIslandsFlat = config.get("DimBlacklist", "genIslandsFlat", false, "Generate slime islands in flat worlds").getBoolean(false); //Experimental functionality throwableSmeltery = config.get("Experimental", "Items can be thrown into smelteries", true).getBoolean(true); newSmeltery = config.get("Experimental", "Use new adaptive Smeltery code", false, "Warning: Very buggy").getBoolean(false); //Addon stuff isCleaverTwoHanded = config.get("Battlegear", "Can Cleavers have shields", true).getBoolean(true); isHatchetWeapon = config.get("Battlegear", "Are Hatches also weapons", true).getBoolean(true); //Achievement Properties achievementsEnabled = config.get("Achievement Properties", "AchievementsEnabled", true).getBoolean(true); /* Save the configuration file */ config.save(); File gt = new File(location + "/GregTech"); if (gt.exists()) { File gtDyn = new File(location + "/GregTech/DynamicConfig.cfg"); Configuration gtConfig = new Configuration(gtDyn); gtConfig.load(); gregtech = gtConfig.get("smelting", "tile.anvil.slightlyDamaged", false).getBoolean(false); } } //Blocks public static int woodStation; public static int toolForge; public static int heldItemBlock; public static int woodCrafter; public static int woodCrafterSlab; public static int furnaceSlab; public static int ores; public static int lavaTank; public static int smeltery; public static int searedTable; public static int castingChannel; public static int airTank; public static int craftedSoil; public static int oreSlag; public static int oreGravel; public static int metalBlock; public static int redstoneMachine; public static int dryingRack; public static int woodenRail; // public static int signalBus; // public static int signalTerminal; //Crops public static int oreBerry; public static int oreBerrySecond; public static int netherOreBerry; //Traps public static int landmine; public static int punji; public static int barricadeOak; public static int barricadeSpruce; public static int barricadeBirch; public static int barricadeJungle; public static int slimeExplosive; //InfiBlocks public static int speedBlock; public static int glass; public static int glassPane; public static int stainedGlass; public static int stainedGlassClear; public static int stainedGlassClearPane; //Liquids public static int metalFlowing; public static int metalStill; public static int moltenIron; public static int moltenGold; public static int moltenCopper; public static int moltenTin; public static int moltenAluminum; public static int moltenCobalt; public static int moltenArdite; public static int moltenBronze; public static int moltenAlubrass; public static int moltenManyullyn; public static int moltenAlumite; public static int moltenObsidian; public static int moltenSteel; public static int moltenGlass; public static int moltenStone; public static int moltenEmerald; public static int blood; public static int moltenEnder; public static int moltenSilver; //Thermal Expansion public static int moltenLead; public static int moltenNickel; public static int moltenShiny; public static int moltenInvar; public static int moltenElectrum; //Slime public static int slimePoolBlue; public static int slimeGel; public static int slimeGrass; public static int slimeTallGrass; public static int slimeLeaves; public static int slimeSapling; public static int slimeChannel; public static int slimePad; //Decoration public static int stoneTorch; public static int stoneLadder; public static int multiBrick; public static int multiBrickFancy; public static int redstoneBallRepeater; public static int searedSlab; public static int speedSlab; public static int meatBlock; public static int woolSlab1; public static int woolSlab2; //Patterns and misc public static int blankPattern; public static int materials; public static int toolRod; public static int toolShard; public static int woodPattern; public static int metalPattern; public static int armorPattern; public static int manual; public static int buckets; public static int uselessItem; public static int oreChunks; //Food public static int diamondApple; public static int slimefood; public static int jerky; //Tools public static int pickaxe; public static int shovel; public static int axe; public static int hoe; public static int broadsword; public static int longsword; public static int rapier; public static int dagger; public static int cutlass; public static int frypan; public static int battlesign; public static int longbow; public static int shortbow; public static int potionLauncher; public static int mattock; public static int lumberaxe; public static int scythe; public static int cleaver; public static int excavator; public static int hammer; public static int battleaxe; public static int chisel; public static int arrow; //Tool parts public static int swordBlade; public static int largeGuard; public static int medGuard; public static int crossbar; public static int knifeBlade; public static int fullGuard; public static int pickaxeHead; public static int axeHead; public static int shovelHead; public static int hoeHead; public static int frypanHead; public static int signHead; public static int chiselHead; public static int scytheBlade; public static int lumberHead; public static int largeSwordBlade; public static int excavatorHead; public static int hammerHead; public static int binding; public static int toughBinding; public static int toughRod; public static int largePlate; public static int bowstring; public static int arrowhead; public static int fletching; //Wearables public static int woodHelmet; public static int woodChestplate; public static int woodPants; public static int woodBoots; public static int glove; public static int knapsack; public static int heartCanister; // public static int spoolWire; // public static int lengthWire; //Ore values public static boolean generateCopper; public static boolean generateTin; public static boolean generateAluminum; public static boolean generateNetherOres; public static boolean generateIronSurface; public static boolean generateGoldSurface; public static boolean generateCopperSurface; public static boolean generateTinSurface; public static boolean generateAluminumSurface; public static boolean generateCobaltSurface; public static boolean generateIronBush; public static boolean generateGoldBush; public static boolean generateCopperBush; public static boolean generateTinBush; public static boolean generateAluminumBush; public static boolean generateEssenceBush; public static boolean addToVillages; public static int copperuDensity; public static int tinuDensity; public static int aluminumuDensity; public static int netherDensity; public static int ironsRarity; public static int goldsRarity; public static int coppersRarity; public static int tinsRarity; public static int aluminumsRarity; public static int cobaltsRarity; public static int ironBushDensity; public static int goldBushDensity; public static int copperBushDensity; public static int tinBushDensity; public static int aluminumBushDensity; public static int silverBushDensity; public static int ironBushRarity; public static int goldBushRarity; public static int copperBushRarity; public static int tinBushRarity; public static int aluminumBushRarity; public static int essenceBushRarity; public static int copperuMinY; public static int copperuMaxY; public static int tinuMinY; public static int tinuMaxY; public static int aluminumuMinY; public static int aluminumuMaxY; public static int copperBushMinY; public static int copperBushMaxY; public static int tinBushMinY; public static int tinBushMaxY; public static int aluminumBushMinY; public static int aluminumBushMaxY; public static int seaLevel; //Mobs //Difficulty modifiers public static boolean keepHunger; public static boolean keepLevels; public static boolean alphaRegen; public static boolean alphaHunger; public static boolean disableWoodTools; public static boolean disableStoneTools; public static boolean disableIronTools; public static boolean disableDiamondTools; public static boolean disableGoldTools; public static boolean enableTWood; public static boolean enableTStone; public static boolean enableTCactus; public static boolean enableTBone; public static boolean enableTFlint; public static boolean enableTNetherrack; public static boolean enableTSlime; public static boolean enableTPaper; public static boolean enableTBlueSlime; public static boolean craftMetalTools; public static boolean vanillaMetalBlocks; public static boolean removeVanillaToolRecipes; public static boolean stencilTableCrafting; public static boolean miningLevelIncrease; public static boolean denyMattock; //Smeltery Output Modification public static int ingotsPerOre; public static int ingotsBronzeAlloy; public static int ingotsAluminumBrassAlloy; public static int ingotsAlumiteAlloy; public static int ingotsManyullynAlloy; //Ultra Hardcore modifiers public static boolean enableHealthRegen; public static boolean goldAppleRecipe; public static boolean dropPlayerHeads; public static boolean uhcGhastDrops; public static boolean worldBorder; public static int worldBorderSize; public static boolean freePatterns; public static int goldHead; //Superfun public static boolean superfunWorld; public static boolean beginnerBook; public static boolean gregtech; public static boolean lavaFortuneInteraction; public static int islandRarity; //Looks public static int connectedTexturesMode; public static File cfglocation; //dimensionblacklist public static boolean slimeIslGenDim0Only; public static int[] cfgDimBlackList; public static boolean slimeIslGenDim0; public static boolean genIslandsFlat; //Experimental functionality public static boolean throwableSmeltery; public static boolean newSmeltery; //Addon stuff public static boolean isCleaverTwoHanded; public static boolean isHatchetWeapon; //Achievement options public static boolean achievementsEnabled; }
true
true
public static void initProps (File location) { /* Here we will set up the config file for the mod * First: Create a folder inside the config folder * Second: Create the actual config file * Note: Configs are a pain, but absolutely necessary for every mod. */ File newFile = new File(location + "/TinkersWorkshop.txt"); /* Some basic debugging will go a long way */ try { newFile.createNewFile(); } catch (IOException e) { TConstruct.logger.severe("Could not create configuration file for TConstruct. Reason:"); TConstruct.logger.severe(e.getLocalizedMessage()); } /* [Forge] Configuration class, used as config method */ Configuration config = new Configuration(newFile); cfglocation = location; /* Load the configuration file */ config.load(); /* Define the mod's IDs. * Avoid values below 4096 for items and in the 250-450 range for blocks */ superfunWorld = config.get("Superfun", "All the world is Superfun", false).getBoolean(false); keepHunger = config.get("Difficulty Changes", "Keep hunger on death", true).getBoolean(true); keepLevels = config.get("Difficulty Changes", "Keep levels on death", true).getBoolean(true); beginnerBook = config.get("Difficulty Changes", "Spawn beginner book", true).getBoolean(true); enableTWood = config.get("Difficulty Changes", "Enable mod wooden tools", true).getBoolean(true); enableTStone = config.get("Difficulty Changes", "Enable mod stone tools", true).getBoolean(true); enableTCactus = config.get("Difficulty Changes", "Enable mod cactus tools", true).getBoolean(true); enableTBone = config.get("Difficulty Changes", "Enable mod bone tools", true).getBoolean(true); enableTFlint = config.get("Difficulty Changes", "Enable mod flint tools", true).getBoolean(true); enableTNetherrack = config.get("Difficulty Changes", "Enable mod netherrack tools", true).getBoolean(true); enableTSlime = config.get("Difficulty Changes", "Enable mod slime tools", true).getBoolean(true); enableTPaper = config.get("Difficulty Changes", "Enable mod paper tools", true).getBoolean(true); enableTBlueSlime = config.get("Difficulty Changes", "Enable mod blue slime tools", true).getBoolean(true); craftMetalTools = config.get("Difficulty Changes", "Craft metals with Wood Patterns", false).getBoolean(false); vanillaMetalBlocks = config.get("Difficulty Changes", "Craft vanilla metal blocks", true).getBoolean(true); lavaFortuneInteraction = config.get("Difficulty Changes", "Enable Auto-Smelt and Fortune interaction", true).getBoolean(true); removeVanillaToolRecipes = config.get("Difficulty Changes", "Remove Vanilla Tool Recipes", false).getBoolean(false); stencilTableCrafting = config.get("Difficulty Changes", "Craft Stencil Tables", true).getBoolean(true); miningLevelIncrease = config.get("Difficulty Changes", "Modifiers increase Mining Level", true).getBoolean(true); denyMattock = config.get("Difficulty Changes", "Deny creation of non-metal mattocks", false).getBoolean(false); ingotsPerOre = config.get("Smeltery Output Modification", "Ingots per ore", 2, "Number of ingots returned from smelting ores in the smeltery").getInt(2); ingotsBronzeAlloy = config.get("Smeltery Output Modification", "Bronze ingot return", 4, "Number of ingots returned from smelting Bronze in the smeltery").getInt(4); ingotsAluminumBrassAlloy = config.get("Smeltery Output Modification", "Aluminum Brass ingot return", 4, "Number of ingots returned from smelting Aluminum Brass in the smeltery").getInt(4); ingotsAlumiteAlloy = config.get("Smeltery Output Modification", "Alumite ingot return", 3, "Number of ingots returned from smelting Alumite in the smeltery").getInt(3); ingotsManyullynAlloy = config.get("Smeltery Output Modification", "Manyullyn ingot return", 1, "Number of ingots returned from smelting Manyullyn in the smeltery").getInt(1); //1467-1489 woodStation = config.getBlock("Wood Tool Station", 1471).getInt(1471); heldItemBlock = config.getBlock("Held Item Block", 1472).getInt(1472); lavaTank = config.getBlock("Lava Tank", 1473).getInt(1473); smeltery = config.getBlock("Smeltery", 1474).getInt(1474); oreSlag = config.getBlock("Ores Slag", 1475).getInt(1475); craftedSoil = config.getBlock("Special Soil", 1476).getInt(1476); searedTable = config.getBlock("Seared Table", 1477).getInt(1477); metalBlock = config.getBlock("Metal Storage", 1478).getInt(1478); /*metalFlowing = config.getBlock("Liquid Metal Flowing", 1479).getInt(1479); metalStill = config.getBlock("Liquid Metal Still", 1480).getInt(1480);*/ multiBrick = config.getBlock("Multi Brick", 1481).getInt(1481); stoneTorch = config.getBlock("Stone Torch", 1484).getInt(1484); stoneLadder = config.getBlock("Stone Ladder", 1479).getInt(1479); oreBerry = config.getBlock("Ore Berry One", 1485).getInt(1485); oreBerrySecond = config.getBlock("Ore Berry Two", 1486).getInt(1486); oreGravel = config.getBlock("Ores Gravel", 1488).getInt(1488); speedBlock = config.getBlock("Speed Block", 1489).getInt(1489); landmine = config.getBlock("Landmine", 1470).getInt(1470); toolForge = config.getBlock("Tool Forge", 1468).getInt(1468); multiBrickFancy = config.getBlock("Multi Brick Fancy", 1467).getInt(1467); barricadeOak = config.getBlock("Oak Barricade", 1469).getInt(1469); barricadeSpruce = config.getBlock("Spruce Barricade", 1482).getInt(1482); barricadeBirch = config.getBlock("Birch Barricade", 1483).getInt(1483); barricadeJungle = config.getBlock("Jungle Barricade", 1487).getInt(1487); slimeChannel = config.getBlock("Slime Channel", 3190).getInt(3190); slimePad = config.getBlock("Slime Pad", 3191).getInt(3191); furnaceSlab = config.getBlock("Furnace Slab", 3192).getInt(3192); //Thermal Expansion moltenSilver = config.getBlock("Molten Silver", 3195).getInt(3195); moltenLead = config.getBlock("Molten Lead", 3196).getInt(3196); moltenNickel = config.getBlock("Molten Nickel", 3197).getInt(3197); moltenShiny = config.getBlock("Molten Platinum", 3198).getInt(3198); moltenInvar = config.getBlock("Molten Invar", 3199).getInt(3199); moltenElectrum = config.getBlock("Molten Electrum", 3200).getInt(3200); moltenIron = config.getBlock("Molten Iron", 3201).getInt(3201); moltenGold = config.getBlock("Molten Gold", 3202).getInt(3202); moltenCopper = config.getBlock("Molten Copper", 3203).getInt(3203); moltenTin = config.getBlock("Molten Tin", 3204).getInt(3204); moltenAluminum = config.getBlock("Molten Aluminum", 3205).getInt(3205); moltenCobalt = config.getBlock("Molten Cobalt", 3206).getInt(3206); moltenArdite = config.getBlock("Molten Ardite", 3207).getInt(3207); moltenBronze = config.getBlock("Molten Bronze", 3208).getInt(3208); moltenAlubrass = config.getBlock("Molten Aluminum Brass", 3209).getInt(3209); moltenManyullyn = config.getBlock("Molten Manyullyn", 3210).getInt(3210); moltenAlumite = config.getBlock("Molten Alumite", 3211).getInt(3211); moltenObsidian = config.getBlock("Molten Obsidian", 3212).getInt(3212); moltenSteel = config.getBlock("Molten Steel", 3213).getInt(3213); moltenGlass = config.getBlock("Molten Glass", 3214).getInt(3214); moltenStone = config.getBlock("Molten Stone", 3215).getInt(3215); moltenEmerald = config.getBlock("Molten Emerald", 3216).getInt(3216); blood = config.getBlock("Liquid Cow", 3217).getInt(3217); moltenEnder = config.getBlock("Molten Ender", 3218).getInt(3218); // signalBus = config.getBlock("Signal Bus", 3221).getInt(3221); // signalTerminal = config.getBlock("Signal Terminal", 3222).getInt(3222); glass = config.getBlock("Clear Glass", 3223).getInt(3223); stainedGlass = config.getBlock("Stained Glass", 3224).getInt(3224); stainedGlassClear = config.getBlock("Clear Stained Glass", 3225).getInt(3225); // redstoneMachine = config.getBlock("Redstone Machines", 3226).getInt(3226); // Migrated to TMechworks dryingRack = config.getBlock("Drying Rack", 3227).getInt(3227); glassPane = config.getBlock("Glass Pane", 3228).getInt(3228); stainedGlassClearPane = config.getBlock("Clear Stained Glass Pane", 3229).getInt(3229); searedSlab = config.getBlock("Seared Slab", 3230).getInt(3230); speedSlab = config.getBlock("Speed Slab", 3231).getInt(3231); punji = config.getBlock("Punji", 3232).getInt(3232); woodCrafter = config.getBlock("Crafting Station", 3233).getInt(3233); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); //3246 castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); airTank = config.getBlock("Air Tank", 3246).getInt(3246); slimeExplosive = config.getBlock("SDX", 3247).getInt(3247); castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); woodenRail = config.getBlock("Wooden Rail", 3250).getInt(3250); //3251+ belongs to Natura. Go backwards! manual = config.getItem("Patterns and Misc", "Tinker's Manual", 14018).getInt(14018); blankPattern = config.getItem("Patterns and Misc", "Blank Patterns", 14019).getInt(14019); materials = config.getItem("Patterns and Misc", "Materials", 14020).getInt(14020); toolRod = config.getItem("Patterns and Misc", "Tool Rod", 14021).getInt(14021); toolShard = config.getItem("Patterns and Misc", "Tool Shard", 14022).getInt(14022); woodPattern = config.getItem("Patterns and Misc", "Wood Pattern", 14023).getInt(14023); metalPattern = config.getItem("Patterns and Misc", "Metal Pattern", 14024).getInt(14024); armorPattern = config.getItem("Patterns and Misc", "Armor Pattern", 14025).getInt(14025); pickaxeHead = config.getItem("Tool Parts", "Pickaxe Head", 14026).getInt(14026); shovelHead = config.getItem("Tool Parts", "Shovel Head", 14027).getInt(14027); axeHead = config.getItem("Tool Parts", "Axe Head", 14028).getInt(14028); hoeHead = config.getItem("Tool Parts", "Hoe Head", 14029).getInt(14029); swordBlade = config.getItem("Tool Parts", "Sword Blade", 14030).getInt(14030); largeGuard = config.getItem("Tool Parts", "Large Guard", 14031).getInt(14031); medGuard = config.getItem("Tool Parts", "Medium Guard", 14032).getInt(14032); crossbar = config.getItem("Tool Parts", "Crossbar", 14033).getInt(14033); binding = config.getItem("Tool Parts", "Tool Binding", 14034).getInt(14034); frypanHead = config.getItem("Tool Parts", "Frypan Head", 14035).getInt(14035); signHead = config.getItem("Tool Parts", "Sign Head", 14036).getInt(14036); lumberHead = config.getItem("Tool Parts", "Lumber Axe Head", 14037).getInt(14037); knifeBlade = config.getItem("Tool Parts", "Knife Blade", 14038).getInt(14038); chiselHead = config.getItem("Tool Parts", "Chisel Head", 14039).getInt(14039); scytheBlade = config.getItem("Tool Parts", "Scythe Head", 14040).getInt(14040); toughBinding = config.getItem("Tool Parts", "Tough Binding", 14041).getInt(14041); toughRod = config.getItem("Tool Parts", "Tough Rod", 14042).getInt(14042); largeSwordBlade = config.getItem("Tool Parts", "Large Sword Blade", 14043).getInt(14043); largePlate = config.getItem("Tool Parts", "Large Plate", 14044).getInt(14044); excavatorHead = config.getItem("Tool Parts", "Excavator Head", 14045).getInt(14045); hammerHead = config.getItem("Tool Parts", "Hammer Head", 14046).getInt(14046); fullGuard = config.getItem("Tool Parts", "Full Guard", 14047).getInt(14047); bowstring = config.getItem("Tool Parts", "Bowstring", 14048).getInt(14048); arrowhead = config.getItem("Tool Parts", "Arrowhead", 14049).getInt(14049); fletching = config.getItem("Tool Parts", "Fletching", 14050).getInt(14050); pickaxe = config.getItem("Tools", "Pickaxe", 14051).getInt(14051); shovel = config.getItem("Tools", "Shovel", 14052).getInt(14052); axe = config.getItem("Tools", "Axe", 14053).getInt(14053); hoe = config.getItem("Tools", "Hoe", 14054).getInt(14054); broadsword = config.getItem("Tools", "Broadsword", 14055).getInt(14055); rapier = config.getItem("Tools", "Rapier", 14057).getInt(14057); longsword = config.getItem("Tools", "Longsword", 14056).getInt(14056); dagger = config.getItem("Tools", "Dagger", 14065).getInt(14065); frypan = config.getItem("Tools", "Frying Pan", 14058).getInt(14058); battlesign = config.getItem("Tools", "Battlesign", 14059).getInt(14059); mattock = config.getItem("Tools", "Mattock", 14060).getInt(14060); lumberaxe = config.getItem("Tools", "Lumber Axe", 14061).getInt(14061); longbow = config.getItem("Tools", "Longbow", 14062).getInt(14062); shortbow = config.getItem("Tools", "Shortbow", 14063).getInt(14063); potionLauncher = config.getItem("Tools", "Potion Launcher", 14064).getInt(14064); chisel = config.getItem("Tools", "Chisel", 14066).getInt(14066); scythe = config.getItem("Tools", "Scythe", 14067).getInt(14067); cleaver = config.getItem("Tools", "Cleaver", 14068).getInt(14068); excavator = config.getItem("Tools", "Excavator", 14069).getInt(14069); hammer = config.getItem("Tools", "Hammer", 14070).getInt(14070); battleaxe = config.getItem("Tools", "Battleaxe", 14071).getInt(14071); cutlass = config.getItem("Tools", "Cutlass", 14072).getInt(14072); arrow = config.getItem("Tools", "Arrow", 14073).getInt(14073); buckets = config.getItem("Patterns and Misc", "Buckets", 14101).getInt(14101); uselessItem = config.getItem("Patterns and Misc", "Title Icon", 14102).getInt(14102); slimefood = config.getItem("Patterns and Misc", "Strange Food", 14103).getInt(14103); oreChunks = config.getItem("Patterns and Misc", "Ore Chunks", 14104).getInt(14104); heartCanister = config.getItem("Equipables", "Heart Canister", 14105).getInt(14105); diamondApple = config.getItem("Patterns and Misc", "Jeweled Apple", 14107).getInt(14107); woodHelmet = config.getItem("Equipables", "Wooden Helmet", 14106).getInt(14106); woodChestplate = config.getItem("Equipables", "Wooden Chestplate", 14108).getInt(14108); woodPants = config.getItem("Equipables", "Wooden Pants", 14109).getInt(14109); woodBoots = config.getItem("Equipables", "Wooden Boots", 14110).getInt(14110); glove = config.getItem("Equipables", "Gloves", 14111).getInt(14111); knapsack = config.getItem("Equipables", "Knapsack", 14112).getInt(14112); goldHead = config.getItem("Patterns and Misc", "Golden Head", 14113).getInt(14113); jerky = config.getItem("Patterns and Misc", "Jerky", 14115).getInt(14115); // spoolWire = config.getItem("Logic", "SpoolWire", 14120).getInt(14120); // lengthWire = config.getItem("Logic", "LengthWire", 14121).getInt(14121); boolean ic2 = true; boolean xycraft = true; try { Class c = Class.forName("ic2.core.IC2"); ic2 = false; } catch (Exception e) { } try { Class c = Class.forName("soaryn.xycraft.core.XyCraft"); xycraft = false; } catch (Exception e) { } generateCopper = config.get("Worldgen Disabler", "Generate Copper", ic2).getBoolean(ic2); generateTin = config.get("Worldgen Disabler", "Generate Tin", ic2).getBoolean(ic2); generateAluminum = config.get("Worldgen Disabler", "Generate Aluminum", xycraft).getBoolean(xycraft); generateNetherOres = config.get("Worldgen Disabler", "Generate Cobalt and Ardite", true).getBoolean(true); generateIronSurface = config.get("Worldgen Disabler", "Generate Surface Iron", true).getBoolean(true); generateGoldSurface = config.get("Worldgen Disabler", "Generate Surface Gold", true).getBoolean(true); generateCopperSurface = config.get("Worldgen Disabler", "Generate Surface Copper", true).getBoolean(true); generateTinSurface = config.get("Worldgen Disabler", "Generate Surface Tin", true).getBoolean(true); generateAluminumSurface = config.get("Worldgen Disabler", "Generate Surface Aluminum", true).getBoolean(true); generateIronBush = config.get("Worldgen Disabler", "Generate Iron Bushes", true).getBoolean(true); generateGoldBush = config.get("Worldgen Disabler", "Generate Gold Bushes", true).getBoolean(true); generateCopperBush = config.get("Worldgen Disabler", "Generate Copper Bushes", true).getBoolean(true); generateTinBush = config.get("Worldgen Disabler", "Generate Tin Bushes", true).getBoolean(true); generateAluminumBush = config.get("Worldgen Disabler", "Generate Aluminum Bushes", true).getBoolean(true); generateEssenceBush = config.get("Worldgen Disabler", "Generate Essence Bushes", true).getBoolean(true); addToVillages = config.get("Worldgen Disabler", "Add Village Generation", true).getBoolean(true); copperuDensity = config.get("Worldgen", "Copper Underground Density", 2, "Density: Chances per chunk").getInt(2); tinuDensity = config.get("Worldgen", "Tin Underground Density", 2).getInt(2); aluminumuDensity = config.get("Worldgen", "Aluminum Underground Density", 3).getInt(3); netherDensity = config.get("Worldgen", "Nether Ores Density", 8).getInt(8); copperuMinY = config.get("Worldgen", "Copper Underground Min Y", 20).getInt(20); copperuMaxY = config.get("Worldgen", "Copper Underground Max Y", 60).getInt(60); tinuMinY = config.get("Worldgen", "Tin Underground Min Y", 0).getInt(0); tinuMaxY = config.get("Worldgen", "Tin Underground Max Y", 40).getInt(40); aluminumuMinY = config.get("Worldgen", "Aluminum Underground Min Y", 0).getInt(0); aluminumuMaxY = config.get("Worldgen", "Aluminum Underground Max Y", 64).getInt(64); ironsRarity = config.get("Worldgen", "Iron Surface Rarity", 400).getInt(400); goldsRarity = config.get("Worldgen", "Gold Surface Rarity", 900).getInt(900); coppersRarity = config.get("Worldgen", "Copper Surface Rarity", 100, "Rarity: 1/num to generate in chunk").getInt(100); tinsRarity = config.get("Worldgen", "Tin Surface Rarity", 100).getInt(100); aluminumsRarity = config.get("Worldgen", "Aluminum Surface Rarity", 50).getInt(50); cobaltsRarity = config.get("Worldgen", "Cobalt Surface Rarity", 2000).getInt(2000); ironBushDensity = config.get("Worldgen", "Iron Bush Density", 1).getInt(1); goldBushDensity = config.get("Worldgen", "Gold Bush Density", 1).getInt(1); copperBushDensity = config.get("Worldgen", "Copper Bush Density", 2).getInt(2); tinBushDensity = config.get("Worldgen", "Tin Bush Density", 2).getInt(2); aluminumBushDensity = config.get("Worldgen", "Aluminum Bush Density", 2).getInt(2); silverBushDensity = config.get("Worldgen", "Silver Bush Density", 1).getInt(1); ironBushRarity = config.get("Worldgen", "Iron Bush Rarity", 5).getInt(5); goldBushRarity = config.get("Worldgen", "Gold Bush Rarity", 8).getInt(8); copperBushRarity = config.get("Worldgen", "Copper Bush Rarity", 3).getInt(3); tinBushRarity = config.get("Worldgen", "Tin Bush Rarity", 3).getInt(3); aluminumBushRarity = config.get("Worldgen", "Aluminum Bush Rarity", 2).getInt(2); essenceBushRarity = config.get("Worldgen", "Essence Bush Rarity", 6).getInt(6); copperBushMinY = config.get("Worldgen", "Copper Bush Min Y", 20).getInt(20); copperBushMaxY = config.get("Worldgen", "Copper Bush Max Y", 60).getInt(60); tinBushMinY = config.get("Worldgen", "Tin Bush Min Y", 0).getInt(0); tinBushMaxY = config.get("Worldgen", "Tin Bush Max Y", 40).getInt(40); aluminumBushMinY = config.get("Worldgen", "Aluminum Bush Min Y", 0).getInt(0); aluminumBushMaxY = config.get("Worldgen", "Aluminum Bush Max Y", 60).getInt(60); seaLevel = config.get("general", "Sea level", 64).getInt(64); enableHealthRegen = config.get("Ultra Hardcore Changes", "Passive Health Regen", true).getBoolean(true); goldAppleRecipe = config.get("Ultra Hardcore Changes", "Change Crafting Recipes", false, "Makes recipes for gold apples, carrots, and melon potions more expensive").getBoolean(false); dropPlayerHeads = config.get("Ultra Hardcore Changes", "Players drop heads on death", false).getBoolean(false); uhcGhastDrops = config.get("Ultra Hardcore Changes", "Change Ghast drops to Gold Ingots", false).getBoolean(false); worldBorder = config.get("Ultra Hardcore Changes", "Add World Border", false).getBoolean(false); worldBorderSize = config.get("Ultra Hardcore Changes", "World Border Radius", 1000).getInt(1000); freePatterns = config.get("Ultra Hardcore Changes", "Add Patterns to Pattern Chests", false, "Gives all tier 1 patterns when pattern chest is placed").getBoolean(false); AbilityHelper.necroticUHS = config.get("Ultra Hardcore Changes", "Necrotic modifier only heals on hostile mob kills", false).getBoolean(false); //Slime pools islandRarity = config.get("Worldgen", "Slime Island Rarity", 1450).getInt(1450); //Looks Property conTexMode = config.get("Looks", "Connected Textures Enabled", true); conTexMode.comment = "0 = disabled, 1 = enabled, 2 = enabled + ignore stained glass meta"; connectedTexturesMode = conTexMode.getInt(2); //dimension blacklist cfgDimBlackList = config.get("DimBlackList", "SlimeIslandDimBlacklist", new int[] {}, "Add dimension ID's to prevent slime islands from generating in them").getIntList(); slimeIslGenDim0Only = config.get("DimBlackList", "GenerateSlimeIslandInDim0Only", false, "True: slime islands wont generate in any ages other than overworld(if enabled); False: will generate in all non-blackisted ages").getBoolean(false); slimeIslGenDim0 = config.get("DimBlackList", "slimeIslGenDim0", true, "True: slime islands generate in overworld; False they do not generate").getBoolean(true); genIslandsFlat = config.get("DimBlacklist", "genIslandsFlat", false, "Generate slime islands in flat worlds").getBoolean(false); //Experimental functionality throwableSmeltery = config.get("Experimental", "Items can be thrown into smelteries", true).getBoolean(true); newSmeltery = config.get("Experimental", "Use new adaptive Smeltery code", false, "Warning: Very buggy").getBoolean(false); //Addon stuff isCleaverTwoHanded = config.get("Battlegear", "Can Cleavers have shields", true).getBoolean(true); isHatchetWeapon = config.get("Battlegear", "Are Hatches also weapons", true).getBoolean(true); //Achievement Properties achievementsEnabled = config.get("Achievement Properties", "AchievementsEnabled", true).getBoolean(true); /* Save the configuration file */ config.save(); File gt = new File(location + "/GregTech"); if (gt.exists()) { File gtDyn = new File(location + "/GregTech/DynamicConfig.cfg"); Configuration gtConfig = new Configuration(gtDyn); gtConfig.load(); gregtech = gtConfig.get("smelting", "tile.anvil.slightlyDamaged", false).getBoolean(false); } }
public static void initProps (File location) { /* Here we will set up the config file for the mod * First: Create a folder inside the config folder * Second: Create the actual config file * Note: Configs are a pain, but absolutely necessary for every mod. */ File newFile = new File(location + "/TinkersWorkshop.txt"); /* Some basic debugging will go a long way */ try { newFile.createNewFile(); } catch (IOException e) { TConstruct.logger.severe("Could not create configuration file for TConstruct. Reason:"); TConstruct.logger.severe(e.getLocalizedMessage()); } /* [Forge] Configuration class, used as config method */ Configuration config = new Configuration(newFile); cfglocation = location; /* Load the configuration file */ config.load(); /* Define the mod's IDs. * Avoid values below 4096 for items and in the 250-450 range for blocks */ superfunWorld = config.get("Superfun", "All the world is Superfun", false).getBoolean(false); keepHunger = config.get("Difficulty Changes", "Keep hunger on death", true).getBoolean(true); keepLevels = config.get("Difficulty Changes", "Keep levels on death", true).getBoolean(true); beginnerBook = config.get("Difficulty Changes", "Spawn beginner book", true).getBoolean(true); enableTWood = config.get("Difficulty Changes", "Enable mod wooden tools", true).getBoolean(true); enableTStone = config.get("Difficulty Changes", "Enable mod stone tools", true).getBoolean(true); enableTCactus = config.get("Difficulty Changes", "Enable mod cactus tools", true).getBoolean(true); enableTBone = config.get("Difficulty Changes", "Enable mod bone tools", true).getBoolean(true); enableTFlint = config.get("Difficulty Changes", "Enable mod flint tools", true).getBoolean(true); enableTNetherrack = config.get("Difficulty Changes", "Enable mod netherrack tools", true).getBoolean(true); enableTSlime = config.get("Difficulty Changes", "Enable mod slime tools", true).getBoolean(true); enableTPaper = config.get("Difficulty Changes", "Enable mod paper tools", true).getBoolean(true); enableTBlueSlime = config.get("Difficulty Changes", "Enable mod blue slime tools", true).getBoolean(true); craftMetalTools = config.get("Difficulty Changes", "Craft metals with Wood Patterns", false).getBoolean(false); vanillaMetalBlocks = config.get("Difficulty Changes", "Craft vanilla metal blocks", true).getBoolean(true); lavaFortuneInteraction = config.get("Difficulty Changes", "Enable Auto-Smelt and Fortune interaction", true).getBoolean(true); removeVanillaToolRecipes = config.get("Difficulty Changes", "Remove Vanilla Tool Recipes", false).getBoolean(false); stencilTableCrafting = config.get("Difficulty Changes", "Craft Stencil Tables", true).getBoolean(true); miningLevelIncrease = config.get("Difficulty Changes", "Modifiers increase Mining Level", true).getBoolean(true); denyMattock = config.get("Difficulty Changes", "Deny creation of non-metal mattocks", false).getBoolean(false); ingotsPerOre = config.get("Smeltery Output Modification", "Ingots per ore", 2, "Number of ingots returned from smelting ores in the smeltery").getInt(2); ingotsBronzeAlloy = config.get("Smeltery Output Modification", "Bronze ingot return", 3, "Number of ingots returned from smelting Bronze in the smeltery").getInt(3); ingotsAluminumBrassAlloy = config.get("Smeltery Output Modification", "Aluminum Brass ingot return", 4, "Number of ingots returned from smelting Aluminum Brass in the smeltery").getInt(4); ingotsAlumiteAlloy = config.get("Smeltery Output Modification", "Alumite ingot return", 3, "Number of ingots returned from smelting Alumite in the smeltery").getInt(3); ingotsManyullynAlloy = config.get("Smeltery Output Modification", "Manyullyn ingot return", 1, "Number of ingots returned from smelting Manyullyn in the smeltery").getInt(1); //1467-1489 woodStation = config.getBlock("Wood Tool Station", 1471).getInt(1471); heldItemBlock = config.getBlock("Held Item Block", 1472).getInt(1472); lavaTank = config.getBlock("Lava Tank", 1473).getInt(1473); smeltery = config.getBlock("Smeltery", 1474).getInt(1474); oreSlag = config.getBlock("Ores Slag", 1475).getInt(1475); craftedSoil = config.getBlock("Special Soil", 1476).getInt(1476); searedTable = config.getBlock("Seared Table", 1477).getInt(1477); metalBlock = config.getBlock("Metal Storage", 1478).getInt(1478); /*metalFlowing = config.getBlock("Liquid Metal Flowing", 1479).getInt(1479); metalStill = config.getBlock("Liquid Metal Still", 1480).getInt(1480);*/ multiBrick = config.getBlock("Multi Brick", 1481).getInt(1481); stoneTorch = config.getBlock("Stone Torch", 1484).getInt(1484); stoneLadder = config.getBlock("Stone Ladder", 1479).getInt(1479); oreBerry = config.getBlock("Ore Berry One", 1485).getInt(1485); oreBerrySecond = config.getBlock("Ore Berry Two", 1486).getInt(1486); oreGravel = config.getBlock("Ores Gravel", 1488).getInt(1488); speedBlock = config.getBlock("Speed Block", 1489).getInt(1489); landmine = config.getBlock("Landmine", 1470).getInt(1470); toolForge = config.getBlock("Tool Forge", 1468).getInt(1468); multiBrickFancy = config.getBlock("Multi Brick Fancy", 1467).getInt(1467); barricadeOak = config.getBlock("Oak Barricade", 1469).getInt(1469); barricadeSpruce = config.getBlock("Spruce Barricade", 1482).getInt(1482); barricadeBirch = config.getBlock("Birch Barricade", 1483).getInt(1483); barricadeJungle = config.getBlock("Jungle Barricade", 1487).getInt(1487); slimeChannel = config.getBlock("Slime Channel", 3190).getInt(3190); slimePad = config.getBlock("Slime Pad", 3191).getInt(3191); furnaceSlab = config.getBlock("Furnace Slab", 3192).getInt(3192); //Thermal Expansion moltenSilver = config.getBlock("Molten Silver", 3195).getInt(3195); moltenLead = config.getBlock("Molten Lead", 3196).getInt(3196); moltenNickel = config.getBlock("Molten Nickel", 3197).getInt(3197); moltenShiny = config.getBlock("Molten Platinum", 3198).getInt(3198); moltenInvar = config.getBlock("Molten Invar", 3199).getInt(3199); moltenElectrum = config.getBlock("Molten Electrum", 3200).getInt(3200); moltenIron = config.getBlock("Molten Iron", 3201).getInt(3201); moltenGold = config.getBlock("Molten Gold", 3202).getInt(3202); moltenCopper = config.getBlock("Molten Copper", 3203).getInt(3203); moltenTin = config.getBlock("Molten Tin", 3204).getInt(3204); moltenAluminum = config.getBlock("Molten Aluminum", 3205).getInt(3205); moltenCobalt = config.getBlock("Molten Cobalt", 3206).getInt(3206); moltenArdite = config.getBlock("Molten Ardite", 3207).getInt(3207); moltenBronze = config.getBlock("Molten Bronze", 3208).getInt(3208); moltenAlubrass = config.getBlock("Molten Aluminum Brass", 3209).getInt(3209); moltenManyullyn = config.getBlock("Molten Manyullyn", 3210).getInt(3210); moltenAlumite = config.getBlock("Molten Alumite", 3211).getInt(3211); moltenObsidian = config.getBlock("Molten Obsidian", 3212).getInt(3212); moltenSteel = config.getBlock("Molten Steel", 3213).getInt(3213); moltenGlass = config.getBlock("Molten Glass", 3214).getInt(3214); moltenStone = config.getBlock("Molten Stone", 3215).getInt(3215); moltenEmerald = config.getBlock("Molten Emerald", 3216).getInt(3216); blood = config.getBlock("Liquid Cow", 3217).getInt(3217); moltenEnder = config.getBlock("Molten Ender", 3218).getInt(3218); // signalBus = config.getBlock("Signal Bus", 3221).getInt(3221); // signalTerminal = config.getBlock("Signal Terminal", 3222).getInt(3222); glass = config.getBlock("Clear Glass", 3223).getInt(3223); stainedGlass = config.getBlock("Stained Glass", 3224).getInt(3224); stainedGlassClear = config.getBlock("Clear Stained Glass", 3225).getInt(3225); // redstoneMachine = config.getBlock("Redstone Machines", 3226).getInt(3226); // Migrated to TMechworks dryingRack = config.getBlock("Drying Rack", 3227).getInt(3227); glassPane = config.getBlock("Glass Pane", 3228).getInt(3228); stainedGlassClearPane = config.getBlock("Clear Stained Glass Pane", 3229).getInt(3229); searedSlab = config.getBlock("Seared Slab", 3230).getInt(3230); speedSlab = config.getBlock("Speed Slab", 3231).getInt(3231); punji = config.getBlock("Punji", 3232).getInt(3232); woodCrafter = config.getBlock("Crafting Station", 3233).getInt(3233); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); //3246 castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); airTank = config.getBlock("Air Tank", 3246).getInt(3246); slimeExplosive = config.getBlock("SDX", 3247).getInt(3247); castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); woodenRail = config.getBlock("Wooden Rail", 3250).getInt(3250); //3251+ belongs to Natura. Go backwards! manual = config.getItem("Patterns and Misc", "Tinker's Manual", 14018).getInt(14018); blankPattern = config.getItem("Patterns and Misc", "Blank Patterns", 14019).getInt(14019); materials = config.getItem("Patterns and Misc", "Materials", 14020).getInt(14020); toolRod = config.getItem("Patterns and Misc", "Tool Rod", 14021).getInt(14021); toolShard = config.getItem("Patterns and Misc", "Tool Shard", 14022).getInt(14022); woodPattern = config.getItem("Patterns and Misc", "Wood Pattern", 14023).getInt(14023); metalPattern = config.getItem("Patterns and Misc", "Metal Pattern", 14024).getInt(14024); armorPattern = config.getItem("Patterns and Misc", "Armor Pattern", 14025).getInt(14025); pickaxeHead = config.getItem("Tool Parts", "Pickaxe Head", 14026).getInt(14026); shovelHead = config.getItem("Tool Parts", "Shovel Head", 14027).getInt(14027); axeHead = config.getItem("Tool Parts", "Axe Head", 14028).getInt(14028); hoeHead = config.getItem("Tool Parts", "Hoe Head", 14029).getInt(14029); swordBlade = config.getItem("Tool Parts", "Sword Blade", 14030).getInt(14030); largeGuard = config.getItem("Tool Parts", "Large Guard", 14031).getInt(14031); medGuard = config.getItem("Tool Parts", "Medium Guard", 14032).getInt(14032); crossbar = config.getItem("Tool Parts", "Crossbar", 14033).getInt(14033); binding = config.getItem("Tool Parts", "Tool Binding", 14034).getInt(14034); frypanHead = config.getItem("Tool Parts", "Frypan Head", 14035).getInt(14035); signHead = config.getItem("Tool Parts", "Sign Head", 14036).getInt(14036); lumberHead = config.getItem("Tool Parts", "Lumber Axe Head", 14037).getInt(14037); knifeBlade = config.getItem("Tool Parts", "Knife Blade", 14038).getInt(14038); chiselHead = config.getItem("Tool Parts", "Chisel Head", 14039).getInt(14039); scytheBlade = config.getItem("Tool Parts", "Scythe Head", 14040).getInt(14040); toughBinding = config.getItem("Tool Parts", "Tough Binding", 14041).getInt(14041); toughRod = config.getItem("Tool Parts", "Tough Rod", 14042).getInt(14042); largeSwordBlade = config.getItem("Tool Parts", "Large Sword Blade", 14043).getInt(14043); largePlate = config.getItem("Tool Parts", "Large Plate", 14044).getInt(14044); excavatorHead = config.getItem("Tool Parts", "Excavator Head", 14045).getInt(14045); hammerHead = config.getItem("Tool Parts", "Hammer Head", 14046).getInt(14046); fullGuard = config.getItem("Tool Parts", "Full Guard", 14047).getInt(14047); bowstring = config.getItem("Tool Parts", "Bowstring", 14048).getInt(14048); arrowhead = config.getItem("Tool Parts", "Arrowhead", 14049).getInt(14049); fletching = config.getItem("Tool Parts", "Fletching", 14050).getInt(14050); pickaxe = config.getItem("Tools", "Pickaxe", 14051).getInt(14051); shovel = config.getItem("Tools", "Shovel", 14052).getInt(14052); axe = config.getItem("Tools", "Axe", 14053).getInt(14053); hoe = config.getItem("Tools", "Hoe", 14054).getInt(14054); broadsword = config.getItem("Tools", "Broadsword", 14055).getInt(14055); rapier = config.getItem("Tools", "Rapier", 14057).getInt(14057); longsword = config.getItem("Tools", "Longsword", 14056).getInt(14056); dagger = config.getItem("Tools", "Dagger", 14065).getInt(14065); frypan = config.getItem("Tools", "Frying Pan", 14058).getInt(14058); battlesign = config.getItem("Tools", "Battlesign", 14059).getInt(14059); mattock = config.getItem("Tools", "Mattock", 14060).getInt(14060); lumberaxe = config.getItem("Tools", "Lumber Axe", 14061).getInt(14061); longbow = config.getItem("Tools", "Longbow", 14062).getInt(14062); shortbow = config.getItem("Tools", "Shortbow", 14063).getInt(14063); potionLauncher = config.getItem("Tools", "Potion Launcher", 14064).getInt(14064); chisel = config.getItem("Tools", "Chisel", 14066).getInt(14066); scythe = config.getItem("Tools", "Scythe", 14067).getInt(14067); cleaver = config.getItem("Tools", "Cleaver", 14068).getInt(14068); excavator = config.getItem("Tools", "Excavator", 14069).getInt(14069); hammer = config.getItem("Tools", "Hammer", 14070).getInt(14070); battleaxe = config.getItem("Tools", "Battleaxe", 14071).getInt(14071); cutlass = config.getItem("Tools", "Cutlass", 14072).getInt(14072); arrow = config.getItem("Tools", "Arrow", 14073).getInt(14073); buckets = config.getItem("Patterns and Misc", "Buckets", 14101).getInt(14101); uselessItem = config.getItem("Patterns and Misc", "Title Icon", 14102).getInt(14102); slimefood = config.getItem("Patterns and Misc", "Strange Food", 14103).getInt(14103); oreChunks = config.getItem("Patterns and Misc", "Ore Chunks", 14104).getInt(14104); heartCanister = config.getItem("Equipables", "Heart Canister", 14105).getInt(14105); diamondApple = config.getItem("Patterns and Misc", "Jeweled Apple", 14107).getInt(14107); woodHelmet = config.getItem("Equipables", "Wooden Helmet", 14106).getInt(14106); woodChestplate = config.getItem("Equipables", "Wooden Chestplate", 14108).getInt(14108); woodPants = config.getItem("Equipables", "Wooden Pants", 14109).getInt(14109); woodBoots = config.getItem("Equipables", "Wooden Boots", 14110).getInt(14110); glove = config.getItem("Equipables", "Gloves", 14111).getInt(14111); knapsack = config.getItem("Equipables", "Knapsack", 14112).getInt(14112); goldHead = config.getItem("Patterns and Misc", "Golden Head", 14113).getInt(14113); jerky = config.getItem("Patterns and Misc", "Jerky", 14115).getInt(14115); // spoolWire = config.getItem("Logic", "SpoolWire", 14120).getInt(14120); // lengthWire = config.getItem("Logic", "LengthWire", 14121).getInt(14121); boolean ic2 = true; boolean xycraft = true; try { Class c = Class.forName("ic2.core.IC2"); ic2 = false; } catch (Exception e) { } try { Class c = Class.forName("soaryn.xycraft.core.XyCraft"); xycraft = false; } catch (Exception e) { } generateCopper = config.get("Worldgen Disabler", "Generate Copper", ic2).getBoolean(ic2); generateTin = config.get("Worldgen Disabler", "Generate Tin", ic2).getBoolean(ic2); generateAluminum = config.get("Worldgen Disabler", "Generate Aluminum", xycraft).getBoolean(xycraft); generateNetherOres = config.get("Worldgen Disabler", "Generate Cobalt and Ardite", true).getBoolean(true); generateIronSurface = config.get("Worldgen Disabler", "Generate Surface Iron", true).getBoolean(true); generateGoldSurface = config.get("Worldgen Disabler", "Generate Surface Gold", true).getBoolean(true); generateCopperSurface = config.get("Worldgen Disabler", "Generate Surface Copper", true).getBoolean(true); generateTinSurface = config.get("Worldgen Disabler", "Generate Surface Tin", true).getBoolean(true); generateAluminumSurface = config.get("Worldgen Disabler", "Generate Surface Aluminum", true).getBoolean(true); generateIronBush = config.get("Worldgen Disabler", "Generate Iron Bushes", true).getBoolean(true); generateGoldBush = config.get("Worldgen Disabler", "Generate Gold Bushes", true).getBoolean(true); generateCopperBush = config.get("Worldgen Disabler", "Generate Copper Bushes", true).getBoolean(true); generateTinBush = config.get("Worldgen Disabler", "Generate Tin Bushes", true).getBoolean(true); generateAluminumBush = config.get("Worldgen Disabler", "Generate Aluminum Bushes", true).getBoolean(true); generateEssenceBush = config.get("Worldgen Disabler", "Generate Essence Bushes", true).getBoolean(true); addToVillages = config.get("Worldgen Disabler", "Add Village Generation", true).getBoolean(true); copperuDensity = config.get("Worldgen", "Copper Underground Density", 2, "Density: Chances per chunk").getInt(2); tinuDensity = config.get("Worldgen", "Tin Underground Density", 2).getInt(2); aluminumuDensity = config.get("Worldgen", "Aluminum Underground Density", 3).getInt(3); netherDensity = config.get("Worldgen", "Nether Ores Density", 8).getInt(8); copperuMinY = config.get("Worldgen", "Copper Underground Min Y", 20).getInt(20); copperuMaxY = config.get("Worldgen", "Copper Underground Max Y", 60).getInt(60); tinuMinY = config.get("Worldgen", "Tin Underground Min Y", 0).getInt(0); tinuMaxY = config.get("Worldgen", "Tin Underground Max Y", 40).getInt(40); aluminumuMinY = config.get("Worldgen", "Aluminum Underground Min Y", 0).getInt(0); aluminumuMaxY = config.get("Worldgen", "Aluminum Underground Max Y", 64).getInt(64); ironsRarity = config.get("Worldgen", "Iron Surface Rarity", 400).getInt(400); goldsRarity = config.get("Worldgen", "Gold Surface Rarity", 900).getInt(900); coppersRarity = config.get("Worldgen", "Copper Surface Rarity", 100, "Rarity: 1/num to generate in chunk").getInt(100); tinsRarity = config.get("Worldgen", "Tin Surface Rarity", 100).getInt(100); aluminumsRarity = config.get("Worldgen", "Aluminum Surface Rarity", 50).getInt(50); cobaltsRarity = config.get("Worldgen", "Cobalt Surface Rarity", 2000).getInt(2000); ironBushDensity = config.get("Worldgen", "Iron Bush Density", 1).getInt(1); goldBushDensity = config.get("Worldgen", "Gold Bush Density", 1).getInt(1); copperBushDensity = config.get("Worldgen", "Copper Bush Density", 2).getInt(2); tinBushDensity = config.get("Worldgen", "Tin Bush Density", 2).getInt(2); aluminumBushDensity = config.get("Worldgen", "Aluminum Bush Density", 2).getInt(2); silverBushDensity = config.get("Worldgen", "Silver Bush Density", 1).getInt(1); ironBushRarity = config.get("Worldgen", "Iron Bush Rarity", 5).getInt(5); goldBushRarity = config.get("Worldgen", "Gold Bush Rarity", 8).getInt(8); copperBushRarity = config.get("Worldgen", "Copper Bush Rarity", 3).getInt(3); tinBushRarity = config.get("Worldgen", "Tin Bush Rarity", 3).getInt(3); aluminumBushRarity = config.get("Worldgen", "Aluminum Bush Rarity", 2).getInt(2); essenceBushRarity = config.get("Worldgen", "Essence Bush Rarity", 6).getInt(6); copperBushMinY = config.get("Worldgen", "Copper Bush Min Y", 20).getInt(20); copperBushMaxY = config.get("Worldgen", "Copper Bush Max Y", 60).getInt(60); tinBushMinY = config.get("Worldgen", "Tin Bush Min Y", 0).getInt(0); tinBushMaxY = config.get("Worldgen", "Tin Bush Max Y", 40).getInt(40); aluminumBushMinY = config.get("Worldgen", "Aluminum Bush Min Y", 0).getInt(0); aluminumBushMaxY = config.get("Worldgen", "Aluminum Bush Max Y", 60).getInt(60); seaLevel = config.get("general", "Sea level", 64).getInt(64); enableHealthRegen = config.get("Ultra Hardcore Changes", "Passive Health Regen", true).getBoolean(true); goldAppleRecipe = config.get("Ultra Hardcore Changes", "Change Crafting Recipes", false, "Makes recipes for gold apples, carrots, and melon potions more expensive").getBoolean(false); dropPlayerHeads = config.get("Ultra Hardcore Changes", "Players drop heads on death", false).getBoolean(false); uhcGhastDrops = config.get("Ultra Hardcore Changes", "Change Ghast drops to Gold Ingots", false).getBoolean(false); worldBorder = config.get("Ultra Hardcore Changes", "Add World Border", false).getBoolean(false); worldBorderSize = config.get("Ultra Hardcore Changes", "World Border Radius", 1000).getInt(1000); freePatterns = config.get("Ultra Hardcore Changes", "Add Patterns to Pattern Chests", false, "Gives all tier 1 patterns when pattern chest is placed").getBoolean(false); AbilityHelper.necroticUHS = config.get("Ultra Hardcore Changes", "Necrotic modifier only heals on hostile mob kills", false).getBoolean(false); //Slime pools islandRarity = config.get("Worldgen", "Slime Island Rarity", 1450).getInt(1450); //Looks Property conTexMode = config.get("Looks", "Connected Textures Enabled", true); conTexMode.comment = "0 = disabled, 1 = enabled, 2 = enabled + ignore stained glass meta"; connectedTexturesMode = conTexMode.getInt(2); //dimension blacklist cfgDimBlackList = config.get("DimBlackList", "SlimeIslandDimBlacklist", new int[] {}, "Add dimension ID's to prevent slime islands from generating in them").getIntList(); slimeIslGenDim0Only = config.get("DimBlackList", "GenerateSlimeIslandInDim0Only", false, "True: slime islands wont generate in any ages other than overworld(if enabled); False: will generate in all non-blackisted ages").getBoolean(false); slimeIslGenDim0 = config.get("DimBlackList", "slimeIslGenDim0", true, "True: slime islands generate in overworld; False they do not generate").getBoolean(true); genIslandsFlat = config.get("DimBlacklist", "genIslandsFlat", false, "Generate slime islands in flat worlds").getBoolean(false); //Experimental functionality throwableSmeltery = config.get("Experimental", "Items can be thrown into smelteries", true).getBoolean(true); newSmeltery = config.get("Experimental", "Use new adaptive Smeltery code", false, "Warning: Very buggy").getBoolean(false); //Addon stuff isCleaverTwoHanded = config.get("Battlegear", "Can Cleavers have shields", true).getBoolean(true); isHatchetWeapon = config.get("Battlegear", "Are Hatches also weapons", true).getBoolean(true); //Achievement Properties achievementsEnabled = config.get("Achievement Properties", "AchievementsEnabled", true).getBoolean(true); /* Save the configuration file */ config.save(); File gt = new File(location + "/GregTech"); if (gt.exists()) { File gtDyn = new File(location + "/GregTech/DynamicConfig.cfg"); Configuration gtConfig = new Configuration(gtDyn); gtConfig.load(); gregtech = gtConfig.get("smelting", "tile.anvil.slightlyDamaged", false).getBoolean(false); } }
diff --git a/src/cnc/gcode/controller/CNCGCodeController.java b/src/cnc/gcode/controller/CNCGCodeController.java index 9cfe97b..ee5b31d 100644 --- a/src/cnc/gcode/controller/CNCGCodeController.java +++ b/src/cnc/gcode/controller/CNCGCodeController.java @@ -1,169 +1,169 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cnc.gcode.controller; import java.awt.Point; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.text.Utilities; /** * * @author patrick */ public class CNCGCodeController { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { if(args.length!=0) { //Usage: if(!args[0].equals("-postprocessor") || args.length!=11) { System.out.println("Usage:"); System.out.println("java -jar "+Tools.getJarName()+" -postprocessor [input file] [output file] [max time for optimization in seconds] [move x] [move y] [mirror x (true/false)] [mirror y (true/false)] [backlash x] [backlash y] [backlash z]"); System.exit(1); } //Load data: File fin= new File(args[1]); if(!fin.exists()) { - System.out.println("inout file does not exists!"); + System.out.println("inout file does not exist!"); System.exit(1); } if(!fin.canRead()) { System.out.println("inout file not readable!"); System.exit(1); } File fout= new File(args[2]); Database.OPTIMISATIONTIMEOUT.set(""+Integer.parseInt(args[3])); double movex = Double.parseDouble(args[4]); double movey = Double.parseDouble(args[5]); boolean mirrorx = Boolean.parseBoolean(args[6]); boolean mirrory = Boolean.parseBoolean(args[7]); Database.BL0.set(""+Double.parseDouble(args[8])); Database.BL1.set(""+Double.parseDouble(args[9])); Database.BL2.set(""+Double.parseDouble(args[10])); //Load File System.out.println("Loading file ..."); CNCCommand.Calchelper c= new CNCCommand.Calchelper(); ArrayList<CNCCommand> cmds= new ArrayList<>(); String line; int warings=0; int errors=0; try (BufferedReader br = new BufferedReader(new FileReader(fin))) { while((line = br.readLine() )!=null) { CNCCommand command= new CNCCommand(line); CNCCommand.State t=command.calcCommand(c); if(t==CNCCommand.State.WARNING) warings++; if(t==CNCCommand.State.ERROR) errors++; cmds.add(command); } } double maxTime=c.secounds; - System.out.println("File loaded with "+warings+" Warings and "+errors+" Errors!"); + System.out.println("File loaded with "+warings+" Warnings and "+errors+" Errors!"); //Optimize CNCCommand.Optimiser o= new CNCCommand.Optimiser(new CNCCommand.Optimiser.IProgress() { String lastmessage=""; @Override public void publish(String message, int progess) throws MyException { if(!lastmessage.equals(message)) { lastmessage=message; System.out.println(message); } } }); try { //Not much to do the CNCOpimiser does all the work :-) cmds=o.execute(cmds); } catch (MyException ex) { System.out.println(ex.getMessage()); System.exit(1); } //Process new comands System.out.println("Process new comands ..."); c= new CNCCommand.Calchelper(); warings=0; errors=0; for(int i=0;i<cmds.size();i++) { CNCCommand command=cmds.get(i); CNCCommand.State t=command.calcCommand(c); if(t==CNCCommand.State.WARNING) warings++; if(t==CNCCommand.State.ERROR) errors++; } - System.out.println("Optimised! Saved time: "+Tools.formatDuration((long)(maxTime-c.secounds)) +"! \nCommands now have "+warings+" Warings and "+errors+" Errors!"); + System.out.println("Optimized! Saved time: "+Tools.formatDuration((long)(maxTime-c.secounds)) +"! \nCommands now have "+warings+" Warnings and "+errors+" Errors!"); //Process new comands System.out.println("Export comands ..."); PrintWriter export=new PrintWriter(fout); CNCCommand.Transform t= new CNCCommand.Transform(movex, movey, mirrorx, mirrory); for(int i=0;i<cmds.size();i++) { CNCCommand cmd=cmds.get(i); export.println(";"+cmd.toString()); for(String execute:cmd.execute(t,false)) { export.println(execute); } } export.close(); System.out.println("Done!"); System.exit(0); } try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {} //Run Mainwindow new MainForm().setVisible(true); } }
false
true
public static void main(String[] args) throws IOException { if(args.length!=0) { //Usage: if(!args[0].equals("-postprocessor") || args.length!=11) { System.out.println("Usage:"); System.out.println("java -jar "+Tools.getJarName()+" -postprocessor [input file] [output file] [max time for optimization in seconds] [move x] [move y] [mirror x (true/false)] [mirror y (true/false)] [backlash x] [backlash y] [backlash z]"); System.exit(1); } //Load data: File fin= new File(args[1]); if(!fin.exists()) { System.out.println("inout file does not exists!"); System.exit(1); } if(!fin.canRead()) { System.out.println("inout file not readable!"); System.exit(1); } File fout= new File(args[2]); Database.OPTIMISATIONTIMEOUT.set(""+Integer.parseInt(args[3])); double movex = Double.parseDouble(args[4]); double movey = Double.parseDouble(args[5]); boolean mirrorx = Boolean.parseBoolean(args[6]); boolean mirrory = Boolean.parseBoolean(args[7]); Database.BL0.set(""+Double.parseDouble(args[8])); Database.BL1.set(""+Double.parseDouble(args[9])); Database.BL2.set(""+Double.parseDouble(args[10])); //Load File System.out.println("Loading file ..."); CNCCommand.Calchelper c= new CNCCommand.Calchelper(); ArrayList<CNCCommand> cmds= new ArrayList<>(); String line; int warings=0; int errors=0; try (BufferedReader br = new BufferedReader(new FileReader(fin))) { while((line = br.readLine() )!=null) { CNCCommand command= new CNCCommand(line); CNCCommand.State t=command.calcCommand(c); if(t==CNCCommand.State.WARNING) warings++; if(t==CNCCommand.State.ERROR) errors++; cmds.add(command); } } double maxTime=c.secounds; System.out.println("File loaded with "+warings+" Warings and "+errors+" Errors!"); //Optimize CNCCommand.Optimiser o= new CNCCommand.Optimiser(new CNCCommand.Optimiser.IProgress() { String lastmessage=""; @Override public void publish(String message, int progess) throws MyException { if(!lastmessage.equals(message)) { lastmessage=message; System.out.println(message); } } }); try { //Not much to do the CNCOpimiser does all the work :-) cmds=o.execute(cmds); } catch (MyException ex) { System.out.println(ex.getMessage()); System.exit(1); } //Process new comands System.out.println("Process new comands ..."); c= new CNCCommand.Calchelper(); warings=0; errors=0; for(int i=0;i<cmds.size();i++) { CNCCommand command=cmds.get(i); CNCCommand.State t=command.calcCommand(c); if(t==CNCCommand.State.WARNING) warings++; if(t==CNCCommand.State.ERROR) errors++; } System.out.println("Optimised! Saved time: "+Tools.formatDuration((long)(maxTime-c.secounds)) +"! \nCommands now have "+warings+" Warings and "+errors+" Errors!"); //Process new comands System.out.println("Export comands ..."); PrintWriter export=new PrintWriter(fout); CNCCommand.Transform t= new CNCCommand.Transform(movex, movey, mirrorx, mirrory); for(int i=0;i<cmds.size();i++) { CNCCommand cmd=cmds.get(i); export.println(";"+cmd.toString()); for(String execute:cmd.execute(t,false)) { export.println(execute); } } export.close(); System.out.println("Done!"); System.exit(0); } try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {} //Run Mainwindow new MainForm().setVisible(true); }
public static void main(String[] args) throws IOException { if(args.length!=0) { //Usage: if(!args[0].equals("-postprocessor") || args.length!=11) { System.out.println("Usage:"); System.out.println("java -jar "+Tools.getJarName()+" -postprocessor [input file] [output file] [max time for optimization in seconds] [move x] [move y] [mirror x (true/false)] [mirror y (true/false)] [backlash x] [backlash y] [backlash z]"); System.exit(1); } //Load data: File fin= new File(args[1]); if(!fin.exists()) { System.out.println("inout file does not exist!"); System.exit(1); } if(!fin.canRead()) { System.out.println("inout file not readable!"); System.exit(1); } File fout= new File(args[2]); Database.OPTIMISATIONTIMEOUT.set(""+Integer.parseInt(args[3])); double movex = Double.parseDouble(args[4]); double movey = Double.parseDouble(args[5]); boolean mirrorx = Boolean.parseBoolean(args[6]); boolean mirrory = Boolean.parseBoolean(args[7]); Database.BL0.set(""+Double.parseDouble(args[8])); Database.BL1.set(""+Double.parseDouble(args[9])); Database.BL2.set(""+Double.parseDouble(args[10])); //Load File System.out.println("Loading file ..."); CNCCommand.Calchelper c= new CNCCommand.Calchelper(); ArrayList<CNCCommand> cmds= new ArrayList<>(); String line; int warings=0; int errors=0; try (BufferedReader br = new BufferedReader(new FileReader(fin))) { while((line = br.readLine() )!=null) { CNCCommand command= new CNCCommand(line); CNCCommand.State t=command.calcCommand(c); if(t==CNCCommand.State.WARNING) warings++; if(t==CNCCommand.State.ERROR) errors++; cmds.add(command); } } double maxTime=c.secounds; System.out.println("File loaded with "+warings+" Warnings and "+errors+" Errors!"); //Optimize CNCCommand.Optimiser o= new CNCCommand.Optimiser(new CNCCommand.Optimiser.IProgress() { String lastmessage=""; @Override public void publish(String message, int progess) throws MyException { if(!lastmessage.equals(message)) { lastmessage=message; System.out.println(message); } } }); try { //Not much to do the CNCOpimiser does all the work :-) cmds=o.execute(cmds); } catch (MyException ex) { System.out.println(ex.getMessage()); System.exit(1); } //Process new comands System.out.println("Process new comands ..."); c= new CNCCommand.Calchelper(); warings=0; errors=0; for(int i=0;i<cmds.size();i++) { CNCCommand command=cmds.get(i); CNCCommand.State t=command.calcCommand(c); if(t==CNCCommand.State.WARNING) warings++; if(t==CNCCommand.State.ERROR) errors++; } System.out.println("Optimized! Saved time: "+Tools.formatDuration((long)(maxTime-c.secounds)) +"! \nCommands now have "+warings+" Warnings and "+errors+" Errors!"); //Process new comands System.out.println("Export comands ..."); PrintWriter export=new PrintWriter(fout); CNCCommand.Transform t= new CNCCommand.Transform(movex, movey, mirrorx, mirrory); for(int i=0;i<cmds.size();i++) { CNCCommand cmd=cmds.get(i); export.println(";"+cmd.toString()); for(String execute:cmd.execute(t,false)) { export.println(execute); } } export.close(); System.out.println("Done!"); System.exit(0); } try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {} //Run Mainwindow new MainForm().setVisible(true); }
diff --git a/src/main/java/net/floodlightcontroller/core/internal/Controller.java b/src/main/java/net/floodlightcontroller/core/internal/Controller.java index f4745d06..5cfe4f09 100644 --- a/src/main/java/net/floodlightcontroller/core/internal/Controller.java +++ b/src/main/java/net/floodlightcontroller/core/internal/Controller.java @@ -1,1978 +1,1980 @@ /** * Copyright 2011, Big Switch Networks, Inc. * Originally created by David Erickson, Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ package net.floodlightcontroller.core.internal; import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IHAListener; import net.floodlightcontroller.core.IInfoProvider; import net.floodlightcontroller.core.IListener.Command; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IOFSwitchDriver; import net.floodlightcontroller.core.IOFSwitchFilter; import net.floodlightcontroller.core.IOFSwitchListener; import net.floodlightcontroller.core.OFSwitchBase; import net.floodlightcontroller.core.annotations.LogMessageDoc; import net.floodlightcontroller.core.annotations.LogMessageDocs; import net.floodlightcontroller.core.internal.OFChannelState.HandshakeState; import net.floodlightcontroller.core.util.ListenerDispatcher; import net.floodlightcontroller.core.web.CoreWebRoutable; import net.floodlightcontroller.counter.ICounterStoreService; import net.floodlightcontroller.flowcache.IFlowCacheService; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.perfmon.IPktInProcessingTimeService; import net.floodlightcontroller.restserver.IRestApiService; import net.floodlightcontroller.storage.IResultSet; import net.floodlightcontroller.storage.IStorageSourceListener; import net.floodlightcontroller.storage.IStorageSourceService; import net.floodlightcontroller.storage.StorageException; import net.floodlightcontroller.threadpool.IThreadPoolService; import net.floodlightcontroller.util.LoadMonitor; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.timeout.IdleStateAwareChannelUpstreamHandler; import org.jboss.netty.handler.timeout.IdleStateEvent; import org.jboss.netty.handler.timeout.ReadTimeoutException; import org.openflow.protocol.OFEchoReply; import org.openflow.protocol.OFError; import org.openflow.protocol.OFError.OFBadActionCode; import org.openflow.protocol.OFError.OFBadRequestCode; import org.openflow.protocol.OFError.OFErrorType; import org.openflow.protocol.OFError.OFFlowModFailedCode; import org.openflow.protocol.OFError.OFHelloFailedCode; import org.openflow.protocol.OFError.OFPortModFailedCode; import org.openflow.protocol.OFError.OFQueueOpFailedCode; import org.openflow.protocol.OFFeaturesReply; import org.openflow.protocol.OFGetConfigReply; import org.openflow.protocol.OFGetConfigRequest; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPhysicalPort; import org.openflow.protocol.OFPortStatus; import org.openflow.protocol.OFPortStatus.OFPortReason; import org.openflow.protocol.OFSetConfig; import org.openflow.protocol.OFStatisticsReply; import org.openflow.protocol.OFStatisticsRequest; import org.openflow.protocol.OFSwitchConfig; import org.openflow.protocol.OFType; import org.openflow.protocol.OFVendor; import org.openflow.protocol.factory.BasicFactory; import org.openflow.protocol.factory.MessageParseException; import org.openflow.protocol.statistics.OFDescriptionStatistics; import org.openflow.protocol.statistics.OFStatistics; import org.openflow.protocol.statistics.OFStatisticsType; import org.openflow.util.HexString; import org.openflow.vendor.nicira.OFNiciraVendorData; import org.openflow.vendor.nicira.OFNiciraVendorExtensions; import org.openflow.vendor.nicira.OFRoleReplyVendorData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The main controller class. Handles all setup and network listeners */ public class Controller implements IFloodlightProviderService, IStorageSourceListener { protected static Logger log = LoggerFactory.getLogger(Controller.class); private static final String ERROR_DATABASE = "The controller could not communicate with the system database."; protected BasicFactory factory; protected ConcurrentMap<OFType, ListenerDispatcher<OFType,IOFMessageListener>> messageListeners; // OFSwitch driver binding map and order protected Map<String, IOFSwitchDriver>switchBindingMap; protected List<String> switchDescSortedList; // The activeSwitches map contains only those switches that are actively // being controlled by us -- it doesn't contain switches that are // in the slave role protected ConcurrentHashMap<Long, IOFSwitch> activeSwitches; // connectedSwitches contains all connected switches, including ones where // we're a slave controller. We need to keep track of them so that we can // send role request messages to switches when our role changes to master // We add a switch to this set after it successfully completes the // handshake. Access to this Set needs to be synchronized with roleChanger protected HashSet<IOFSwitch> connectedSwitches; // The controllerNodeIPsCache maps Controller IDs to their IP address. // It's only used by handleControllerNodeIPsChanged protected HashMap<String, String> controllerNodeIPsCache; protected Set<IOFSwitchListener> switchListeners; protected Set<IHAListener> haListeners; protected Map<String, List<IInfoProvider>> providerMap; protected BlockingQueue<IUpdate> updates; // Module dependencies protected IRestApiService restApi; protected ICounterStoreService counterStore = null; protected IFlowCacheService bigFlowCacheMgr; protected IStorageSourceService storageSource; protected IPktInProcessingTimeService pktinProcTime; protected IThreadPoolService threadPool; // Configuration options protected int openFlowPort = 6633; protected int workerThreads = 0; // The id for this controller node. Should be unique for each controller // node in a controller cluster. protected String controllerId = "localhost"; // The current role of the controller. // If the controller isn't configured to support roles, then this is null. protected Role role; // This is the role of the controller based on HARoleChange notifications // we have sent. I.e., this field reflects the last role notification // we have sent to the listeners. On a transition to slave we first set // this role and then notify, on a transition to master we first notify // and then set the role. We then use it to make sure we don't forward // OF messages while the modules are in slave role. protected volatile Role notifiedRole; // A helper that handles sending and timeout handling for role requests protected RoleChanger roleChanger; // Start time of the controller protected long systemStartTime; // Flag to always flush flow table on switch reconnect (HA or otherwise) protected boolean alwaysClearFlowsOnSwAdd = false; // Storage table names protected static final String CONTROLLER_TABLE_NAME = "controller_controller"; protected static final String CONTROLLER_ID = "id"; protected static final String SWITCH_CONFIG_TABLE_NAME = "controller_switchconfig"; protected static final String SWITCH_CONFIG_CORE_SWITCH = "core_switch"; protected static final String CONTROLLER_INTERFACE_TABLE_NAME = "controller_controllerinterface"; protected static final String CONTROLLER_INTERFACE_ID = "id"; protected static final String CONTROLLER_INTERFACE_CONTROLLER_ID = "controller_id"; protected static final String CONTROLLER_INTERFACE_TYPE = "type"; protected static final String CONTROLLER_INTERFACE_NUMBER = "number"; protected static final String CONTROLLER_INTERFACE_DISCOVERED_IP = "discovered_ip"; // Perf. related configuration protected static final int SEND_BUFFER_SIZE = 4 * 1024 * 1024; public static final int BATCH_MAX_SIZE = 100; protected static final boolean ALWAYS_DECODE_ETH = true; // Load monitor for overload protection protected final boolean overload_drop = Boolean.parseBoolean(System.getProperty("overload_drop", "false")); protected final LoadMonitor loadmonitor = new LoadMonitor(log); /** * Updates handled by the main loop */ protected interface IUpdate { /** * Calls the appropriate listeners */ public void dispatch(); } public enum SwitchUpdateType { ADDED, REMOVED, PORTCHANGED } /** * Update message indicating a switch was added or removed */ protected class SwitchUpdate implements IUpdate { public IOFSwitch sw; public SwitchUpdateType switchUpdateType; public SwitchUpdate(IOFSwitch sw, SwitchUpdateType switchUpdateType) { this.sw = sw; this.switchUpdateType = switchUpdateType; } @Override public void dispatch() { if (log.isTraceEnabled()) { log.trace("Dispatching switch update {} {}", sw, switchUpdateType); } if (switchListeners != null) { for (IOFSwitchListener listener : switchListeners) { switch(switchUpdateType) { case ADDED: listener.addedSwitch(sw); break; case REMOVED: listener.removedSwitch(sw); break; case PORTCHANGED: listener.switchPortChanged(sw.getId()); break; } } } } } /** * Update message indicating controller's role has changed */ protected class HARoleUpdate implements IUpdate { public Role oldRole; public Role newRole; public HARoleUpdate(Role newRole, Role oldRole) { this.oldRole = oldRole; this.newRole = newRole; } @Override public void dispatch() { // Make sure that old and new roles are different. if (oldRole == newRole) { if (log.isTraceEnabled()) { log.trace("HA role update ignored as the old and " + "new roles are the same. newRole = {}" + "oldRole = {}", newRole, oldRole); } return; } if (log.isTraceEnabled()) { log.trace("Dispatching HA Role update newRole = {}, oldRole = {}", newRole, oldRole); } // Set notified role to slave before notifying listeners. This // stops OF messages from being sent to listeners if (newRole == Role.SLAVE) Controller.this.notifiedRole = newRole; if (haListeners != null) { for (IHAListener listener : haListeners) { listener.roleChanged(oldRole, newRole); } } // Set notified role to master/equal after notifying listeners. // We now forward messages again if (newRole != Role.SLAVE) Controller.this.notifiedRole = newRole; } } /** * Update message indicating * IPs of controllers in controller cluster have changed. */ protected class HAControllerNodeIPUpdate implements IUpdate { public Map<String,String> curControllerNodeIPs; public Map<String,String> addedControllerNodeIPs; public Map<String,String> removedControllerNodeIPs; public HAControllerNodeIPUpdate( HashMap<String,String> curControllerNodeIPs, HashMap<String,String> addedControllerNodeIPs, HashMap<String,String> removedControllerNodeIPs) { this.curControllerNodeIPs = curControllerNodeIPs; this.addedControllerNodeIPs = addedControllerNodeIPs; this.removedControllerNodeIPs = removedControllerNodeIPs; } @Override public void dispatch() { if (log.isTraceEnabled()) { log.trace("Dispatching HA Controller Node IP update " + "curIPs = {}, addedIPs = {}, removedIPs = {}", new Object[] { curControllerNodeIPs, addedControllerNodeIPs, removedControllerNodeIPs } ); } if (haListeners != null) { for (IHAListener listener: haListeners) { listener.controllerNodeIPsChanged(curControllerNodeIPs, addedControllerNodeIPs, removedControllerNodeIPs); } } } } // *************** // Getters/Setters // *************** public void setStorageSourceService(IStorageSourceService storageSource) { this.storageSource = storageSource; } public void setCounterStore(ICounterStoreService counterStore) { this.counterStore = counterStore; } public void setFlowCacheMgr(IFlowCacheService flowCacheMgr) { this.bigFlowCacheMgr = flowCacheMgr; } public void setPktInProcessingService(IPktInProcessingTimeService pits) { this.pktinProcTime = pits; } public void setRestApiService(IRestApiService restApi) { this.restApi = restApi; } public void setThreadPoolService(IThreadPoolService tp) { this.threadPool = tp; } @Override public Role getRole() { synchronized(roleChanger) { return role; } } @Override public void setRole(Role role) { if (role == null) throw new NullPointerException("Role can not be null."); // Need to synchronize to ensure a reliable ordering on role request // messages send and to ensure the list of connected switches is stable // RoleChanger will handle the actual sending of the message and // timeout handling // @see RoleChanger synchronized(roleChanger) { if (role.equals(this.role)) { log.debug("Ignoring role change: role is already {}", role); return; } Role oldRole = this.role; this.role = role; log.debug("Submitting role change request to role {}", role); roleChanger.submitRequest(connectedSwitches, role); // Enqueue an update for our listeners. try { this.updates.put(new HARoleUpdate(role, oldRole)); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } } // ********************** // ChannelUpstreamHandler // ********************** /** * Return a new channel handler for processing a switch connections * @param state The channel state object for the connection * @return the new channel handler */ protected ChannelUpstreamHandler getChannelHandler(OFChannelState state) { return new OFChannelHandler(state); } /** * Channel handler deals with the switch connection and dispatches * switch messages to the appropriate locations. * @author readams */ protected class OFChannelHandler extends IdleStateAwareChannelUpstreamHandler { protected IOFSwitch sw; protected Channel channel; protected OFChannelState state; public OFChannelHandler(OFChannelState state) { this.state = state; } @Override @LogMessageDoc(message="New switch connection from {ip address}", explanation="A new switch has connected from the " + "specified IP address") public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); log.info("New switch connection from {}", channel.getRemoteAddress()); sendHandShakeMessage(OFType.HELLO); } @Override @LogMessageDoc(message="Disconnected switch {switch information}", explanation="The specified switch has disconnected.") public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (sw != null && state.hsState == HandshakeState.READY) { if (activeSwitches.containsKey(sw.getId())) { // It's safe to call removeSwitch even though the map might // not contain this particular switch but another with the // same DPID removeSwitch(sw); } synchronized(roleChanger) { connectedSwitches.remove(sw); roleChanger.removePendingRequests(sw); } sw.setConnected(false); } log.info("Disconnected switch {}", sw); } @Override @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="Disconnecting switch {switch} due to read timeout", explanation="The connected switch has failed to send any " + "messages or respond to echo requests", recommendation=LogMessageDoc.CHECK_SWITCH), @LogMessageDoc(level="ERROR", message="Disconnecting switch {switch}: failed to " + "complete handshake", explanation="The switch did not respond correctly " + "to handshake messages", recommendation=LogMessageDoc.CHECK_SWITCH), @LogMessageDoc(level="ERROR", message="Disconnecting switch {switch} due to IO Error: {}", explanation="There was an error communicating with the switch", recommendation=LogMessageDoc.CHECK_SWITCH), @LogMessageDoc(level="ERROR", message="Disconnecting switch {switch} due to switch " + "state error: {error}", explanation="The switch sent an unexpected message", recommendation=LogMessageDoc.CHECK_SWITCH), @LogMessageDoc(level="ERROR", message="Disconnecting switch {switch} due to " + "message parse failure", explanation="Could not parse a message from the switch", recommendation=LogMessageDoc.CHECK_SWITCH), @LogMessageDoc(level="ERROR", message="Terminating controller due to storage exception", explanation=ERROR_DATABASE, recommendation=LogMessageDoc.CHECK_CONTROLLER), @LogMessageDoc(level="ERROR", message="Could not process message: queue full", explanation="OpenFlow messages are arriving faster than " + " the controller can process them.", recommendation=LogMessageDoc.CHECK_CONTROLLER), @LogMessageDoc(level="ERROR", message="Error while processing message " + "from switch {switch} {cause}", explanation="An error occurred processing the switch message", recommendation=LogMessageDoc.GENERIC_ACTION) }) public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (e.getCause() instanceof ReadTimeoutException) { // switch timeout log.error("Disconnecting switch {} due to read timeout", sw); ctx.getChannel().close(); } else if (e.getCause() instanceof HandshakeTimeoutException) { log.error("Disconnecting switch {}: failed to complete handshake", sw); ctx.getChannel().close(); } else if (e.getCause() instanceof ClosedChannelException) { //log.warn("Channel for sw {} already closed", sw); } else if (e.getCause() instanceof IOException) { log.error("Disconnecting switch {} due to IO Error: {}", sw, e.getCause().getMessage()); ctx.getChannel().close(); } else if (e.getCause() instanceof SwitchStateException) { log.error("Disconnecting switch {} due to switch state error: {}", sw, e.getCause().getMessage()); ctx.getChannel().close(); } else if (e.getCause() instanceof MessageParseException) { log.error("Disconnecting switch " + sw + " due to message parse failure", e.getCause()); ctx.getChannel().close(); } else if (e.getCause() instanceof StorageException) { log.error("Terminating controller due to storage exception", e.getCause()); terminate(); } else if (e.getCause() instanceof RejectedExecutionException) { log.warn("Could not process message: queue full"); } else { log.error("Error while processing message from switch " + sw, e.getCause()); ctx.getChannel().close(); } } @Override public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception { List<OFMessage> msglist = new ArrayList<OFMessage>(1); msglist.add(factory.getMessage(OFType.ECHO_REQUEST)); e.getChannel().write(msglist); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof List) { @SuppressWarnings("unchecked") List<OFMessage> msglist = (List<OFMessage>)e.getMessage(); LoadMonitor.LoadLevel loadlevel; int packets_dropped = 0; int packets_allowed = 0; int lldps_allowed = 0; if (overload_drop) { loadlevel = loadmonitor.getLoadLevel(); } else { loadlevel = LoadMonitor.LoadLevel.OK; } for (OFMessage ofm : msglist) { try { if (overload_drop && !loadlevel.equals(LoadMonitor.LoadLevel.OK)) { switch (ofm.getType()) { case PACKET_IN: switch (loadlevel) { case VERYHIGH: // Drop all packet-ins, including LLDP/BDDPs packets_dropped++; continue; case HIGH: // Drop all packet-ins, except LLDP/BDDPs byte[] data = ((OFPacketIn)ofm).getPacketData(); if (data.length > 14) { if (((data[12] == (byte)0x88) && (data[13] == (byte)0xcc)) || ((data[12] == (byte)0x89) && (data[13] == (byte)0x42))) { lldps_allowed++; packets_allowed++; break; } } packets_dropped++; continue; default: // Load not high, go ahead and process msg packets_allowed++; break; } break; default: // Process all non-packet-ins packets_allowed++; break; } } // Do the actual packet processing processOFMessage(ofm); } catch (Exception ex) { // We are the last handler in the stream, so run the // exception through the channel again by passing in // ctx.getChannel(). Channels.fireExceptionCaught(ctx.getChannel(), ex); } } if (loadlevel != LoadMonitor.LoadLevel.OK) { if (log.isDebugEnabled()) { log.debug( "Overload: Detected {}, packets dropped={}", loadlevel.toString(), packets_dropped); log.debug( "Overload: Packets allowed={} (LLDP/BDDPs allowed={})", packets_allowed, lldps_allowed); } } // Flush all flow-mods/packet-out/stats generated from this "train" OFSwitchBase.flush_all(); counterStore.updateFlush(); bigFlowCacheMgr.updateFlush(); } } /** * Process the request for the switch description */ @LogMessageDoc(level="ERROR", message="Exception in reading description " + " during handshake {exception}", explanation="Could not process the switch description string", recommendation=LogMessageDoc.CHECK_SWITCH) void processSwitchDescReply(OFStatisticsReply m) { try { // Read description, if it has been updated OFDescriptionStatistics description = new OFDescriptionStatistics(); ChannelBuffer data = ChannelBuffers.buffer(description.getLength()); OFStatistics f = m.getFirstStatistics(); f.writeTo(data); description.readFrom(data); state.description = description; state.hasDescription = true; checkSwitchReady(); } catch (Exception ex) { log.error("Exception in reading description " + " during handshake", ex); } } /** * Send initial switch setup information that we need before adding * the switch * @throws IOException */ private void sendHandShakeMessage(OFType type) throws IOException { // Send initial Features Request List<OFMessage> msglist = new ArrayList<OFMessage>(1); msglist.add(factory.getMessage(type)); channel.write(msglist); } /** * Send the configuration requests we can only do after we have * the features reply * @throws IOException */ private void sendFeatureReplyConfiguration() throws IOException { List<OFMessage> msglist = new ArrayList<OFMessage>(3); // Ensure we receive the full packet via PacketIn OFSetConfig configSet = (OFSetConfig) factory .getMessage(OFType.SET_CONFIG); configSet.setMissSendLength((short) 0xffff) .setLengthU(OFSwitchConfig.MINIMUM_LENGTH); configSet.setXid(-4); msglist.add(configSet); // Verify (need barrier?) OFGetConfigRequest configReq = (OFGetConfigRequest) factory.getMessage(OFType.GET_CONFIG_REQUEST); configReq.setXid(-3); msglist.add(configReq); // Get Description to set switch-specific flags OFStatisticsRequest req = new OFStatisticsRequest(); req.setStatisticType(OFStatisticsType.DESC); req.setXid(-2); // something "large" req.setLengthU(req.getLengthU()); msglist.add(req); channel.write(msglist); } protected void checkSwitchReady() { if (!state.switchBindingDone) { bindSwitchToDriver(); } if (state.hsState == HandshakeState.FEATURES_REPLY && state.switchBindingDone) { state.hsState = HandshakeState.READY; // replay queued port status messages for (OFMessage m : state.queuedOFMessages) { try { processOFMessage(m); } catch (Exception e) { log.error("Failed to process delayed OFMessage {} {}", m, e.getCause()); } } state.queuedOFMessages.clear(); synchronized(roleChanger) { // We need to keep track of all of the switches that are connected // to the controller, in any role, so that we can later send the // role request messages when the controller role changes. // We need to be synchronized while doing this: we must not // send a another role request to the connectedSwitches until // we were able to add this new switch to connectedSwitches // *and* send the current role to the new switch. connectedSwitches.add(sw); // Send a role request. // This is a probe that we'll use to determine if the switch // actually supports the role request message. If it does we'll // get back a role reply message. If it doesn't we'll get back an // OFError message. // If role is MASTER we will promote switch to active // list when we receive the switch's role reply messages if (log.isDebugEnabled()) log.debug("This controller's role is {}, " + "sending initial role request msg to {}", role, sw); Collection<IOFSwitch> swList = new ArrayList<IOFSwitch>(1); swList.add(sw); roleChanger.submitRequest(swList, role); } } } protected void bindSwitchToDriver() { if (!state.hasGetConfigReply) { log.debug("Waiting for config reply from switch {}", channel.getRemoteAddress()); return; } if (!state.hasDescription) { log.debug("Waiting for switch description from switch {}", channel.getRemoteAddress()); return; } for (String desc : switchDescSortedList) { if (state.description.getManufacturerDescription() .startsWith(desc)) { sw = switchBindingMap.get(desc) .getOFSwitchImpl(desc, state.description); if (sw != null) { break; } } } if (sw == null) { sw = new OFSwitchImpl(); } // set switch information sw.setChannel(channel); sw.setFloodlightProvider(Controller.this); sw.setThreadPoolService(threadPool); sw.setFeaturesReply(state.featuresReply); sw.setSwitchProperties(state.description); readPropertyFromStorage(); log.info("Switch {} bound to class {}", HexString.toHexString(sw.getId()), sw.getClass().getName()); log.info("{}", state.description); state.featuresReply = null; state.description = null; state.switchBindingDone = true; } private void readPropertyFromStorage() { // At this time, also set other switch properties from storage boolean is_core_switch = false; IResultSet resultSet = null; try { String swid = sw.getStringId(); resultSet = storageSource.getRow(SWITCH_CONFIG_TABLE_NAME, swid); for (Iterator<IResultSet> it = resultSet.iterator(); it.hasNext();) { // In case of multiple rows, use the status // in last row? Map<String, Object> row = it.next().getRow(); if (row.containsKey(SWITCH_CONFIG_CORE_SWITCH)) { if (log.isDebugEnabled()) { log.debug("Reading SWITCH_IS_CORE_SWITCH " + "config for switch={}, is-core={}", sw, row.get(SWITCH_CONFIG_CORE_SWITCH)); } String ics = (String)row.get(SWITCH_CONFIG_CORE_SWITCH); is_core_switch = ics.equals("true"); } } } finally { if (resultSet != null) resultSet.close(); } if (is_core_switch) { sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH, new Boolean(true)); } } protected boolean handleVendorMessage(OFVendor vendorMessage) { boolean shouldHandleMessage = false; int vendor = vendorMessage.getVendor(); switch (vendor) { case OFNiciraVendorData.NX_VENDOR_ID: OFNiciraVendorData niciraVendorData = (OFNiciraVendorData)vendorMessage.getVendorData(); int dataType = niciraVendorData.getDataType(); switch (dataType) { case OFRoleReplyVendorData.NXT_ROLE_REPLY: OFRoleReplyVendorData roleReplyVendorData = (OFRoleReplyVendorData) niciraVendorData; roleChanger.handleRoleReplyMessage(sw, vendorMessage, roleReplyVendorData); break; default: log.warn("Unhandled Nicira VENDOR message; " + "data type = {}", dataType); break; } break; default: shouldHandleMessage = true; break; } return shouldHandleMessage; } /** * Dispatch an Openflow message from a switch to the appropriate * handler. * @param m The message to process * @throws IOException * @throws SwitchStateException */ @LogMessageDocs({ @LogMessageDoc(level="WARN", message="Config Reply from {switch} has " + "miss length set to {length}", explanation="The controller requires that the switch " + "use a miss length of 0xffff for correct " + "function", recommendation="Use a different switch to ensure " + "correct function"), @LogMessageDoc(level="WARN", message="Received ERROR from sw {switch} that " +"indicates roles are not supported " +"but we have received a valid " +"role reply earlier", explanation="The switch sent a confusing message to the" + "controller") }) protected void processOFMessage(OFMessage m) throws IOException, SwitchStateException { boolean shouldHandleMessage = false; switch (m.getType()) { case HELLO: if (log.isTraceEnabled()) log.trace("HELLO from {}", sw); if (state.hsState.equals(HandshakeState.START)) { state.hsState = HandshakeState.HELLO; sendHandShakeMessage(OFType.FEATURES_REQUEST); } else { throw new SwitchStateException("Unexpected HELLO from " + sw); } break; case ECHO_REQUEST: OFEchoReply reply = (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY); reply.setXid(m.getXid()); List<OFMessage> msglist = new ArrayList<OFMessage>(1); msglist.add(reply); channel.write(msglist); break; case ECHO_REPLY: break; case FEATURES_REPLY: if (log.isTraceEnabled()) log.trace("Features Reply from {}", sw); if (state.hsState.equals(HandshakeState.HELLO)) { sendFeatureReplyConfiguration(); state.featuresReply = (OFFeaturesReply) m; state.hsState = HandshakeState.FEATURES_REPLY; } else { // return results to rest api caller sw.setFeaturesReply((OFFeaturesReply) m); sw.deliverOFFeaturesReply(m); } break; case GET_CONFIG_REPLY: if (log.isTraceEnabled()) log.trace("Get config reply from {}", sw); if (!state.hsState.equals(HandshakeState.FEATURES_REPLY)) { String em = "Unexpected GET_CONFIG_REPLY from " + sw; throw new SwitchStateException(em); } OFGetConfigReply cr = (OFGetConfigReply) m; if (cr.getMissSendLength() == (short)0xffff) { log.trace("Config Reply from {} confirms " + "miss length set to 0xffff", sw); } else { log.warn("Config Reply from {} has " + "miss length set to {}", sw, cr.getMissSendLength() & 0xffff); } state.hasGetConfigReply = true; checkSwitchReady(); break; case VENDOR: shouldHandleMessage = handleVendorMessage((OFVendor)m); break; case ERROR: // TODO: we need better error handling. Especially for // request/reply style message (stats, roles) we should have // a unified way to lookup the xid in the error message. // This will probable involve rewriting the way we handle // request/reply style messages. OFError error = (OFError) m; if (roleChanger.checkFirstPendingRoleRequestXid( sw, error.getXid())) { roleChanger.deliverRoleRequestError(sw, error); } else { logError(sw, error); + // allow registered listeners to receive error messages + shouldHandleMessage = true; } break; case STATS_REPLY: if (state.hsState.ordinal() < HandshakeState.FEATURES_REPLY.ordinal()) { String em = "Unexpected STATS_REPLY from " + sw; throw new SwitchStateException(em); } if (sw == null) { processSwitchDescReply((OFStatisticsReply) m); } else { sw.deliverStatisticsReply(m); } break; case PORT_STATUS: if (sw != null) { handlePortStatusMessage(sw, (OFPortStatus)m); shouldHandleMessage = true; } else { // Queue till we complete driver binding state.queuedOFMessages.add(m); } break; default: shouldHandleMessage = true; break; } if (shouldHandleMessage) { // WARNING: sw is null if handshake is not complete if (!state.hsState.equals(HandshakeState.READY)) { log.debug("Ignoring message type {} received " + "from switch {} before switch is " + "fully configured.", m.getType(), sw); } else { sw.getListenerReadLock().lock(); try { if (sw.isConnected()) { // Only dispatch message if the switch is in the // activeSwitch map and if the switches role is // not slave and the modules are not in slave // TODO: Should we dispatch messages that we expect to // receive when we're in the slave role, e.g. port // status messages? Since we're "hiding" switches from // the listeners when we're in the slave role, then it // seems a little weird to dispatch port status messages // to them. On the other hand there might be special // modules that care about all of the connected switches // and would like to receive port status notifications. if (sw.getHARole() == Role.SLAVE || notifiedRole == Role.SLAVE || !activeSwitches.containsKey(sw.getId())) { // Don't log message if it's a port status message // since we expect to receive those from the switch // and don't want to emit spurious messages. if (m.getType() != OFType.PORT_STATUS) { log.debug("Ignoring message type {} received " + "from switch {} while in the slave role.", m.getType(), sw); } } else { handleMessage(sw, m, null); } } } finally { sw.getListenerReadLock().unlock(); } } } } } // **************** // Message handlers // **************** protected void handlePortStatusMessage(IOFSwitch sw, OFPortStatus m) { short portNumber = m.getDesc().getPortNumber(); OFPhysicalPort port = m.getDesc(); if (m.getReason() == (byte)OFPortReason.OFPPR_MODIFY.ordinal()) { sw.setPort(port); log.debug("Port #{} modified for {}", portNumber, sw); } else if (m.getReason() == (byte)OFPortReason.OFPPR_ADD.ordinal()) { sw.setPort(port); log.debug("Port #{} added for {}", portNumber, sw); } else if (m.getReason() == (byte)OFPortReason.OFPPR_DELETE.ordinal()) { sw.deletePort(portNumber); log.debug("Port #{} deleted for {}", portNumber, sw); } SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.PORTCHANGED); try { this.updates.put(update); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } /** * flcontext_cache - Keep a thread local stack of contexts */ protected static final ThreadLocal<Stack<FloodlightContext>> flcontext_cache = new ThreadLocal <Stack<FloodlightContext>> () { @Override protected Stack<FloodlightContext> initialValue() { return new Stack<FloodlightContext>(); } }; /** * flcontext_alloc - pop a context off the stack, if required create a new one * @return FloodlightContext */ protected static FloodlightContext flcontext_alloc() { FloodlightContext flcontext = null; if (flcontext_cache.get().empty()) { flcontext = new FloodlightContext(); } else { flcontext = flcontext_cache.get().pop(); } return flcontext; } /** * flcontext_free - Free the context to the current thread * @param flcontext */ protected void flcontext_free(FloodlightContext flcontext) { flcontext.getStorage().clear(); flcontext_cache.get().push(flcontext); } /** * Handle replies to certain OFMessages, and pass others off to listeners * @param sw The switch for the message * @param m The message * @param bContext The floodlight context. If null then floodlight context would * be allocated in this function * @throws IOException */ @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="Ignoring PacketIn (Xid = {xid}) because the data" + " field is empty.", explanation="The switch sent an improperly-formatted PacketIn" + " message", recommendation=LogMessageDoc.CHECK_SWITCH), @LogMessageDoc(level="WARN", message="Unhandled OF Message: {} from {}", explanation="The switch sent a message not handled by " + "the controller") }) protected void handleMessage(IOFSwitch sw, OFMessage m, FloodlightContext bContext) throws IOException { Ethernet eth = null; switch (m.getType()) { case PACKET_IN: OFPacketIn pi = (OFPacketIn)m; if (pi.getPacketData().length <= 0) { log.error("Ignoring PacketIn (Xid = " + pi.getXid() + ") because the data field is empty."); return; } if (Controller.ALWAYS_DECODE_ETH) { eth = new Ethernet(); eth.deserialize(pi.getPacketData(), 0, pi.getPacketData().length); counterStore.updatePacketInCountersLocal(sw, m, eth); } // fall through to default case... default: List<IOFMessageListener> listeners = null; if (messageListeners.containsKey(m.getType())) { listeners = messageListeners.get(m.getType()). getOrderedListeners(); } FloodlightContext bc = null; if (listeners != null) { // Check if floodlight context is passed from the calling // function, if so use that floodlight context, otherwise // allocate one if (bContext == null) { bc = flcontext_alloc(); } else { bc = bContext; } if (eth != null) { IFloodlightProviderService.bcStore.put(bc, IFloodlightProviderService.CONTEXT_PI_PAYLOAD, eth); } // Get the starting time (overall and per-component) of // the processing chain for this packet if performance // monitoring is turned on pktinProcTime.bootstrap(listeners); pktinProcTime.recordStartTimePktIn(); Command cmd; for (IOFMessageListener listener : listeners) { if (listener instanceof IOFSwitchFilter) { if (!((IOFSwitchFilter)listener).isInterested(sw)) { continue; } } pktinProcTime.recordStartTimeComp(listener); cmd = listener.receive(sw, m, bc); pktinProcTime.recordEndTimeComp(listener); if (Command.STOP.equals(cmd)) { break; } } pktinProcTime.recordEndTimePktIn(sw, m, bc); } else { log.warn("Unhandled OF Message: {} from {}", m, sw); } if ((bContext == null) && (bc != null)) flcontext_free(bc); } } /** * Log an OpenFlow error message from a switch * @param sw The switch that sent the error * @param error The error message */ @LogMessageDoc(level="ERROR", message="Error {error type} {error code} from {switch}", explanation="The switch responded with an unexpected error" + "to an OpenFlow message from the controller", recommendation="This could indicate improper network operation. " + "If the problem persists restarting the switch and " + "controller may help." ) protected void logError(IOFSwitch sw, OFError error) { int etint = 0xffff & error.getErrorType(); if (etint < 0 || etint >= OFErrorType.values().length) { log.error("Unknown error code {} from sw {}", etint, sw); } OFErrorType et = OFErrorType.values()[etint]; switch (et) { case OFPET_HELLO_FAILED: OFHelloFailedCode hfc = OFHelloFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, hfc, sw}); break; case OFPET_BAD_REQUEST: OFBadRequestCode brc = OFBadRequestCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, brc, sw}); break; case OFPET_BAD_ACTION: OFBadActionCode bac = OFBadActionCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, bac, sw}); break; case OFPET_FLOW_MOD_FAILED: OFFlowModFailedCode fmfc = OFFlowModFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, fmfc, sw}); break; case OFPET_PORT_MOD_FAILED: OFPortModFailedCode pmfc = OFPortModFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, pmfc, sw}); break; case OFPET_QUEUE_OP_FAILED: OFQueueOpFailedCode qofc = OFQueueOpFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, qofc, sw}); break; default: break; } } /** * Add a switch to the active switch list and call the switch listeners. * This happens either when a switch first connects (and the controller is * not in the slave role) or when the role of the controller changes from * slave to master. * * FIXME: remove shouldReadSwitchPortStateFromStorage argument once * performance problems are solved. We should call it always or never. * * @param sw the switch that has been added */ // TODO: need to rethink locking and the synchronous switch update. // We can / should also handle duplicate DPIDs in connectedSwitches @LogMessageDoc(level="ERROR", message="New switch added {switch} for already-added switch {switch}", explanation="A switch with the same DPID as another switch " + "connected to the controller. This can be caused by " + "multiple switches configured with the same DPID, or " + "by a switch reconnected very quickly after " + "disconnecting.", recommendation="If this happens repeatedly, it is likely there " + "are switches with duplicate DPIDs on the network. " + "Reconfigure the appropriate switches. If it happens " + "very rarely, then it is likely this is a transient " + "network problem that can be ignored." ) protected void addSwitch(IOFSwitch sw, boolean shouldClearFlowMods) { // TODO: is it safe to modify the HashMap without holding // the old switch's lock? IOFSwitch oldSw = this.activeSwitches.put(sw.getId(), sw); if (sw == oldSw) { // Note == for object equality, not .equals for value log.info("New add switch for pre-existing switch {}", sw); return; } if (oldSw != null) { oldSw.getListenerWriteLock().lock(); try { log.error("New switch added {} for already-added switch {}", sw, oldSw); // Set the connected flag to false to suppress calling // the listeners for this switch in processOFMessage oldSw.setConnected(false); oldSw.cancelAllStatisticsReplies(); // we need to clean out old switch state definitively // before adding the new switch // FIXME: It seems not completely kosher to call the // switch listeners here. I thought one of the points of // having the asynchronous switch update mechanism was so // the addedSwitch and removedSwitch were always called // from a single thread to simplify concurrency issues // for the listener. if (switchListeners != null) { for (IOFSwitchListener listener : switchListeners) { listener.removedSwitch(oldSw); } } // will eventually trigger a removeSwitch(), which will cause // a "Not removing Switch ... already removed debug message. // TODO: Figure out a way to handle this that avoids the // spurious debug message. oldSw.disconnectOutputStream(); } finally { oldSw.getListenerWriteLock().unlock(); } } if (shouldClearFlowMods) sw.clearAllFlowMods(); SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.ADDED); try { this.updates.put(update); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } /** * Remove a switch from the active switch list and call the switch listeners. * This happens either when the switch is disconnected or when the * controller's role for the switch changes from master to slave. * @param sw the switch that has been removed */ protected void removeSwitch(IOFSwitch sw) { // No need to acquire the listener lock, since // this method is only called after netty has processed all // pending messages log.debug("removeSwitch: {}", sw); if (!this.activeSwitches.remove(sw.getId(), sw) || !sw.isConnected()) { log.debug("Not removing switch {}; already removed", sw); return; } // We cancel all outstanding statistics replies if the switch transition // from active. In the future we might allow statistics requests // from slave controllers. Then we need to move this cancelation // to switch disconnect sw.cancelAllStatisticsReplies(); // FIXME: I think there's a race condition if we call updateInactiveSwitchInfo // here if role support is enabled. In that case if the switch is being // removed because we've been switched to being in the slave role, then I think // it's possible that the new master may have already been promoted to master // and written out the active switch state to storage. If we now execute // updateInactiveSwitchInfo we may wipe out all of the state that was // written out by the new master. Maybe need to revisit how we handle all // of the switch state that's written to storage. SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.REMOVED); try { this.updates.put(update); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } // *************** // IFloodlightProvider // *************** @Override public synchronized void addOFMessageListener(OFType type, IOFMessageListener listener) { ListenerDispatcher<OFType, IOFMessageListener> ldd = messageListeners.get(type); if (ldd == null) { ldd = new ListenerDispatcher<OFType, IOFMessageListener>(); messageListeners.put(type, ldd); } ldd.addListener(type, listener); } @Override public synchronized void removeOFMessageListener(OFType type, IOFMessageListener listener) { ListenerDispatcher<OFType, IOFMessageListener> ldd = messageListeners.get(type); if (ldd != null) { ldd.removeListener(listener); } } private void logListeners() { for (Map.Entry<OFType, ListenerDispatcher<OFType, IOFMessageListener>> entry : messageListeners.entrySet()) { OFType type = entry.getKey(); ListenerDispatcher<OFType, IOFMessageListener> ldd = entry.getValue(); StringBuffer sb = new StringBuffer(); sb.append("OFListeners for "); sb.append(type); sb.append(": "); for (IOFMessageListener l : ldd.getOrderedListeners()) { sb.append(l.getName()); sb.append(","); } log.debug(sb.toString()); } } public void removeOFMessageListeners(OFType type) { messageListeners.remove(type); } @Override public Map<Long, IOFSwitch> getSwitches() { return Collections.unmodifiableMap(this.activeSwitches); } @Override public void addOFSwitchListener(IOFSwitchListener listener) { this.switchListeners.add(listener); } @Override public void removeOFSwitchListener(IOFSwitchListener listener) { this.switchListeners.remove(listener); } @Override public Map<OFType, List<IOFMessageListener>> getListeners() { Map<OFType, List<IOFMessageListener>> lers = new HashMap<OFType, List<IOFMessageListener>>(); for(Entry<OFType, ListenerDispatcher<OFType, IOFMessageListener>> e : messageListeners.entrySet()) { lers.put(e.getKey(), e.getValue().getOrderedListeners()); } return Collections.unmodifiableMap(lers); } @Override @LogMessageDocs({ @LogMessageDoc(message="Failed to inject OFMessage {message} onto " + "a null switch", explanation="Failed to process a message because the switch " + " is no longer connected."), @LogMessageDoc(level="ERROR", message="Error reinjecting OFMessage on switch {switch}", explanation="An I/O error occured while attempting to " + "process an OpenFlow message", recommendation=LogMessageDoc.CHECK_SWITCH) }) public boolean injectOfMessage(IOFSwitch sw, OFMessage msg, FloodlightContext bc) { if (sw == null) { log.info("Failed to inject OFMessage {} onto a null switch", msg); return false; } // FIXME: Do we need to be able to inject messages to switches // where we're the slave controller (i.e. they're connected but // not active)? // FIXME: Don't we need synchronization logic here so we're holding // the listener read lock when we call handleMessage? After some // discussions it sounds like the right thing to do here would be to // inject the message as a netty upstream channel event so it goes // through the normal netty event processing, including being // handled if (!activeSwitches.containsKey(sw.getId())) return false; try { // Pass Floodlight context to the handleMessages() handleMessage(sw, msg, bc); } catch (IOException e) { log.error("Error reinjecting OFMessage on switch {}", HexString.toHexString(sw.getId())); return false; } return true; } @Override @LogMessageDoc(message="Calling System.exit", explanation="The controller is terminating") public synchronized void terminate() { log.info("Calling System.exit"); System.exit(1); } @Override public boolean injectOfMessage(IOFSwitch sw, OFMessage msg) { // call the overloaded version with floodlight context set to null return injectOfMessage(sw, msg, null); } @Override public void handleOutgoingMessage(IOFSwitch sw, OFMessage m, FloodlightContext bc) { if (log.isTraceEnabled()) { String str = OFMessage.getDataAsString(sw, m, bc); log.trace("{}", str); } List<IOFMessageListener> listeners = null; if (messageListeners.containsKey(m.getType())) { listeners = messageListeners.get(m.getType()).getOrderedListeners(); } if (listeners != null) { for (IOFMessageListener listener : listeners) { if (listener instanceof IOFSwitchFilter) { if (!((IOFSwitchFilter)listener).isInterested(sw)) { continue; } } if (Command.STOP.equals(listener.receive(sw, m, bc))) { break; } } } } @Override public BasicFactory getOFMessageFactory() { return factory; } @Override public String getControllerId() { return controllerId; } // ************** // Initialization // ************** protected void updateControllerInfo() { // Write out the controller info to the storage source Map<String, Object> controllerInfo = new HashMap<String, Object>(); String id = getControllerId(); controllerInfo.put(CONTROLLER_ID, id); storageSource.updateRow(CONTROLLER_TABLE_NAME, controllerInfo); } /** * Sets the initial role based on properties in the config params. * It looks for two different properties. * If the "role" property is specified then the value should be * either "EQUAL", "MASTER", or "SLAVE" and the role of the * controller is set to the specified value. If the "role" property * is not specified then it looks next for the "role.path" property. * In this case the value should be the path to a property file in * the file system that contains a property called "floodlight.role" * which can be one of the values listed above for the "role" property. * The idea behind the "role.path" mechanism is that you have some * separate heartbeat and master controller election algorithm that * determines the role of the controller. When a role transition happens, * it updates the current role in the file specified by the "role.path" * file. Then if floodlight restarts for some reason it can get the * correct current role of the controller from the file. * @param configParams The config params for the FloodlightProvider service * @return A valid role if role information is specified in the * config params, otherwise null */ @LogMessageDocs({ @LogMessageDoc(message="Controller role set to {role}", explanation="Setting the initial HA role to "), @LogMessageDoc(level="ERROR", message="Invalid current role value: {role}", explanation="An invalid HA role value was read from the " + "properties file", recommendation=LogMessageDoc.CHECK_CONTROLLER) }) protected Role getInitialRole(Map<String, String> configParams) { Role role = Role.MASTER; String roleString = configParams.get("role"); if (roleString == null) { String rolePath = configParams.get("rolepath"); if (rolePath != null) { Properties properties = new Properties(); try { properties.load(new FileInputStream(rolePath)); roleString = properties.getProperty("floodlight.role"); } catch (IOException exc) { // Don't treat it as an error if the file specified by the // rolepath property doesn't exist. This lets us enable the // HA mechanism by just creating/setting the floodlight.role // property in that file without having to modify the // floodlight properties. } } } if (roleString != null) { // Canonicalize the string to the form used for the enum constants roleString = roleString.trim().toUpperCase(); try { role = Role.valueOf(roleString); } catch (IllegalArgumentException exc) { log.error("Invalid current role value: {}", roleString); } } log.info("Controller role set to {}", role); return role; } /** * Tell controller that we're ready to accept switches loop * @throws IOException */ @Override @LogMessageDocs({ @LogMessageDoc(message="Listening for switch connections on {address}", explanation="The controller is ready and listening for new" + " switch connections"), @LogMessageDoc(message="Storage exception in controller " + "updates loop; terminating process", explanation=ERROR_DATABASE, recommendation=LogMessageDoc.CHECK_CONTROLLER), @LogMessageDoc(level="ERROR", message="Exception in controller updates loop", explanation="Failed to dispatch controller event", recommendation=LogMessageDoc.GENERIC_ACTION) }) public void run() { if (log.isDebugEnabled()) { logListeners(); } try { final ServerBootstrap bootstrap = createServerBootStrap(); bootstrap.setOption("reuseAddr", true); bootstrap.setOption("child.keepAlive", true); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE); ChannelPipelineFactory pfact = new OpenflowPipelineFactory(this, null); bootstrap.setPipelineFactory(pfact); InetSocketAddress sa = new InetSocketAddress(openFlowPort); final ChannelGroup cg = new DefaultChannelGroup(); cg.add(bootstrap.bind(sa)); log.info("Listening for switch connections on {}", sa); } catch (Exception e) { throw new RuntimeException(e); } // main loop while (true) { try { IUpdate update = updates.take(); update.dispatch(); } catch (InterruptedException e) { return; } catch (StorageException e) { log.error("Storage exception in controller " + "updates loop; terminating process", e); return; } catch (Exception e) { log.error("Exception in controller updates loop", e); } } } private ServerBootstrap createServerBootStrap() { if (workerThreads == 0) { return new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); } else { return new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), workerThreads)); } } public void setConfigParams(Map<String, String> configParams) { String ofPort = configParams.get("openflowport"); if (ofPort != null) { this.openFlowPort = Integer.parseInt(ofPort); } log.debug("OpenFlow port set to {}", this.openFlowPort); String threads = configParams.get("workerthreads"); if (threads != null) { this.workerThreads = Integer.parseInt(threads); } log.debug("Number of worker threads set to {}", this.workerThreads); String controllerId = configParams.get("controllerid"); if (controllerId != null) { this.controllerId = controllerId; } log.debug("ControllerId set to {}", this.controllerId); } private void initVendorMessages() { // Configure openflowj to be able to parse the role request/reply // vendor messages. OFNiciraVendorExtensions.initialize(); } /** * Initialize internal data structures */ public void init(Map<String, String> configParams) { // These data structures are initialized here because other // module's startUp() might be called before ours this.messageListeners = new ConcurrentHashMap<OFType, ListenerDispatcher<OFType, IOFMessageListener>>(); this.switchListeners = new CopyOnWriteArraySet<IOFSwitchListener>(); this.haListeners = new CopyOnWriteArraySet<IHAListener>(); this.switchBindingMap = new ConcurrentHashMap<String, IOFSwitchDriver>(); this.switchDescSortedList = new ArrayList<String>(); this.activeSwitches = new ConcurrentHashMap<Long, IOFSwitch>(); this.connectedSwitches = new HashSet<IOFSwitch>(); this.controllerNodeIPsCache = new HashMap<String, String>(); this.updates = new LinkedBlockingQueue<IUpdate>(); this.factory = new BasicFactory(); this.providerMap = new HashMap<String, List<IInfoProvider>>(); setConfigParams(configParams); this.role = getInitialRole(configParams); this.notifiedRole = this.role; this.roleChanger = new RoleChanger(this); initVendorMessages(); this.systemStartTime = System.currentTimeMillis(); } /** * Startup all of the controller's components */ @LogMessageDoc(message="Waiting for storage source", explanation="The system database is not yet ready", recommendation="If this message persists, this indicates " + "that the system database has failed to start. " + LogMessageDoc.CHECK_CONTROLLER) public void startupComponents() { // Create the table names we use storageSource.createTable(CONTROLLER_TABLE_NAME, null); storageSource.createTable(CONTROLLER_INTERFACE_TABLE_NAME, null); storageSource.createTable(SWITCH_CONFIG_TABLE_NAME, null); storageSource.setTablePrimaryKeyName(CONTROLLER_TABLE_NAME, CONTROLLER_ID); storageSource.addListener(CONTROLLER_INTERFACE_TABLE_NAME, this); while (true) { try { updateControllerInfo(); break; } catch (StorageException e) { log.info("Waiting for storage source"); try { Thread.sleep(1000); } catch (InterruptedException e1) { } } } // Startup load monitoring if (overload_drop) { this.loadmonitor.startMonitoring( this.threadPool.getScheduledExecutor()); } // Add our REST API restApi.addRestletRoutable(new CoreWebRoutable()); } @Override public void addInfoProvider(String type, IInfoProvider provider) { if (!providerMap.containsKey(type)) { providerMap.put(type, new ArrayList<IInfoProvider>()); } providerMap.get(type).add(provider); } @Override public void removeInfoProvider(String type, IInfoProvider provider) { if (!providerMap.containsKey(type)) { log.debug("Provider type {} doesn't exist.", type); return; } providerMap.get(type).remove(provider); } @Override public Map<String, Object> getControllerInfo(String type) { if (!providerMap.containsKey(type)) return null; Map<String, Object> result = new LinkedHashMap<String, Object>(); for (IInfoProvider provider : providerMap.get(type)) { result.putAll(provider.getInfo(type)); } return result; } @Override public void addHAListener(IHAListener listener) { this.haListeners.add(listener); } @Override public void removeHAListener(IHAListener listener) { this.haListeners.remove(listener); } /** * Handle changes to the controller nodes IPs and dispatch update. */ @SuppressWarnings("unchecked") protected void handleControllerNodeIPChanges() { HashMap<String,String> curControllerNodeIPs = new HashMap<String,String>(); HashMap<String,String> addedControllerNodeIPs = new HashMap<String,String>(); HashMap<String,String> removedControllerNodeIPs =new HashMap<String,String>(); String[] colNames = { CONTROLLER_INTERFACE_CONTROLLER_ID, CONTROLLER_INTERFACE_TYPE, CONTROLLER_INTERFACE_NUMBER, CONTROLLER_INTERFACE_DISCOVERED_IP }; synchronized(controllerNodeIPsCache) { // We currently assume that interface Ethernet0 is the relevant // controller interface. Might change. // We could (should?) implement this using // predicates, but creating the individual and compound predicate // seems more overhead then just checking every row. Particularly, // since the number of rows is small and changes infrequent IResultSet res = storageSource.executeQuery(CONTROLLER_INTERFACE_TABLE_NAME, colNames,null, null); while (res.next()) { if (res.getString(CONTROLLER_INTERFACE_TYPE).equals("Ethernet") && res.getInt(CONTROLLER_INTERFACE_NUMBER) == 0) { String controllerID = res.getString(CONTROLLER_INTERFACE_CONTROLLER_ID); String discoveredIP = res.getString(CONTROLLER_INTERFACE_DISCOVERED_IP); String curIP = controllerNodeIPsCache.get(controllerID); curControllerNodeIPs.put(controllerID, discoveredIP); if (curIP == null) { // new controller node IP addedControllerNodeIPs.put(controllerID, discoveredIP); } else if (curIP != discoveredIP) { // IP changed removedControllerNodeIPs.put(controllerID, curIP); addedControllerNodeIPs.put(controllerID, discoveredIP); } } } // Now figure out if rows have been deleted. We can't use the // rowKeys from rowsDeleted directly, since the tables primary // key is a compound that we can't disassemble Set<String> curEntries = curControllerNodeIPs.keySet(); Set<String> removedEntries = controllerNodeIPsCache.keySet(); removedEntries.removeAll(curEntries); for (String removedControllerID : removedEntries) removedControllerNodeIPs.put(removedControllerID, controllerNodeIPsCache.get(removedControllerID)); controllerNodeIPsCache = (HashMap<String, String>) curControllerNodeIPs.clone(); HAControllerNodeIPUpdate update = new HAControllerNodeIPUpdate( curControllerNodeIPs, addedControllerNodeIPs, removedControllerNodeIPs); if (!removedControllerNodeIPs.isEmpty() || !addedControllerNodeIPs.isEmpty()) { try { this.updates.put(update); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } } } @Override public Map<String, String> getControllerNodeIPs() { // We return a copy of the mapping so we can guarantee that // the mapping return is the same as one that will be (or was) // dispatched to IHAListeners HashMap<String,String> retval = new HashMap<String,String>(); synchronized(controllerNodeIPsCache) { retval.putAll(controllerNodeIPsCache); } return retval; } @Override public void rowsModified(String tableName, Set<Object> rowKeys) { if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) { handleControllerNodeIPChanges(); } } @Override public void rowsDeleted(String tableName, Set<Object> rowKeys) { if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) { handleControllerNodeIPChanges(); } } @Override public long getSystemStartTime() { return (this.systemStartTime); } @Override public void setAlwaysClearFlowsOnSwAdd(boolean value) { this.alwaysClearFlowsOnSwAdd = value; } public boolean getAlwaysClearFlowsOnSwAdd() { return this.alwaysClearFlowsOnSwAdd; } @Override public void addOFSwitchDriver(String description, IOFSwitchDriver driver) { IOFSwitchDriver existingDriver = switchBindingMap.get(description); if (existingDriver != null) { log.warn("Failed to add OFSwitch driver for {}, " + "already registered", description); return; } switchBindingMap.put(description, driver); // Sort so we match the longest string first int index = -1; for (String desc : switchDescSortedList) { if (description.compareTo(desc) > 0) { index = switchDescSortedList.indexOf(desc); switchDescSortedList.add(index, description); break; } } if (index == -1) { // append to list switchDescSortedList.add(description); } } }
true
true
protected void processOFMessage(OFMessage m) throws IOException, SwitchStateException { boolean shouldHandleMessage = false; switch (m.getType()) { case HELLO: if (log.isTraceEnabled()) log.trace("HELLO from {}", sw); if (state.hsState.equals(HandshakeState.START)) { state.hsState = HandshakeState.HELLO; sendHandShakeMessage(OFType.FEATURES_REQUEST); } else { throw new SwitchStateException("Unexpected HELLO from " + sw); } break; case ECHO_REQUEST: OFEchoReply reply = (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY); reply.setXid(m.getXid()); List<OFMessage> msglist = new ArrayList<OFMessage>(1); msglist.add(reply); channel.write(msglist); break; case ECHO_REPLY: break; case FEATURES_REPLY: if (log.isTraceEnabled()) log.trace("Features Reply from {}", sw); if (state.hsState.equals(HandshakeState.HELLO)) { sendFeatureReplyConfiguration(); state.featuresReply = (OFFeaturesReply) m; state.hsState = HandshakeState.FEATURES_REPLY; } else { // return results to rest api caller sw.setFeaturesReply((OFFeaturesReply) m); sw.deliverOFFeaturesReply(m); } break; case GET_CONFIG_REPLY: if (log.isTraceEnabled()) log.trace("Get config reply from {}", sw); if (!state.hsState.equals(HandshakeState.FEATURES_REPLY)) { String em = "Unexpected GET_CONFIG_REPLY from " + sw; throw new SwitchStateException(em); } OFGetConfigReply cr = (OFGetConfigReply) m; if (cr.getMissSendLength() == (short)0xffff) { log.trace("Config Reply from {} confirms " + "miss length set to 0xffff", sw); } else { log.warn("Config Reply from {} has " + "miss length set to {}", sw, cr.getMissSendLength() & 0xffff); } state.hasGetConfigReply = true; checkSwitchReady(); break; case VENDOR: shouldHandleMessage = handleVendorMessage((OFVendor)m); break; case ERROR: // TODO: we need better error handling. Especially for // request/reply style message (stats, roles) we should have // a unified way to lookup the xid in the error message. // This will probable involve rewriting the way we handle // request/reply style messages. OFError error = (OFError) m; if (roleChanger.checkFirstPendingRoleRequestXid( sw, error.getXid())) { roleChanger.deliverRoleRequestError(sw, error); } else { logError(sw, error); } break; case STATS_REPLY: if (state.hsState.ordinal() < HandshakeState.FEATURES_REPLY.ordinal()) { String em = "Unexpected STATS_REPLY from " + sw; throw new SwitchStateException(em); } if (sw == null) { processSwitchDescReply((OFStatisticsReply) m); } else { sw.deliverStatisticsReply(m); } break; case PORT_STATUS: if (sw != null) { handlePortStatusMessage(sw, (OFPortStatus)m); shouldHandleMessage = true; } else { // Queue till we complete driver binding state.queuedOFMessages.add(m); } break; default: shouldHandleMessage = true; break; } if (shouldHandleMessage) { // WARNING: sw is null if handshake is not complete if (!state.hsState.equals(HandshakeState.READY)) { log.debug("Ignoring message type {} received " + "from switch {} before switch is " + "fully configured.", m.getType(), sw); } else { sw.getListenerReadLock().lock(); try { if (sw.isConnected()) { // Only dispatch message if the switch is in the // activeSwitch map and if the switches role is // not slave and the modules are not in slave // TODO: Should we dispatch messages that we expect to // receive when we're in the slave role, e.g. port // status messages? Since we're "hiding" switches from // the listeners when we're in the slave role, then it // seems a little weird to dispatch port status messages // to them. On the other hand there might be special // modules that care about all of the connected switches // and would like to receive port status notifications. if (sw.getHARole() == Role.SLAVE || notifiedRole == Role.SLAVE || !activeSwitches.containsKey(sw.getId())) { // Don't log message if it's a port status message // since we expect to receive those from the switch // and don't want to emit spurious messages. if (m.getType() != OFType.PORT_STATUS) { log.debug("Ignoring message type {} received " + "from switch {} while in the slave role.", m.getType(), sw); } } else { handleMessage(sw, m, null); } } } finally { sw.getListenerReadLock().unlock(); } } } }
protected void processOFMessage(OFMessage m) throws IOException, SwitchStateException { boolean shouldHandleMessage = false; switch (m.getType()) { case HELLO: if (log.isTraceEnabled()) log.trace("HELLO from {}", sw); if (state.hsState.equals(HandshakeState.START)) { state.hsState = HandshakeState.HELLO; sendHandShakeMessage(OFType.FEATURES_REQUEST); } else { throw new SwitchStateException("Unexpected HELLO from " + sw); } break; case ECHO_REQUEST: OFEchoReply reply = (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY); reply.setXid(m.getXid()); List<OFMessage> msglist = new ArrayList<OFMessage>(1); msglist.add(reply); channel.write(msglist); break; case ECHO_REPLY: break; case FEATURES_REPLY: if (log.isTraceEnabled()) log.trace("Features Reply from {}", sw); if (state.hsState.equals(HandshakeState.HELLO)) { sendFeatureReplyConfiguration(); state.featuresReply = (OFFeaturesReply) m; state.hsState = HandshakeState.FEATURES_REPLY; } else { // return results to rest api caller sw.setFeaturesReply((OFFeaturesReply) m); sw.deliverOFFeaturesReply(m); } break; case GET_CONFIG_REPLY: if (log.isTraceEnabled()) log.trace("Get config reply from {}", sw); if (!state.hsState.equals(HandshakeState.FEATURES_REPLY)) { String em = "Unexpected GET_CONFIG_REPLY from " + sw; throw new SwitchStateException(em); } OFGetConfigReply cr = (OFGetConfigReply) m; if (cr.getMissSendLength() == (short)0xffff) { log.trace("Config Reply from {} confirms " + "miss length set to 0xffff", sw); } else { log.warn("Config Reply from {} has " + "miss length set to {}", sw, cr.getMissSendLength() & 0xffff); } state.hasGetConfigReply = true; checkSwitchReady(); break; case VENDOR: shouldHandleMessage = handleVendorMessage((OFVendor)m); break; case ERROR: // TODO: we need better error handling. Especially for // request/reply style message (stats, roles) we should have // a unified way to lookup the xid in the error message. // This will probable involve rewriting the way we handle // request/reply style messages. OFError error = (OFError) m; if (roleChanger.checkFirstPendingRoleRequestXid( sw, error.getXid())) { roleChanger.deliverRoleRequestError(sw, error); } else { logError(sw, error); // allow registered listeners to receive error messages shouldHandleMessage = true; } break; case STATS_REPLY: if (state.hsState.ordinal() < HandshakeState.FEATURES_REPLY.ordinal()) { String em = "Unexpected STATS_REPLY from " + sw; throw new SwitchStateException(em); } if (sw == null) { processSwitchDescReply((OFStatisticsReply) m); } else { sw.deliverStatisticsReply(m); } break; case PORT_STATUS: if (sw != null) { handlePortStatusMessage(sw, (OFPortStatus)m); shouldHandleMessage = true; } else { // Queue till we complete driver binding state.queuedOFMessages.add(m); } break; default: shouldHandleMessage = true; break; } if (shouldHandleMessage) { // WARNING: sw is null if handshake is not complete if (!state.hsState.equals(HandshakeState.READY)) { log.debug("Ignoring message type {} received " + "from switch {} before switch is " + "fully configured.", m.getType(), sw); } else { sw.getListenerReadLock().lock(); try { if (sw.isConnected()) { // Only dispatch message if the switch is in the // activeSwitch map and if the switches role is // not slave and the modules are not in slave // TODO: Should we dispatch messages that we expect to // receive when we're in the slave role, e.g. port // status messages? Since we're "hiding" switches from // the listeners when we're in the slave role, then it // seems a little weird to dispatch port status messages // to them. On the other hand there might be special // modules that care about all of the connected switches // and would like to receive port status notifications. if (sw.getHARole() == Role.SLAVE || notifiedRole == Role.SLAVE || !activeSwitches.containsKey(sw.getId())) { // Don't log message if it's a port status message // since we expect to receive those from the switch // and don't want to emit spurious messages. if (m.getType() != OFType.PORT_STATUS) { log.debug("Ignoring message type {} received " + "from switch {} while in the slave role.", m.getType(), sw); } } else { handleMessage(sw, m, null); } } } finally { sw.getListenerReadLock().unlock(); } } } }
diff --git a/server/src/main/java/org/socialhistoryservices/pid/controllers/KeysController.java b/server/src/main/java/org/socialhistoryservices/pid/controllers/KeysController.java index 39cf1b2..f14ee9d 100644 --- a/server/src/main/java/org/socialhistoryservices/pid/controllers/KeysController.java +++ b/server/src/main/java/org/socialhistoryservices/pid/controllers/KeysController.java @@ -1,88 +1,88 @@ /* * The PID webservice offers SOAP methods to manage the Handle System(r) resolution technology. * * Copyright (C) 2010-2011, International Institute of Social History * * 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 org.socialhistoryservices.pid.controllers; import org.socialhistoryservices.pid.util.NamingAuthority; import org.socialhistoryservices.security.MongoTokenStore; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.ClientDetails; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.ClientToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.RandomValueTokenServices; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.HashSet; import java.util.List; @Controller public class KeysController { private MongoTokenStore mongoTokenStore; private RandomValueTokenServices tokenServices; private ClientDetailsService clientDetailsService; private static String clientId = "pid-webservice-client"; // Should be the same as in the Spring ClientProvider @RequestMapping("/admin/keys") public ModelAndView list( @RequestParam(value = "token", required = false) String refresh_token) { ModelAndView mav = new ModelAndView("keys"); final SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); List<String> nas = NamingAuthority.getNaRole(authentication); if (refresh_token != null) { mongoTokenStore.removeAccessTokenUsingRefreshToken(refresh_token); mongoTokenStore.removeRefreshToken(refresh_token); } OAuth2AccessToken token = mongoTokenStore.selectKeys(authentication.getName()); if (token == null) { final ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); final ClientToken clientToken = new ClientToken(clientId, new HashSet<String>(clientDetails.getResourceIds()), clientDetails.getClientSecret(), new HashSet<String>(clientDetails.getScope()), clientDetails.getAuthorities()); final OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(clientToken, authentication); token = tokenServices.createAccessToken(oAuth2Authentication); - mongoTokenStore.storeAccessToken(token, oAuth2Authentication); + //mongoTokenStore.storeAccessToken(token, oAuth2Authentication); } mav.addObject("token", token); mav.addObject("nas", nas); return mav; } public void setMongoTokenStore(MongoTokenStore mongoTokenStore) { this.mongoTokenStore = mongoTokenStore; } public void setTokenServices(RandomValueTokenServices tokenServices) { this.tokenServices = tokenServices; } public void setClientDetails(org.springframework.security.oauth2.provider.ClientDetailsService clientDetailsService) { this.clientDetailsService = clientDetailsService; } }
true
true
public ModelAndView list( @RequestParam(value = "token", required = false) String refresh_token) { ModelAndView mav = new ModelAndView("keys"); final SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); List<String> nas = NamingAuthority.getNaRole(authentication); if (refresh_token != null) { mongoTokenStore.removeAccessTokenUsingRefreshToken(refresh_token); mongoTokenStore.removeRefreshToken(refresh_token); } OAuth2AccessToken token = mongoTokenStore.selectKeys(authentication.getName()); if (token == null) { final ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); final ClientToken clientToken = new ClientToken(clientId, new HashSet<String>(clientDetails.getResourceIds()), clientDetails.getClientSecret(), new HashSet<String>(clientDetails.getScope()), clientDetails.getAuthorities()); final OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(clientToken, authentication); token = tokenServices.createAccessToken(oAuth2Authentication); mongoTokenStore.storeAccessToken(token, oAuth2Authentication); } mav.addObject("token", token); mav.addObject("nas", nas); return mav; }
public ModelAndView list( @RequestParam(value = "token", required = false) String refresh_token) { ModelAndView mav = new ModelAndView("keys"); final SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); List<String> nas = NamingAuthority.getNaRole(authentication); if (refresh_token != null) { mongoTokenStore.removeAccessTokenUsingRefreshToken(refresh_token); mongoTokenStore.removeRefreshToken(refresh_token); } OAuth2AccessToken token = mongoTokenStore.selectKeys(authentication.getName()); if (token == null) { final ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); final ClientToken clientToken = new ClientToken(clientId, new HashSet<String>(clientDetails.getResourceIds()), clientDetails.getClientSecret(), new HashSet<String>(clientDetails.getScope()), clientDetails.getAuthorities()); final OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(clientToken, authentication); token = tokenServices.createAccessToken(oAuth2Authentication); //mongoTokenStore.storeAccessToken(token, oAuth2Authentication); } mav.addObject("token", token); mav.addObject("nas", nas); return mav; }
diff --git a/m3ua/impl/src/main/java/org/mobicents/protocols/ss7/m3ua/impl/oam/M3UAShellExecutor.java b/m3ua/impl/src/main/java/org/mobicents/protocols/ss7/m3ua/impl/oam/M3UAShellExecutor.java index 1ce55f205..8a3d4a546 100644 --- a/m3ua/impl/src/main/java/org/mobicents/protocols/ss7/m3ua/impl/oam/M3UAShellExecutor.java +++ b/m3ua/impl/src/main/java/org/mobicents/protocols/ss7/m3ua/impl/oam/M3UAShellExecutor.java @@ -1,474 +1,478 @@ /* * TeleStax, Open Source Cloud Communications * Copyright 2012, Telestax Inc 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.mobicents.protocols.ss7.m3ua.impl.oam; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.mobicents.protocols.ss7.m3ua.As; import org.mobicents.protocols.ss7.m3ua.AspFactory; import org.mobicents.protocols.ss7.m3ua.ExchangeType; import org.mobicents.protocols.ss7.m3ua.Functionality; import org.mobicents.protocols.ss7.m3ua.IPSPType; import org.mobicents.protocols.ss7.m3ua.impl.AsImpl; import org.mobicents.protocols.ss7.m3ua.impl.AspFactoryImpl; import org.mobicents.protocols.ss7.m3ua.impl.M3UAManagementImpl; import org.mobicents.protocols.ss7.m3ua.impl.parameter.ParameterFactoryImpl; import org.mobicents.protocols.ss7.m3ua.parameter.NetworkAppearance; import org.mobicents.protocols.ss7.m3ua.parameter.ParameterFactory; import org.mobicents.protocols.ss7.m3ua.parameter.RoutingContext; import org.mobicents.protocols.ss7.m3ua.parameter.TrafficModeType; import org.mobicents.ss7.management.console.ShellExecutor; /** * * @author amit bhayani * */ public class M3UAShellExecutor implements ShellExecutor { private static final Logger logger = Logger.getLogger(M3UAShellExecutor.class); private M3UAManagementImpl m3uaManagement; protected ParameterFactory parameterFactory = new ParameterFactoryImpl(); public M3UAShellExecutor() { } public M3UAManagementImpl getM3uaManagement() { return m3uaManagement; } public void setM3uaManagement(M3UAManagementImpl m3uaManagement) { this.m3uaManagement = m3uaManagement; } /** * m3ua as create <as-name> <AS | SGW | IPSP> mode <SE | DE> ipspType < client | server > rc <routing-context> traffic-mode * <traffic mode> min-asp <minimum asp active for TrafficModeType.Loadshare> network-appearance <network appearance> * * @param args * @return */ private String createAs(String[] args) throws Exception { if (args.length < 5 || args.length > 17) { return M3UAOAMMessages.INVALID_COMMAND; } // Create new Rem AS String asName = args[3]; if (asName == null) { return M3UAOAMMessages.INVALID_COMMAND; } Functionality functionlaity = Functionality.getFunctionality(args[4]); ExchangeType exchangeType = null; IPSPType ipspType = null; RoutingContext rc = null; TrafficModeType trafficModeType = null; NetworkAppearance na = null; if (functionlaity == null) { return M3UAOAMMessages.INVALID_COMMAND; } int count = 5; int minAspActiveForLoadbalance = 1; while (count < args.length) { String key = args[count++]; if (key == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (key.equals("mode")) { exchangeType = ExchangeType.getExchangeType(args[count++]); if (exchangeType == null) { return M3UAOAMMessages.INVALID_COMMAND; } } else if (key.equals("ipspType")) { ipspType = IPSPType.getIPSPType(args[count++]); } else if (key.equals("rc")) { long rcLong = Long.parseLong(args[count++]); rc = parameterFactory.createRoutingContext(new long[] { rcLong }); } else if (key.equals("traffic-mode")) { trafficModeType = getTrafficModeType(args[count++]); } else if (key.equals("network-appearance")) { na = parameterFactory.createNetworkAppearance(Long.parseLong(args[count++])); } else if (key.equals("min-asp")) { minAspActiveForLoadbalance = Integer.parseInt(args[count++]); } else { return M3UAOAMMessages.INVALID_COMMAND; } } As asImpl = this.m3uaManagement.createAs(asName, functionlaity, exchangeType, ipspType, rc, trafficModeType, minAspActiveForLoadbalance, na); return String.format(M3UAOAMMessages.CREATE_AS_SUCESSFULL, asImpl.getName()); } /** * m3ua as destroy <as-name> * * @param args * @return * @throws Exception */ private String destroyAs(String[] args) throws Exception { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String asName = args[3]; if (asName == null) { return M3UAOAMMessages.INVALID_COMMAND; } AsImpl asImpl = this.m3uaManagement.destroyAs(asName); return String.format(M3UAOAMMessages.DESTROY_AS_SUCESSFULL, asName); } /** * m3ua as add <as-name> <asp-name> * * @param args * @return * @throws Exception */ private String addAspToAs(String[] args) throws Exception { if (args.length < 5) { return M3UAOAMMessages.INVALID_COMMAND; } // Add Rem ASP to Rem AS if (args[3] == null || args[4] == null) { return M3UAOAMMessages.INVALID_COMMAND; } this.m3uaManagement.assignAspToAs(args[3], args[4]); return String.format(M3UAOAMMessages.ADD_ASP_TO_AS_SUCESSFULL, args[4], args[3]); } /** * m3ua as remove <as-name> <asp-name> * * @param args * @return * @throws Exception */ private String removeAspFromAs(String[] args) throws Exception { if (args.length < 5) { return M3UAOAMMessages.INVALID_COMMAND; } // Add Rem ASP to Rem AS if (args[3] == null || args[4] == null) { return M3UAOAMMessages.INVALID_COMMAND; } this.m3uaManagement.unassignAspFromAs(args[3], args[4]); return String.format(M3UAOAMMessages.REMOVE_ASP_FROM_AS_SUCESSFULL, args[4], args[3]); } private TrafficModeType getTrafficModeType(String mode) { int iMode = -1; if (mode == null) { return null; } else if (mode.equals("loadshare")) { iMode = TrafficModeType.Loadshare; } else if (mode.equals("override")) { iMode = TrafficModeType.Override; } else if (mode.equals("broadcast")) { iMode = TrafficModeType.Broadcast; } else { return null; } return this.parameterFactory.createTrafficModeType(iMode); } private String showAspFactories() { List<AspFactory> aspfactories = this.m3uaManagement.getAspfactories(); if (aspfactories.size() == 0) { return M3UAOAMMessages.NO_ASP_DEFINED_YET; } StringBuffer sb = new StringBuffer(); for (AspFactory aspFactory : aspfactories) { AspFactoryImpl aspFactoryImpl = (AspFactoryImpl) aspFactory; sb.append(M3UAOAMMessages.NEW_LINE); aspFactoryImpl.show(sb); sb.append(M3UAOAMMessages.NEW_LINE); } return sb.toString(); } private String showRoutes() { Map<String, As[]> route = this.m3uaManagement.getRoute(); if (route.size() == 0) { return M3UAOAMMessages.NO_ROUTE_DEFINED_YET; } StringBuffer sb = new StringBuffer(); Set<String> keys = route.keySet(); for (String key : keys) { As[] asList = route.get(key); sb.append(M3UAOAMMessages.NEW_LINE); sb.append(key); sb.append(M3UAOAMMessages.TAB); for (int i = 0; i < asList.length; i++) { As asImpl = asList[i]; if (asImpl != null) { sb.append(asImpl.getName()); sb.append(M3UAOAMMessages.COMMA); } } sb.append(M3UAOAMMessages.NEW_LINE); } return sb.toString(); } private String showAs() { List<As> appServers = this.m3uaManagement.getAppServers(); if (appServers.size() == 0) { return M3UAOAMMessages.NO_AS_DEFINED_YET; } StringBuffer sb = new StringBuffer(); for (As as : appServers) { AsImpl asImpl = (AsImpl) as; sb.append(M3UAOAMMessages.NEW_LINE); asImpl.show(sb); sb.append(M3UAOAMMessages.NEW_LINE); } return sb.toString(); } private String executeM3UA(String[] args) { try { if (args.length < 3 || args.length > 15) { // any command will have atleast 3 args return M3UAOAMMessages.INVALID_COMMAND; } if (args[1] == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (args[1].equals("as")) { // related to rem AS for SigGatewayImpl String rasCmd = args[2]; if (rasCmd == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (rasCmd.equals("create")) { return this.createAs(args); } else if (rasCmd.equals("destroy")) { return this.destroyAs(args); } else if (rasCmd.equals("add")) { return this.addAspToAs(args); } else if (rasCmd.equals("remove")) { return this.removeAspFromAs(args); } else if (rasCmd.equals("show")) { return this.showAs(); } return M3UAOAMMessages.INVALID_COMMAND; } else if (args[1].equals("asp")) { if (args.length < 3 || args.length > 9) { return M3UAOAMMessages.INVALID_COMMAND; } // related to rem AS for SigGatewayImpl String raspCmd = args[2]; if (raspCmd == null) { return M3UAOAMMessages.INVALID_COMMAND; } else if (raspCmd.equals("create")) { // Create new ASP if (args.length < 5) { return M3UAOAMMessages.INVALID_COMMAND; } String aspname = args[3]; String assocName = args[4]; if (aspname == null || assocName == null) { return M3UAOAMMessages.INVALID_COMMAND; } AspFactory factory = null; if (args.length == 5) { factory = this.m3uaManagement.createAspFactory(aspname, assocName, false); } else { int count = 5; - long aspid = 0; + long aspid = -1; boolean isHeartBeatEnabled = false; while (count < args.length) { String key = args[count++]; if (key == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (key.equals("aspid")) { aspid = Long.parseLong(args[count++]); } else if (key.equals("heartbeat")) { isHeartBeatEnabled = Boolean.parseBoolean(args[count++]); } else { return M3UAOAMMessages.INVALID_COMMAND; } } - factory = this.m3uaManagement.createAspFactory(aspname, assocName, aspid, isHeartBeatEnabled); + if(aspid == -1){ + factory = this.m3uaManagement.createAspFactory(aspname, assocName, isHeartBeatEnabled); + } else { + factory = this.m3uaManagement.createAspFactory(aspname, assocName, aspid, isHeartBeatEnabled); + } } return String.format(M3UAOAMMessages.CREATE_ASP_SUCESSFULL, factory.getName()); } else if (raspCmd.equals("destroy")) { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String aspName = args[3]; this.m3uaManagement.destroyAspFactory(aspName); return String.format(M3UAOAMMessages.DESTROY_ASP_SUCESSFULL, aspName); } else if (raspCmd.equals("show")) { return this.showAspFactories(); } else if (raspCmd.equals("start")) { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String aspName = args[3]; this.m3uaManagement.startAsp(aspName); return String.format(M3UAOAMMessages.ASP_START_SUCESSFULL, aspName); } else if (raspCmd.equals("stop")) { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String aspName = args[3]; this.m3uaManagement.stopAsp(aspName); return String.format(M3UAOAMMessages.ASP_STOP_SUCESSFULL, aspName); } return M3UAOAMMessages.INVALID_COMMAND; } else if (args[1].equals("route")) { String routeCmd = args[2]; if (routeCmd == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (routeCmd.equals("add")) { if (args.length < 5 || args.length > 7) { return M3UAOAMMessages.INVALID_COMMAND; } int count = 3; String asName = args[count++]; int dpc = -1; int opc = -1; int si = -1; if (asName == null) { return M3UAOAMMessages.INVALID_COMMAND; } dpc = Integer.parseInt(args[count++]); while (count < args.length) { opc = Integer.parseInt(args[count++]); si = Integer.parseInt(args[count++]); } this.m3uaManagement.addRoute(dpc, opc, si, asName); return String.format(M3UAOAMMessages.ADD_ROUTE_AS_FOR_DPC_SUCCESSFULL, asName, dpc); } if (routeCmd.equals("remove")) { if (args.length < 5 || args.length > 7) { return M3UAOAMMessages.INVALID_COMMAND; } int count = 3; String asName = args[count++]; int dpc = -1; int opc = -1; int si = -1; if (asName == null) { return M3UAOAMMessages.INVALID_COMMAND; } dpc = Integer.parseInt(args[count++]); while (count < args.length) { opc = Integer.parseInt(args[count++]); si = Integer.parseInt(args[count++]); } this.m3uaManagement.removeRoute(dpc, opc, si, asName); return String.format(M3UAOAMMessages.REMOVE_AS_ROUTE_FOR_DPC_SUCCESSFULL, asName, dpc); } if (routeCmd.equals("show")) { return this.showRoutes(); } } return M3UAOAMMessages.INVALID_COMMAND; } catch (Exception e) { logger.error(String.format("Error while executing comand %s", Arrays.toString(args)), e); return e.getMessage(); } } public String execute(String[] args) { if (args[0].equals("m3ua")) { return this.executeM3UA(args); } return M3UAOAMMessages.INVALID_COMMAND; } /* * (non-Javadoc) * * @see org.mobicents.ss7.management.console.ShellExecutor#handles(java.lang. String) */ @Override public boolean handles(String command) { return (command.startsWith("m3ua")); } }
false
true
private String executeM3UA(String[] args) { try { if (args.length < 3 || args.length > 15) { // any command will have atleast 3 args return M3UAOAMMessages.INVALID_COMMAND; } if (args[1] == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (args[1].equals("as")) { // related to rem AS for SigGatewayImpl String rasCmd = args[2]; if (rasCmd == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (rasCmd.equals("create")) { return this.createAs(args); } else if (rasCmd.equals("destroy")) { return this.destroyAs(args); } else if (rasCmd.equals("add")) { return this.addAspToAs(args); } else if (rasCmd.equals("remove")) { return this.removeAspFromAs(args); } else if (rasCmd.equals("show")) { return this.showAs(); } return M3UAOAMMessages.INVALID_COMMAND; } else if (args[1].equals("asp")) { if (args.length < 3 || args.length > 9) { return M3UAOAMMessages.INVALID_COMMAND; } // related to rem AS for SigGatewayImpl String raspCmd = args[2]; if (raspCmd == null) { return M3UAOAMMessages.INVALID_COMMAND; } else if (raspCmd.equals("create")) { // Create new ASP if (args.length < 5) { return M3UAOAMMessages.INVALID_COMMAND; } String aspname = args[3]; String assocName = args[4]; if (aspname == null || assocName == null) { return M3UAOAMMessages.INVALID_COMMAND; } AspFactory factory = null; if (args.length == 5) { factory = this.m3uaManagement.createAspFactory(aspname, assocName, false); } else { int count = 5; long aspid = 0; boolean isHeartBeatEnabled = false; while (count < args.length) { String key = args[count++]; if (key == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (key.equals("aspid")) { aspid = Long.parseLong(args[count++]); } else if (key.equals("heartbeat")) { isHeartBeatEnabled = Boolean.parseBoolean(args[count++]); } else { return M3UAOAMMessages.INVALID_COMMAND; } } factory = this.m3uaManagement.createAspFactory(aspname, assocName, aspid, isHeartBeatEnabled); } return String.format(M3UAOAMMessages.CREATE_ASP_SUCESSFULL, factory.getName()); } else if (raspCmd.equals("destroy")) { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String aspName = args[3]; this.m3uaManagement.destroyAspFactory(aspName); return String.format(M3UAOAMMessages.DESTROY_ASP_SUCESSFULL, aspName); } else if (raspCmd.equals("show")) { return this.showAspFactories(); } else if (raspCmd.equals("start")) { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String aspName = args[3]; this.m3uaManagement.startAsp(aspName); return String.format(M3UAOAMMessages.ASP_START_SUCESSFULL, aspName); } else if (raspCmd.equals("stop")) { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String aspName = args[3]; this.m3uaManagement.stopAsp(aspName); return String.format(M3UAOAMMessages.ASP_STOP_SUCESSFULL, aspName); } return M3UAOAMMessages.INVALID_COMMAND; } else if (args[1].equals("route")) { String routeCmd = args[2]; if (routeCmd == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (routeCmd.equals("add")) { if (args.length < 5 || args.length > 7) { return M3UAOAMMessages.INVALID_COMMAND; } int count = 3; String asName = args[count++]; int dpc = -1; int opc = -1; int si = -1; if (asName == null) { return M3UAOAMMessages.INVALID_COMMAND; } dpc = Integer.parseInt(args[count++]); while (count < args.length) { opc = Integer.parseInt(args[count++]); si = Integer.parseInt(args[count++]); } this.m3uaManagement.addRoute(dpc, opc, si, asName); return String.format(M3UAOAMMessages.ADD_ROUTE_AS_FOR_DPC_SUCCESSFULL, asName, dpc); } if (routeCmd.equals("remove")) { if (args.length < 5 || args.length > 7) { return M3UAOAMMessages.INVALID_COMMAND; } int count = 3; String asName = args[count++]; int dpc = -1; int opc = -1; int si = -1; if (asName == null) { return M3UAOAMMessages.INVALID_COMMAND; } dpc = Integer.parseInt(args[count++]); while (count < args.length) { opc = Integer.parseInt(args[count++]); si = Integer.parseInt(args[count++]); } this.m3uaManagement.removeRoute(dpc, opc, si, asName); return String.format(M3UAOAMMessages.REMOVE_AS_ROUTE_FOR_DPC_SUCCESSFULL, asName, dpc); } if (routeCmd.equals("show")) { return this.showRoutes(); } } return M3UAOAMMessages.INVALID_COMMAND; } catch (Exception e) { logger.error(String.format("Error while executing comand %s", Arrays.toString(args)), e); return e.getMessage(); } }
private String executeM3UA(String[] args) { try { if (args.length < 3 || args.length > 15) { // any command will have atleast 3 args return M3UAOAMMessages.INVALID_COMMAND; } if (args[1] == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (args[1].equals("as")) { // related to rem AS for SigGatewayImpl String rasCmd = args[2]; if (rasCmd == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (rasCmd.equals("create")) { return this.createAs(args); } else if (rasCmd.equals("destroy")) { return this.destroyAs(args); } else if (rasCmd.equals("add")) { return this.addAspToAs(args); } else if (rasCmd.equals("remove")) { return this.removeAspFromAs(args); } else if (rasCmd.equals("show")) { return this.showAs(); } return M3UAOAMMessages.INVALID_COMMAND; } else if (args[1].equals("asp")) { if (args.length < 3 || args.length > 9) { return M3UAOAMMessages.INVALID_COMMAND; } // related to rem AS for SigGatewayImpl String raspCmd = args[2]; if (raspCmd == null) { return M3UAOAMMessages.INVALID_COMMAND; } else if (raspCmd.equals("create")) { // Create new ASP if (args.length < 5) { return M3UAOAMMessages.INVALID_COMMAND; } String aspname = args[3]; String assocName = args[4]; if (aspname == null || assocName == null) { return M3UAOAMMessages.INVALID_COMMAND; } AspFactory factory = null; if (args.length == 5) { factory = this.m3uaManagement.createAspFactory(aspname, assocName, false); } else { int count = 5; long aspid = -1; boolean isHeartBeatEnabled = false; while (count < args.length) { String key = args[count++]; if (key == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (key.equals("aspid")) { aspid = Long.parseLong(args[count++]); } else if (key.equals("heartbeat")) { isHeartBeatEnabled = Boolean.parseBoolean(args[count++]); } else { return M3UAOAMMessages.INVALID_COMMAND; } } if(aspid == -1){ factory = this.m3uaManagement.createAspFactory(aspname, assocName, isHeartBeatEnabled); } else { factory = this.m3uaManagement.createAspFactory(aspname, assocName, aspid, isHeartBeatEnabled); } } return String.format(M3UAOAMMessages.CREATE_ASP_SUCESSFULL, factory.getName()); } else if (raspCmd.equals("destroy")) { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String aspName = args[3]; this.m3uaManagement.destroyAspFactory(aspName); return String.format(M3UAOAMMessages.DESTROY_ASP_SUCESSFULL, aspName); } else if (raspCmd.equals("show")) { return this.showAspFactories(); } else if (raspCmd.equals("start")) { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String aspName = args[3]; this.m3uaManagement.startAsp(aspName); return String.format(M3UAOAMMessages.ASP_START_SUCESSFULL, aspName); } else if (raspCmd.equals("stop")) { if (args.length < 4) { return M3UAOAMMessages.INVALID_COMMAND; } String aspName = args[3]; this.m3uaManagement.stopAsp(aspName); return String.format(M3UAOAMMessages.ASP_STOP_SUCESSFULL, aspName); } return M3UAOAMMessages.INVALID_COMMAND; } else if (args[1].equals("route")) { String routeCmd = args[2]; if (routeCmd == null) { return M3UAOAMMessages.INVALID_COMMAND; } if (routeCmd.equals("add")) { if (args.length < 5 || args.length > 7) { return M3UAOAMMessages.INVALID_COMMAND; } int count = 3; String asName = args[count++]; int dpc = -1; int opc = -1; int si = -1; if (asName == null) { return M3UAOAMMessages.INVALID_COMMAND; } dpc = Integer.parseInt(args[count++]); while (count < args.length) { opc = Integer.parseInt(args[count++]); si = Integer.parseInt(args[count++]); } this.m3uaManagement.addRoute(dpc, opc, si, asName); return String.format(M3UAOAMMessages.ADD_ROUTE_AS_FOR_DPC_SUCCESSFULL, asName, dpc); } if (routeCmd.equals("remove")) { if (args.length < 5 || args.length > 7) { return M3UAOAMMessages.INVALID_COMMAND; } int count = 3; String asName = args[count++]; int dpc = -1; int opc = -1; int si = -1; if (asName == null) { return M3UAOAMMessages.INVALID_COMMAND; } dpc = Integer.parseInt(args[count++]); while (count < args.length) { opc = Integer.parseInt(args[count++]); si = Integer.parseInt(args[count++]); } this.m3uaManagement.removeRoute(dpc, opc, si, asName); return String.format(M3UAOAMMessages.REMOVE_AS_ROUTE_FOR_DPC_SUCCESSFULL, asName, dpc); } if (routeCmd.equals("show")) { return this.showRoutes(); } } return M3UAOAMMessages.INVALID_COMMAND; } catch (Exception e) { logger.error(String.format("Error while executing comand %s", Arrays.toString(args)), e); return e.getMessage(); } }
diff --git a/tests/org.eclipse.acceleo.parser.tests/src/org/eclipse/acceleo/parser/tests/AcceleoParserTests.java b/tests/org.eclipse.acceleo.parser.tests/src/org/eclipse/acceleo/parser/tests/AcceleoParserTests.java index d88f856b..6d8d6986 100644 --- a/tests/org.eclipse.acceleo.parser.tests/src/org/eclipse/acceleo/parser/tests/AcceleoParserTests.java +++ b/tests/org.eclipse.acceleo.parser.tests/src/org/eclipse/acceleo/parser/tests/AcceleoParserTests.java @@ -1,184 +1,184 @@ /******************************************************************************* * Copyright (c) 2008, 2009 Obeo. * 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: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.acceleo.parser.tests; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.eclipse.acceleo.common.utils.ModelUtils; import org.eclipse.acceleo.internal.parser.cst.utils.FileContent; import org.eclipse.acceleo.parser.AcceleoParser; import org.eclipse.acceleo.parser.AcceleoParserProblem; import org.eclipse.acceleo.parser.AcceleoSourceBuffer; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Platform; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.osgi.framework.Bundle; public class AcceleoParserTests extends TestCase { private Bundle bundle; @Override protected void setUp() throws Exception { super.setUp(); bundle = Platform.getBundle("org.eclipse.acceleo.parser.tests"); } @Override protected void tearDown() throws Exception { super.tearDown(); bundle = null; } private File createFile(String pathName) { try { String fileLocation = FileLocator.resolve(bundle.getEntry(pathName)).getPath(); return new File(fileLocation); } catch (IOException e) { throw new AssertionFailedError(e.getMessage()); } catch (NullPointerException e) { /* * on the server the unit test fails with an NPE :S */ throw new AssertionFailedError(e.getMessage()); } } private URI createFileURI(String pathName) { try { String fileLocation = FileLocator.resolve(bundle.getEntry(pathName)).getPath(); return URI.createFileURI(fileLocation); } catch (IOException e) { throw new AssertionFailedError(e.getMessage()); } } public void testCompileSourceBufferEcoreAcceleoWithImport() { File file = createFile("/data/template/mtlParserEcore.mtl"); AcceleoSourceBuffer source = new AcceleoSourceBuffer(file); AcceleoParser parser = new AcceleoParser(); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = ModelUtils.createResource(URI .createURI("http://acceleo.eclipse.org/default.emtl"), resourceSet); List<URI> dependencies = new ArrayList<URI>(); dependencies.add(createFileURI("/data/template/mtlParserEcoreCommon.emtl")); parser.parse(source, resource, dependencies); assertNotNull(source.getAST()); if (source.getProblems().getList().size() > 0) { fail(source.getProblems().getMessage()); } } public void testCompileSourceBufferLibrary2textAcceleo() { File file = createFile("/data/template/mtlParserLibrary2text.mtl"); AcceleoSourceBuffer source = new AcceleoSourceBuffer(file); AcceleoParser parser = new AcceleoParser(); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = ModelUtils.createResource(URI .createURI("http://acceleo.eclipse.org/default.emtl"), resourceSet); parser.parse(source, resource, new ArrayList<URI>()); assertNotNull(source.getAST()); if (source.getProblems().getList().size() > 0) { fail(source.getProblems().getMessage()); } } public void testCompileFileLibrary2textAcceleo() { File iFile = createFile("/data/template/mtlParserLibrary2text.mtl"); URI oURI = createFileURI("/data/template/mtlParserLibrary2text.emtl"); testCompileFile(iFile, oURI, 0); } public void testCompileFileLibrary2textAcceleoWithBadOutputURI() { File iFile = createFile("/data/template/mtlParserLibrary2text.mtl"); URI oURI = URI.createURI("http://acceleo.eclipse.org"); testCompileFile(iFile, oURI, 1); } private void testCompileFile(File iFile, URI oURI, int problemsCount) { List<File> iFiles = new ArrayList<File>(); iFiles.add(iFile); AcceleoParser parser = new AcceleoParser(); List<URI> oURIs = new ArrayList<URI>(); oURIs.add(oURI); assertNull(parser.getProblems(iFile)); parser.parse(iFiles, oURIs, new ArrayList<URI>()); if (parser.getProblems(iFile).getList().size() != problemsCount) { fail("You must have " + problemsCount + " syntax errors : " + parser.getProblems(iFile).getMessage()); } if (problemsCount == 0) { assertEquals(parser.getProblems(iFile).getMessage(), ""); assertEquals(parser.getProblems(iFile).toString(), ""); } else { assertTrue(parser.getProblems(iFile).getMessage() != null); Iterator<AcceleoParserProblem> it = parser.getProblems(iFile).getList().iterator(); while (it.hasNext()) { AcceleoParserProblem parserProblem = it.next(); assertTrue(parserProblem.getMessage() != null); assertTrue(parserProblem.getLine() > 0); assertTrue(parserProblem.getPosBegin() > -1); assertTrue(parserProblem.getPosEnd() > -1); assertTrue(parserProblem.toString().length() > 0); } } parser.getProblems(iFile).clear(); } public void testIndentStrategy() { File file = createFile("/data/template/mtlIndentStrategy.mtl"); AcceleoSourceBuffer source = new AcceleoSourceBuffer(file); AcceleoParser parser = new AcceleoParser(); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = ModelUtils.createResource(URI .createURI("http://acceleo.eclipse.org/default.emtl"), resourceSet); List<URI> dependencies = new ArrayList<URI>(); parser.parse(source, resource, dependencies); assertNotNull(source.getAST()); if (source.getProblems().getList().size() > 0) { fail(source.getProblems().getMessage()); } String[] results = {"\n", "\n", "\t\t", "\n", "", "\t\t", "\n", "", "\t", "\n", "\t\t", "\n", "", "", - "\t\t\t", "\n", "", "\t\t\t", "\n", "", "\n", "\n\t\t", "\n", ""}; + "\t\t\t", "\n", "", "\t\t\t", "\n", "", "\n", "\n\t\t", "\n", "\n" }; int i = -1; StringBuffer report = new StringBuffer(); Iterator<EObject> it = resource.getContents().get(0).eAllContents(); while (it.hasNext()) { - EObject eObject = (EObject)it.next(); + EObject eObject = it.next(); if (eObject instanceof org.eclipse.ocl.ecore.StringLiteralExp) { i++; org.eclipse.ocl.ecore.StringLiteralExp literal = (org.eclipse.ocl.ecore.StringLiteralExp)eObject; String symbol = literal.getStringSymbol().replaceAll("\r", ""); if (i >= results.length || !results[i].equals(symbol)) { int line = FileContent.lineNumber(source.getBuffer(), literal.getStartPosition()); report.append("New value at line " + line + " [" + i + "] = '" + symbol + "'\n"); } } } if (report.length() > 0) { System.out.print(report); fail(report.toString()); } } }
false
true
public void testIndentStrategy() { File file = createFile("/data/template/mtlIndentStrategy.mtl"); AcceleoSourceBuffer source = new AcceleoSourceBuffer(file); AcceleoParser parser = new AcceleoParser(); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = ModelUtils.createResource(URI .createURI("http://acceleo.eclipse.org/default.emtl"), resourceSet); List<URI> dependencies = new ArrayList<URI>(); parser.parse(source, resource, dependencies); assertNotNull(source.getAST()); if (source.getProblems().getList().size() > 0) { fail(source.getProblems().getMessage()); } String[] results = {"\n", "\n", "\t\t", "\n", "", "\t\t", "\n", "", "\t", "\n", "\t\t", "\n", "", "", "\t\t\t", "\n", "", "\t\t\t", "\n", "", "\n", "\n\t\t", "\n", ""}; int i = -1; StringBuffer report = new StringBuffer(); Iterator<EObject> it = resource.getContents().get(0).eAllContents(); while (it.hasNext()) { EObject eObject = (EObject)it.next(); if (eObject instanceof org.eclipse.ocl.ecore.StringLiteralExp) { i++; org.eclipse.ocl.ecore.StringLiteralExp literal = (org.eclipse.ocl.ecore.StringLiteralExp)eObject; String symbol = literal.getStringSymbol().replaceAll("\r", ""); if (i >= results.length || !results[i].equals(symbol)) { int line = FileContent.lineNumber(source.getBuffer(), literal.getStartPosition()); report.append("New value at line " + line + " [" + i + "] = '" + symbol + "'\n"); } } } if (report.length() > 0) { System.out.print(report); fail(report.toString()); } }
public void testIndentStrategy() { File file = createFile("/data/template/mtlIndentStrategy.mtl"); AcceleoSourceBuffer source = new AcceleoSourceBuffer(file); AcceleoParser parser = new AcceleoParser(); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = ModelUtils.createResource(URI .createURI("http://acceleo.eclipse.org/default.emtl"), resourceSet); List<URI> dependencies = new ArrayList<URI>(); parser.parse(source, resource, dependencies); assertNotNull(source.getAST()); if (source.getProblems().getList().size() > 0) { fail(source.getProblems().getMessage()); } String[] results = {"\n", "\n", "\t\t", "\n", "", "\t\t", "\n", "", "\t", "\n", "\t\t", "\n", "", "", "\t\t\t", "\n", "", "\t\t\t", "\n", "", "\n", "\n\t\t", "\n", "\n" }; int i = -1; StringBuffer report = new StringBuffer(); Iterator<EObject> it = resource.getContents().get(0).eAllContents(); while (it.hasNext()) { EObject eObject = it.next(); if (eObject instanceof org.eclipse.ocl.ecore.StringLiteralExp) { i++; org.eclipse.ocl.ecore.StringLiteralExp literal = (org.eclipse.ocl.ecore.StringLiteralExp)eObject; String symbol = literal.getStringSymbol().replaceAll("\r", ""); if (i >= results.length || !results[i].equals(symbol)) { int line = FileContent.lineNumber(source.getBuffer(), literal.getStartPosition()); report.append("New value at line " + line + " [" + i + "] = '" + symbol + "'\n"); } } } if (report.length() > 0) { System.out.print(report); fail(report.toString()); } }
diff --git a/src/test/java/org/weymouth/demo/model/DataTest.java b/src/test/java/org/weymouth/demo/model/DataTest.java index fcf9320..d2b869f 100755 --- a/src/test/java/org/weymouth/demo/model/DataTest.java +++ b/src/test/java/org/weymouth/demo/model/DataTest.java @@ -1,18 +1,18 @@ package org.weymouth.demo.model; import junit.framework.Assert; import org.junit.Test; public class DataTest { @Test public void test(){ String probe = "probe"; Data d = new Data(probe); String data = d.getData(); - data = null; + // data = null; // this will cause the test to fail; without being a compile error Assert.assertNotNull(data); Assert.assertEquals(probe, data); } }
true
true
public void test(){ String probe = "probe"; Data d = new Data(probe); String data = d.getData(); data = null; Assert.assertNotNull(data); Assert.assertEquals(probe, data); }
public void test(){ String probe = "probe"; Data d = new Data(probe); String data = d.getData(); // data = null; // this will cause the test to fail; without being a compile error Assert.assertNotNull(data); Assert.assertEquals(probe, data); }
diff --git a/src/main/java/org/pircbotx/PircBotX.java b/src/main/java/org/pircbotx/PircBotX.java index 537ccf0..d1cc303 100644 --- a/src/main/java/org/pircbotx/PircBotX.java +++ b/src/main/java/org/pircbotx/PircBotX.java @@ -1,2342 +1,2342 @@ /** * Copyright (C) 2010 Leon Blakey <lord.quackstar at gmail.com> * * This file is part of PircBotX. * * PircBotX 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. * * PircBotX 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 PircBotX. If not, see <http://www.gnu.org/licenses/>. */ package org.pircbotx; import lombok.Setter; import lombok.Getter; import java.util.concurrent.CountDownLatch; import javax.net.SocketFactory; import org.pircbotx.hooks.events.ActionEvent; import org.pircbotx.hooks.events.ChannelInfoEvent; import org.pircbotx.hooks.events.ConnectEvent; import org.pircbotx.hooks.events.DeVoiceEvent; import org.pircbotx.hooks.events.DeopEvent; import org.pircbotx.hooks.events.FingerEvent; import org.pircbotx.hooks.events.InviteEvent; import org.pircbotx.hooks.events.JoinEvent; import org.pircbotx.hooks.events.KickEvent; import org.pircbotx.hooks.events.MessageEvent; import org.pircbotx.hooks.events.ModeEvent; import org.pircbotx.hooks.events.MotdEvent; import org.pircbotx.hooks.events.NickChangeEvent; import org.pircbotx.hooks.events.NoticeEvent; import org.pircbotx.hooks.events.OpEvent; import org.pircbotx.hooks.events.PartEvent; import org.pircbotx.hooks.events.PingEvent; import org.pircbotx.hooks.events.PrivateMessageEvent; import org.pircbotx.hooks.events.QuitEvent; import org.pircbotx.hooks.events.RemoveChannelBanEvent; import org.pircbotx.hooks.events.RemoveChannelKeyEvent; import org.pircbotx.hooks.events.RemoveChannelLimitEvent; import org.pircbotx.hooks.events.RemoveInviteOnlyEvent; import org.pircbotx.hooks.events.RemoveModeratedEvent; import org.pircbotx.hooks.events.RemoveNoExternalMessagesEvent; import org.pircbotx.hooks.events.RemovePrivateEvent; import org.pircbotx.hooks.events.RemoveSecretEvent; import org.pircbotx.hooks.events.RemoveTopicProtectionEvent; import org.pircbotx.hooks.events.ServerPingEvent; import org.pircbotx.hooks.events.ServerResponseEvent; import org.pircbotx.hooks.events.SetChannelBanEvent; import org.pircbotx.hooks.events.SetChannelKeyEvent; import org.pircbotx.hooks.events.SetChannelLimitEvent; import org.pircbotx.hooks.events.SetInviteOnlyEvent; import org.pircbotx.hooks.events.SetModeratedEvent; import org.pircbotx.hooks.events.SetNoExternalMessagesEvent; import org.pircbotx.hooks.events.SetPrivateEvent; import org.pircbotx.hooks.events.SetSecretEvent; import org.pircbotx.hooks.events.SetTopicProtectionEvent; import org.pircbotx.hooks.events.TimeEvent; import org.pircbotx.hooks.events.TopicEvent; import org.pircbotx.hooks.events.UnknownEvent; import org.pircbotx.hooks.events.UserListEvent; import org.pircbotx.hooks.events.UserModeEvent; import org.pircbotx.hooks.events.VersionEvent; import org.pircbotx.hooks.events.VoiceEvent; import org.pircbotx.hooks.Event; import org.pircbotx.hooks.managers.ListenerManager; import java.util.HashSet; import org.pircbotx.exception.IrcException; import org.pircbotx.exception.NickAlreadyInUseException; import java.util.Set; import java.io.PrintWriter; import java.io.StringWriter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Collections; import java.util.StringTokenizer; import lombok.Synchronized; import org.pircbotx.hooks.CoreHooks; import org.pircbotx.hooks.managers.GenericListenerManager; import org.pircbotx.hooks.Listener; import org.pircbotx.hooks.managers.ThreadedListenerManager; import static org.pircbotx.ReplyConstants.*; /** * PircBotX is a Java framework for writing IRC bots quickly and easily. * <p> * It provides an event-driven architecture to handle common IRC * events, flood protection, DCC support, ident support, and more. * The comprehensive logfile format is suitable for use with pisg to generate * channel statistics. * <p> * Methods of the PircBotX class can be called to send events to the IRC server * that it connects to. For example, calling the sendMessage method will * send a message to a channel or user on the IRC server. Multiple servers * can be supported using multiple instances of PircBotX. * <p> * To perform an action when the PircBotX receives a normal message from the IRC * server, you would override the onMessage method defined in the PircBotX * class. All on<i>XYZ</i> methods in the PircBotX class are automatically called * when the event <i>XYZ</i> happens, so you would override these if you wish * to do something when it does happen. * <p> * Some event methods, such as onPing, should only really perform a specific * function (i.e. respond to a PING from the server). For your convenience, such * methods are already correctly implemented in the PircBotX and should not * normally need to be overridden. Please read the full documentation for each * method to see which ones are already implemented by the PircBotX class. * * @author Origionally by: * <a href="http://www.jibble.org/">Paul James Mutton</a> for <a href="http://www.jibble.org/pircbot.php">PircBot</a> * <p>Forked and Maintained by in <a href="http://pircbotx.googlecode.com">PircBotX</a>: * Leon Blakey <lord.quackstar at gmail.com> */ public class PircBotX { /** * The definitive version number of this release of PircBotX. * (Note: Change this before automatically building releases) */ public static final String VERSION = "1.2 Beta 2"; protected Socket _socket; // Connection stuff. protected InputThread _inputThread = null; protected OutputThread _outputThread = null; private String _charset = null; private InetAddress _inetAddress = null; // Details about the last server that we connected to. private String _server = null; private int _port = -1; private String _password = null; private long _messageDelay = 1000; /* * A Many to Many map that links Users to Channels and channels to users. Modified * to remove each channel's and user's internal refrences to each other. */ protected ManyToManyMap<Channel, User> _userChanInfo = new ManyToManyMap<Channel, User>() { @Override public Set<Channel> deleteB(User b) { //Remove the Channels internal reference to the User synchronized (lockObject) { for (Channel curChan : BMap.get(b)) curChan.removeUser(b); } return super.deleteB(b); } @Override public boolean dissociate(Channel a, User b, boolean remove) { //Remove the Channels internal reference to the User a.removeUser(b); boolean result = super.dissociate(a, b, remove); //If user is not associated with anything, remove //Don't put in deleteB because user might be PMing us but not in our channels if(getAValues(b).isEmpty()) deleteB(b); return result; } }; // DccManager to process and handle all DCC events. private DccManager _dccManager = new DccManager(this); private int[] _dccPorts = null; private InetAddress _dccInetAddress = null; // Default settings for the PircBotX. private boolean _autoNickChange = false; private boolean _verbose = false; private String _name = "PircBotX"; private String _nick = _name; private String _login = "PircBotX"; private String _version = "PircBotX " + VERSION + ", a fork of PircBot, the Java IRC bot - pircbotx.googlecode.com"; private String _finger = "You ought to be arrested for fingering a bot!"; private String _channelPrefixes = "#&+!"; /** * The logging lock object preventing lines from being printed as other * lines are being printed */ private final Object logLock = new Object(); protected ListenerManager<? extends PircBotX> listenerManager = new ThreadedListenerManager(); /** * The number of milliseconds to wait before the socket times out on read * operations. This does not mean the socket is invalid. By default its 5 * minutes */ private int socketTimeout = 1000 * 60 * 5; private final ServerInfo serverInfo = new ServerInfo(this); protected final ListBuilder<ChannelListEntry> channelListBuilder = new ListBuilder(); private SocketFactory _socketFactory = null; /** * Constructs a PircBotX with the default settings and adding {@link CoreHooks} * to the default ListenerManager, {@link ThreadedListenerManager}. This also * adds a shutdown hook to the current runtime while will properly shutdown * the bot by calling {@link #disconnect() } and {@link #dispose() } */ public PircBotX() { listenerManager.addListener(new CoreHooks()); final PircBotX thisBot = this; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (thisBot.isConnected()) { thisBot.disconnect(); thisBot.dispose(); } } }); } /** * Attempt to connect to the specified IRC server. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname) throws IOException, IrcException, NickAlreadyInUseException { this.connect(hostname, 6667, null, null); } /** * Attempt to connect to the specified IRC server and port number. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname, int port) throws IOException, IrcException, NickAlreadyInUseException { this.connect(hostname, port, null, null); } /** * Attempt to connect to the specified IRC server using the given port * and password. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * @param password The password to use to join the server. * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname, int port, String password) throws IOException, IrcException, NickAlreadyInUseException { this.connect(hostname, port, password, null); } /** * Attempt to connect to the specified IRC server using the given port number * and socketFactory. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * @param socketFactory The factory to use for creating sockets, including secure sockets * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname, int port, SocketFactory socketFactory) throws IOException, IrcException, NickAlreadyInUseException { this.connect(hostname, port, null, socketFactory); } /** * Attempt to connect to the specified IRC server using the supplied * port number, password, and socketFactory. * The onConnect method is called upon success. * * @param hostname The hostname of the server to connect to. * @param port The port number to connect to on the server. * @param password The password to use to join the server. * @param socketFactory The factory to use for creating sockets, including secure sockets * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void connect(String hostname, int port, String password, SocketFactory socketFactory) throws IOException, IrcException, NickAlreadyInUseException { _server = hostname; _port = port; _password = password; if (isConnected()) throw new IrcException("The PircBotXis already connected to an IRC server. Disconnect first."); // Don't clear the outqueue - there might be something important in it! // Clear everything we may have know about channels. _userChanInfo.clear(); // Connect to the server. if (socketFactory == null) _socket = new Socket(hostname, port); else _socket = socketFactory.createSocket(hostname, port); log("*** Connected to server."); _inetAddress = _socket.getLocalAddress(); InputStreamReader inputStreamReader = null; OutputStreamWriter outputStreamWriter = null; if (getEncoding() != null) { // Assume the specified encoding is valid for this JVM. inputStreamReader = new InputStreamReader(_socket.getInputStream(), getEncoding()); outputStreamWriter = new OutputStreamWriter(_socket.getOutputStream(), getEncoding()); } else { // Otherwise, just use the JVM's default encoding. inputStreamReader = new InputStreamReader(_socket.getInputStream()); outputStreamWriter = new OutputStreamWriter(_socket.getOutputStream()); } BufferedReader breader = new BufferedReader(inputStreamReader); BufferedWriter bwriter = new BufferedWriter(outputStreamWriter); //Construct the output and input threads _inputThread = new InputThread(this, _socket, breader); if (_outputThread == null) _outputThread = new OutputThread(this, bwriter); _outputThread.start(); // Attempt to join the server. if (Utils.isBlank(password)) _outputThread.sendRawLineNow("PASS " + password); String nick = getName(); _outputThread.sendRawLineNow("NICK " + nick); _outputThread.sendRawLineNow("USER " + getLogin() + " 8 * :" + getVersion()); // Read stuff back from the server to see if we connected. String line = null; int tries = 1; while ((line = breader.readLine()) != null) { handleLine(line); int firstSpace = line.indexOf(" "); int secondSpace = line.indexOf(" ", firstSpace + 1); if (secondSpace >= 0) { String code = line.substring(firstSpace + 1, secondSpace); if (code.equals("004")) //EXAMPLE: PircBotX gibson.freenode.net a-ircd-version1.5 allUserModes allChannelModes // We're connected to the server. break; else if (code.equals("433")) //EXAMPLE: AnAlreadyUsedName :Nickname already in use //Nickname in use, rename if (_autoNickChange) { tries++; nick = getName() + tries; _outputThread.sendRawLineNow("NICK " + nick); } else { _socket.close(); _inputThread = null; throw new NickAlreadyInUseException(line); } else if (code.equals("439")) { //EXAMPLE: PircBotX: Target change too fast. Please wait 104 seconds // No action required. } else if (code.startsWith("5") || code.startsWith("4")) { _socket.close(); _inputThread = null; throw new IrcException("Could not log into the IRC server: " + line); } } setNick(nick); } log("*** Logged onto server."); // This makes the socket timeout on read operations after 5 minutes. _socket.setSoTimeout(getSocketTimeout()); //Start input to start accepting lines _inputThread.start(); getListenerManager().dispatchEvent(new ConnectEvent(this)); } /** * Reconnects to the IRC server that we were previously connected to. * If necessary, the appropriate port number and password will be used. * This method will throw an IrcException if we have never connected * to an IRC server previously. * * @since PircBotX 0.9.9 * * @throws IOException if it was not possible to connect to the server. * @throws IrcException if the server would not let us join it. * @throws NickAlreadyInUseException if our nick is already in use on the server. */ public synchronized void reconnect() throws IOException, IrcException, NickAlreadyInUseException { if (getServer() == null) throw new IrcException("Cannot reconnect to an IRC server because we were never connected to one previously!"); connect(getServer(), getPort(), getPassword(), getSocketFactory()); } /** * This method disconnects from the server cleanly by calling the * quitServer() method. Providing the PircBotX was connected to an * IRC server, the onDisconnect() will be called as soon as the * disconnection is made by the server. * * @see #quitServer() quitServer * @see #quitServer(String) quitServer */ public synchronized void disconnect() { quitServer(); } /** * When you connect to a server and your nick is already in use and * this is set to true, a new nick will be automatically chosen. * This is done by adding numbers to the end of the nick until an * available nick is found. * * @param autoNickChange Set to true if you want automatic nick changes * during connection. */ public void setAutoNickChange(boolean autoNickChange) { _autoNickChange = autoNickChange; } /** * Starts an ident server (Identification Protocol Server, RFC 1413). * <p> * Most IRC servers attempt to contact the ident server on connecting * hosts in order to determine the user's identity. A few IRC servers * will not allow you to connect unless this information is provided. * <p> * So when a PircBotX is run on a machine that does not run an ident server, * it may be necessary to call this method to start one up. * <p> * Calling this method starts up an ident server which will respond with * the login provided by calling getLogin() and then shut down immediately. * It will also be shut down if it has not been contacted within 60 seconds * of creation. * <p> * If you require an ident response, then the correct procedure is to start * the ident server and then connect to the IRC server. The IRC server may * then contact the ident server to get the information it needs. * <p> * The ident server will fail to start if there is already an ident server * running on port 113, or if you are running as an unprivileged user who * is unable to create a server socket on that port number. * <p> * If it is essential for you to use an ident server when connecting to an * IRC server, then make sure that port 113 on your machine is visible to * the IRC server so that it may contact the ident server. * * @since PircBotX 0.9c */ public IdentServer startIdentServer() { return new IdentServer(this, getLogin()); } /** * Joins a channel. * * @param channel The name of the channel to join (eg "#cs"). */ public void joinChannel(String channel) { sendRawLineViaQueue("JOIN " + channel); } /** * Joins a channel with a key. * * @param channel The name of the channel to join (eg "#cs"). * @param key The key that will be used to join the channel. */ public void joinChannel(String channel, String key) { joinChannel(channel + " " + key); } /** * Parts a channel. * * @param channel The name of the channel to leave. */ public void partChannel(String channel) { sendRawLine("PART " + channel); } /** * Parts a channel, giving a reason. * * @param channel The name of the channel to leave. * @param reason The reason for parting the channel. */ public void partChannel(String channel, String reason) { sendRawLine("PART " + channel + " :" + reason); } /** * Quits from the IRC server. * Providing we are actually connected to an IRC server, the * onDisconnect() method will be called as soon as the IRC server * disconnects us. */ public void quitServer() { quitServer(""); } /** * Quits from the IRC server with a reason. * Providing we are actually connected to an IRC server, the * onDisconnect() method will be called as soon as the IRC server * disconnects us. * * @param reason The reason for quitting the server. */ public void quitServer(String reason) { sendRawLine("QUIT :" + reason); } /** * Sends a raw line to the IRC server as soon as possible, bypassing the * outgoing message queue. * * @param line The raw line to send to the IRC server. */ public void sendRawLine(String line) { if (isConnected()) _outputThread.sendRawLineNow(line); } /** * Sends a raw line through the outgoing message queue. * * @param line The raw line to send to the IRC server. */ public void sendRawLineViaQueue(String line) { if (line == null) throw new NullPointerException("Cannot send null messages to server"); if (isConnected()) _outputThread.send(line); } /** * Sends a message to a channel or a private message to a user. These * messages are added to the outgoing message queue and sent at the * earliest possible opportunity. * <p> * Some examples: - * <pre> // Send the message "Hello!" to the channel #cs. * sendMessage("#cs", "Hello!"); * * // Send a private message to Paul that says "Hi". * sendMessage("Paul", "Hi");</pre> * * You may optionally apply colours, boldness, underlining, etc to * the message by using the <code>Colors</code> class. * * @param target The name of the channel or user nick to send to. * @param message The message to send. * * @see Colors */ public void sendMessage(String target, String message) { _outputThread.send("PRIVMSG " + target + " :" + message); } public void sendMessage(Event event, String message) { User target = Utils.getSource(event); if (target != null && message != null) sendMessage(target, message); } public void sendMessage(User target, String message) { if (target != null && message != null) sendMessage(target.getNick(), message); } public void sendMessage(Channel target, String message) { if (target != null && message != null) sendMessage(target.getName(), message); } /** * Send a message to the given user in the given channel in this format: * <code>user: message</code>. Very useful for responding directly to a command * @param chan The channel to send the message to * @param user * @param message */ public void sendMessage(Channel chan, User user, String message) { if (chan != null && user != null && message != null) sendMessage(chan.getName(), user.getNick() + ": " + message); } /** * Sends an action to the channel or to a user. * * @param target The name of the channel or user nick to send to. * @param action The action to send. * * @see Colors */ public void sendAction(String target, String action) { sendCTCPCommand(target, "ACTION " + action); } public void sendAction(Event event, String message) { User target = Utils.getSource(event); if (target != null && message != null) sendAction(target, message); } public void sendAction(User target, String message) { if (target != null && message != null) sendAction(target.getNick(), message); } public void sendAction(Channel target, String message) { if (target != null && message != null) sendAction(target.getName(), message); } /** * Sends a notice to the channel or to a user. * * @param target The name of the channel or user nick to send to. * @param notice The notice to send. */ public void sendNotice(String target, String notice) { _outputThread.send("NOTICE " + target + " :" + notice); } public void sendNotice(Event event, String notice) { User target = Utils.getSource(event); if (target != null && notice != null) sendNotice(target, notice); } public void sendNotice(User target, String notice) { if (target != null && notice != null) sendNotice(target.getNick(), notice); } public void sendNotice(Channel target, String notice) { if (target != null && notice != null) sendNotice(target.getName(), notice); } /** * Sends a CTCP command to a channel or user. (Client to client protocol). * Examples of such commands are "PING <number>", "FINGER", "VERSION", etc. * For example, if you wish to request the version of a user called "Dave", * then you would call <code>sendCTCPCommand("Dave", "VERSION");</code>. * The type of response to such commands is largely dependant on the target * client software. * * @since PircBotX 0.9.5 * * @param target The name of the channel or user to send the CTCP message to. * @param command The CTCP command to send. */ public void sendCTCPCommand(String target, String command) { _outputThread.send("PRIVMSG " + target + " :\u0001" + command + "\u0001"); } public void sendCTCPCommand(Event event, String command) { User target = Utils.getSource(event); if (target != null && command != null) sendCTCPCommand(target, command); } public void sendCTCPCommand(User target, String command) { if (target != null && command != null) sendCTCPCommand(target.getNick(), command); } public void sendCTCPResponse(String target, String message) { _outputThread.send("NOTICE " + target + " :\u0001" + message + "\u0001"); } public void sendCTCPResponse(Event event, String message) { User target = Utils.getSource(event); if (target != null && message != null) sendCTCPResponse(target, message); } public void sendCTCPResponse(User target, String message) { if (target != null && message != null) sendCTCPResponse(target.getNick(), message); } /** * Attempt to change the current nick (nickname) of the bot when it * is connected to an IRC server. * After confirmation of a successful nick change, the getNick method * will return the new nick. * * @param newNick The new nick to use. */ public void changeNick(String newNick) { sendRawLine("NICK " + newNick); } /** * Identify the bot with NickServ, supplying the appropriate password. * Some IRC Networks (such as freenode) require users to <i>register</i> and * <i>identify</i> with NickServ before they are able to send private messages * to other users, thus reducing the amount of spam. If you are using * an IRC network where this kind of policy is enforced, you will need * to make your bot <i>identify</i> itself to NickServ before you can send * private messages. Assuming you have already registered your bot's * nick with NickServ, this method can be used to <i>identify</i> with * the supplied password. It usually makes sense to identify with NickServ * immediately after connecting to a server. * <p> * This method issues a raw NICKSERV command to the server, and is therefore * safer than the alternative approach of sending a private message to * NickServ. The latter approach is considered dangerous, as it may cause * you to inadvertently transmit your password to an untrusted party if you * connect to a network which does not run a NickServ service and where the * untrusted party has assumed the nick "NickServ". However, if your IRC * network is only compatible with the private message approach, you may * typically identify like so: * <pre>sendMessage("NickServ", "identify PASSWORD");</pre> * * @param password The password which will be used to identify with NickServ. */ public void identify(String password) { sendRawLine("NICKSERV IDENTIFY " + password); } /** * Set the mode of a channel. * This method attempts to set the mode of a channel. This * may require the bot to have operator status on the channel. * For example, if the bot has operator status, we can grant * operator status to "Dave" on the #cs channel * by calling setMode("#cs", "+o Dave"); * An alternative way of doing this would be to use the op method. * * @param chan The channel on which to perform the mode change. * @param mode The new mode to apply to the channel. This may include * zero or more arguments if necessary. * * @see #op(org.pircbotx.Channel, org.pircbotx.User) */ public void setMode(Channel chan, String mode) { sendRawLine("MODE " + chan.getName() + " " + mode); } /** * Set a mode for a user. See {@link #setMode(org.pircbotx.Channel, java.lang.String) } * @param chan The channel on which to perform the mode change. * @param mode The new mode to apply to the channel. <b>This should not * include arguments!</b> * @param user The user to perform the mode change on * @see #setMode(org.pircbotx.Channel, java.lang.String) */ public void setMode(Channel chan, String mode, User user) { setMode(chan, mode + user.getNick()); } /** * Sends an invitation to join a channel. Some channels can be marked * as "invite-only", so it may be useful to allow a bot to invite people * into it. * * @param nick The nick of the user to invite * @param channel The channel you are inviting the user to join. * */ public void sendInvite(String nick, String channel) { sendRawLine("INVITE " + nick + " :" + channel); } public void sendInvite(Event event, String channel) { User target = Utils.getSource(event); if (target != null && channel != null) sendInvite(target, channel); } public void sendInvite(User target, String channel) { if (target != null && channel != null) sendInvite(target.getNick(), channel); } public void sendInvite(Event event, Channel channel) { User target = Utils.getSource(event); if (target != null && channel != null) sendInvite(target, channel); } public void sendInvite(User target, Channel channel) { if (target != null && channel != null) sendInvite(target.getNick(), channel); } public void sendInvite(Channel target, Channel channel) { if (target != null && channel != null) sendInvite(target.getName(), channel); } public void sendInvite(String nick, Channel channel) { if (nick != null && channel != null) sendInvite(nick, channel.getName()); } /** * Bans a user from a channel. An example of a valid hostmask is * "*!*compu@*.18hp.net". This may be used in conjunction with the * kick method to permanently remove a user from a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param channel The channel to ban the user from. * @param hostmask A hostmask representing the user we're banning. */ public void ban(String channel, String hostmask) { sendRawLine("MODE " + channel + " +b " + hostmask); } /** * Unbans a user from a channel. An example of a valid hostmask is * "*!*compu@*.18hp.net". * Successful use of this method may require the bot to have operator * status itself. * * @param channel The channel to unban the user from. * @param hostmask A hostmask representing the user we're unbanning. */ public void unBan(String channel, String hostmask) { sendRawLine("MODE " + channel + " -b " + hostmask); } /** * Grants operator privilidges to a user on a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param chan The channel we're opping the user on. * @param user The user we are opping. */ public void op(Channel chan, User user) { setMode(chan, "+o " + user.getNick()); } /** * Removes operator privileges from a user on a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param chan The channel we're deopping the user on. * @param user The user we are deopping. */ public void deOp(Channel chan, User user) { setMode(chan, "-o " + user.getNick()); } /** * Grants voice privileges to a user on a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param chan The channel we're voicing the user on. * @param user The user we are voicing. */ public void voice(Channel chan, User user) { setMode(chan, "+v " + user.getNick()); } /** * Removes voice privileges from a user on a channel. * Successful use of this method may require the bot to have operator * status itself. * * @param chan The channel we're devoicing the user on. * @param user The user we are devoicing. */ public void deVoice(Channel chan, User user) { setMode(chan, "-v " + user.getNick()); } /** * Set the topic for a channel. * This method attempts to set the topic of a channel. This * may require the bot to have operator status if the topic * is protected. * * @param chan The channel on which to perform the mode change. * @param topic The new topic for the channel. * */ public void setTopic(Channel chan, String topic) { sendRawLine("TOPIC " + chan.getName() + " :" + topic); } /** * Kicks a user from a channel. * This method attempts to kick a user from a channel and * may require the bot to have operator status in the channel. * * @param chan The channel to kick the user from. * @param user The user to kick. */ public void kick(Channel chan, User user) { kick(chan, user, ""); } /** * Kicks a user from a channel, giving a reason. * This method attempts to kick a user from a channel and * may require the bot to have operator status in the channel. * * @param chan The channel to kick the user from. * @param user The user to kick. * @param reason A description of the reason for kicking a user. */ public void kick(Channel chan, User user, String reason) { sendRawLine("KICK " + chan.getName() + " " + user.getNick() + " :" + reason); } /** * Issues a request for a list of all channels on the IRC server. * When the PircBotX receives information for each channel, it will * call the onChannelInfo method, which you will need to override * if you want it to do anything useful. * <p> * <b>NOTE:</b> This will do nothing if a channel list is already in effect * * @see ChannelInfoEvent */ public void listChannels() { listChannels(null); } /** * Issues a request for a list of all channels on the IRC server. * When the PircBotX receives information for each channel, it will * call the onChannelInfo method, which you will need to override * if you want it to do anything useful. * <p> * Some IRC servers support certain parameters for LIST requests. * One example is a parameter of ">10" to list only those channels * that have more than 10 users in them. Whether these parameters * are supported or not will depend on the IRC server software. * <p> * <b>NOTE:</b> This will do nothing if a channel list is already in effect * @param parameters The parameters to supply when requesting the * list. * * @see ChannelInfoEvent */ public void listChannels(String parameters) { if (!channelListBuilder.isRunning()) if (parameters == null) sendRawLine("LIST"); else sendRawLine("LIST " + parameters); } /** * Sends a file to another user. Resuming is supported. * The other user must be able to connect directly to your bot to be * able to receive the file. * <p> * You may throttle the speed of this file transfer by calling the * setPacketDelay method on the DccFileTransfer that is returned. * <p> * This method may not be overridden. * * @since 0.9c * * @param file The file to send. * @param reciever The user to whom the file is to be sent. * @param timeout The number of milliseconds to wait for the recipient to * acccept the file (we recommend about 120000). * * @return The DccFileTransfer that can be used to monitor this transfer. * * @see DccFileTransfer * */ public DccFileTransfer dccSendFile(File file, User reciever, int timeout) { DccFileTransfer transfer = new DccFileTransfer(this, _dccManager, file, reciever, timeout); transfer.doSend(true); return transfer; } /** * Attempts to establish a DCC CHAT session with a client. This method * issues the connection request to the client and then waits for the * client to respond. If the connection is successfully made, then a * DccChat object is returned by this method. If the connection is not * made within the time limit specified by the timeout value, then null * is returned. * <p> * It is <b>strongly recommended</b> that you call this method within a new * Thread, as it may take a long time to return. * <p> * This method may not be overridden. * * @param sender The user object representing the user we are trying to * establish a chat with. * @param timeout The number of milliseconds to wait for the recipient to * accept the chat connection (we recommend about 120000). * * @return a DccChat object that can be used to send and recieve lines of * text. Returns <b>null</b> if the connection could not be made. * * @see DccChat * @since PircBotX 0.9.8 */ public DccChat dccSendChatRequest(User sender, int timeout) { DccChat chat = null; try { ServerSocket ss = null; int[] ports = getDccPorts(); if (ports == null) // Use any free port. ss = new ServerSocket(0); else { for (int i = 0; i < ports.length; i++) try { ss = new ServerSocket(ports[i]); // Found a port number we could use. break; } catch (Exception e) { // Do nothing; go round and try another port. } if (ss == null) // No ports could be used. throw new IOException("All ports returned by getDccPorts() are in use."); } ss.setSoTimeout(timeout); int port = ss.getLocalPort(); InetAddress inetAddress = getDccInetAddress(); if (inetAddress == null) inetAddress = getInetAddress(); byte[] ip = inetAddress.getAddress(); long ipNum = ipToLong(ip); sendCTCPCommand(sender, "DCC CHAT chat " + ipNum + " " + port); // The client may now connect to us to chat. Socket socket = ss.accept(); // Close the server socket now that we've finished with it. ss.close(); chat = new DccChat(this, sender, socket); } catch (Exception e) { // Do nothing. } return chat; } /** * Adds a line to the log. This log is currently output to the standard * output and is in the correct format for use by tools such as pisg, the * Perl IRC Statistics Generator. You may override this method if you wish * to do something else with log entries. * Each line in the log begins with a number which * represents the logging time (as the number of milliseconds since the * epoch). This timestamp and the following log entry are separated by * a single space character, " ". Outgoing messages are distinguishable * by a log entry that has ">>>" immediately following the space character * after the timestamp. DCC events use "+++" and warnings about unhandled * Exceptions and Errors use "###". * <p> * This implementation of the method will only cause log entries to be * output if the PircBotX has had its verbose mode turned on by calling * setVerbose(true); * * @param line The line to add to the log. */ @Synchronized(value="logLock") public void log(String line) { if (_verbose) System.out.println(System.currentTimeMillis() + " " + line); } @Synchronized(value="logLock") public void logException(Throwable t) { if (!_verbose) return; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); StringTokenizer tokenizer = new StringTokenizer(sw.toString(), "\r\n"); log("### Your implementation of PircBotX is faulty and you have"); log("### allowed an uncaught Exception or Error to propagate in your"); log("### code. It may be possible for PircBotX to continue operating"); log("### normally. Here is the stack trace that was produced: -"); log("### "); while (tokenizer.hasMoreTokens()) log("### " + tokenizer.nextToken()); } /** * This method handles events when any line of text arrives from the server, * then calling the appropriate method in the PircBotX. This method is * protected and only called by the InputThread for this instance. * <p> * This method may not be overridden! * * @param line The raw line of text from the server. */ protected void handleLine(String line) { log("<<<" + line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. getListenerManager().dispatchEvent(new ServerPingEvent(this, line.substring(5))); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else { // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; target = token; } } else { // We don't know what this line means. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); User source = getUser(sourceNick); //If the channel matches a prefix, then its a channel - Channel channel = (_channelPrefixes.indexOf(target.charAt(0)) >= 0) ? null : getChannel(target); + Channel channel = (_channelPrefixes.indexOf(target.charAt(0)) >= 0) ? getChannel(target) : null ; // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request getListenerManager().dispatchEvent(new VersionEvent(this, source, channel)); else if (request.startsWith("ACTION ")) // ACTION request getListenerManager().dispatchEvent(new ActionEvent(this, source, channel, request.substring(7))); else if (request.startsWith("PING ")) // PING request getListenerManager().dispatchEvent(new PingEvent(this, source, channel, request.substring(5))); else if (request.equals("TIME")) // TIME request getListenerManager().dispatchEvent(new TimeEvent(this, source, channel)); else if (request.equals("FINGER")) // FINGER request getListenerManager().dispatchEvent(new FingerEvent(this, source, channel)); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(source, request); if (!success) // The DccManager didn't know what to do with the line. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else // An unknown CTCP message - ignore it. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. getListenerManager().dispatchEvent(new MessageEvent(this, channel, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("PRIVMSG")) // This is a private message to us. getListenerManager().dispatchEvent(new PrivateMessageEvent(this, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("JOIN")) { // Someone is joining a channel. if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup (don't use channel var since channel doesn't exist yet) sendRawLine("WHO " + target); sendRawLine("MODE " + target); } User usr = getUser(sourceNick); //Only setup if nessesary if (usr.getHostmask() == null) { usr.setLogin(sourceLogin); usr.setHostmask(sourceHostname); } //user.addUser(usr); getListenerManager().dispatchEvent(new JoinEvent(this, channel, source)); } else if (command.equals("PART")) // Someone is parting from a channel. if (sourceNick.equals(getNick())) //We parted the channel _userChanInfo.deleteA(channel); else { //Just remove the user from memory _userChanInfo.dissociate(channel, getUser(sourceNick)); getListenerManager().dispatchEvent(new PartEvent(this, channel, source)); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; getUser(sourceNick).setNick(newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); getListenerManager().dispatchEvent(new NickChangeEvent(this, sourceNick, newNick, source)); } else if (command.equals("NOTICE")) // Someone is sending a notice. getListenerManager().dispatchEvent(new NoticeEvent(this, source, channel, line.substring(line.indexOf(" :") + 2))); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) //We just quit the server _userChanInfo.clear(); else //Someone else _userChanInfo.deleteB(getUser(sourceNick)); getListenerManager().dispatchEvent(new QuitEvent(this, source, line.substring(line.indexOf(" :") + 2))); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); User user = getUser(sourceNick); if (recipient.equals(getNick())) //We were just kicked _userChanInfo.deleteA(channel); else //Someone else _userChanInfo.dissociate(channel, user, true); getListenerManager().dispatchEvent(new KickEvent(this, channel, source, getUser(recipient), line.substring(line.indexOf(" :") + 2))); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) { // Someone is changing the topic. String topic = line.substring(line.indexOf(" :") + 2); long currentTime = System.currentTimeMillis(); channel.setTopic(topic); channel.setTopicSetter(sourceNick); channel.setTopicTimestamp(currentTime); getListenerManager().dispatchEvent(new TopicEvent(this, channel, topic, source, currentTime, true)); } else if (command.equals("INVITE")) { // Somebody is inviting somebody else into a channel. //Use line method instead of channel since channel is wrong getListenerManager().dispatchEvent(new InviteEvent(this, source, line.substring(line.indexOf(" :") + 2))); } else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } /** * This method is called by the PircBotX when a numeric response * is received from the IRC server. We use this method to * allow PircBotX to process various responses from the server * before then passing them on to the onServerResponse method. * <p> * Note that this method is private and should not appear in any * of the javadoc generated documenation. * * @param code The three-digit numerical code for the response. * @param response The full response from the IRC server. */ protected void processServerResponse(int code, String response) { //NOTE: Update tests if adding support for a new code String[] parsed = response.split(" "); if (code == RPL_LISTSTART) //EXAMPLE: 321 Channel :Users Name (actual text) //A channel list is about to be sent channelListBuilder.setRunning(true); else if (code == RPL_LIST) { //This is part of a full channel listing as part of /LIST //EXAMPLE: 322 lordquackstar #xomb 12 :xomb exokernel project @ www.xomb.org int firstSpace = response.indexOf(' '); int secondSpace = response.indexOf(' ', firstSpace + 1); int thirdSpace = response.indexOf(' ', secondSpace + 1); int colon = response.indexOf(':'); String channel = response.substring(firstSpace + 1, secondSpace); int userCount = 0; try { userCount = Integer.parseInt(response.substring(secondSpace + 1, thirdSpace)); } catch (NumberFormatException e) { // Stick with the value of zero. } String topic = response.substring(colon + 1); channelListBuilder.add(new ChannelListEntry(channel, userCount, topic)); } else if (code == RPL_LISTEND) { //EXAMPLE: 323 :End of /LIST //End of channel list, dispatch event getListenerManager().dispatchEvent(new ChannelInfoEvent(this, channelListBuilder.finish())); channelListBuilder.setRunning(false); } else if (code == RPL_TOPIC) { //EXAMPLE: 332 PircBotX #aChannel :I'm some random topic //This is topic about a channel we've just joined. From /JOIN or /TOPIC parsed = response.split(" ", 3); String channel = parsed[1]; String topic = parsed[2].substring(1); getChannel(channel).setTopic(topic); } else if (code == RPL_TOPICINFO) { //EXAMPLE: 333 PircBotX #aChannel ISetTopic 1564842512 //This is information on the topic of the channel we've just joined. From /JOIN or /TOPIC String channel = parsed[1]; User setBy = getUser(parsed[2]); long date = 0; try { date = Long.parseLong(parsed[3]) * 1000; } catch (NumberFormatException e) { // Stick with the default value of zero. } Channel chan = getChannel(channel); chan.setTopicTimestamp(date); chan.setTopicSetter(setBy.getNick()); getListenerManager().dispatchEvent(new TopicEvent(this, chan, chan.getTopic(), setBy, date, false)); } else if (code == RPL_NAMREPLY) { //EXAMPLE: 353 PircBotX = #aChannel :PircBotX @SuperOp someoneElse //This is a list of nicks in a channel that we've just joined. SPANS MULTIPLE LINES. From /NAMES and /JOIN parsed = response.split(" ", 4); Channel chan = getChannel(parsed[2]); for (String nick : parsed[3].substring(1).split(" ")) { User curUser = getUser(nick); if(nick.contains("@")) chan.addOp(curUser); if(nick.contains("+")) chan.addVoice(curUser); } } else if (code == RPL_ENDOFNAMES) { //EXAMPLE: 366 PircBotX #aChannel :End of /NAMES list // This is the end of a NAMES list, so we know that we've got // the full list of users in the channel that we just joined. From /NAMES and /JOIN String channelName = response.split(" ", 3)[1]; Channel channel = getChannel(channelName); getListenerManager().dispatchEvent(new UserListEvent(this, channel, getUsers(channel))); } else if (code == RPL_WHOREPLY) { //EXAMPLE: PircBotX #aChannel ~someName 74.56.56.56.my.Hostmask wolfe.freenode.net someNick H :0 Full Name //Part of a WHO reply on information on individual users parsed = response.split(" ", 9); Channel chan = getChannel(parsed[1]); User curUser = getUser(parsed[5]); //Only setup when needed if (Utils.isBlank(curUser.getLogin())) { curUser.setLogin(parsed[2]); curUser.setIdentified(parsed[2].startsWith("~")); curUser.setHostmask(parsed[3]); curUser.setServer(parsed[4]); curUser.setNick(parsed[5]); curUser.parseStatus(chan.getName(), parsed[6]); curUser.setHops(Integer.parseInt(parsed[7].substring(1))); curUser.setRealName(parsed[8]); } } else if (code == RPL_ENDOFWHO) { //EXAMPLE: PircBotX #aChannel :End of /WHO list //End of the WHO reply Channel channel = getChannel(response.split(" ")[1]); getListenerManager().dispatchEvent(new UserListEvent(this, channel, getUsers(channel))); } else if (code == RPL_CHANNELMODEIS) //EXAMPLE: PircBotX #aChannel +cnt //Full channel mode (In response to MODE <channel>) getChannel(parsed[1]).parseMode(parsed[2]); else if (code == 329) { //EXAMPLE: 329 lordquackstar #botters 1199140245 //Tells when channel was created. Note mIRC says lordquackstar shouldn't be there while Freenode //displays it. From /JOIN(?) int createDate = -1; String channel = ""; //Freenode version try { createDate = Integer.parseInt(parsed[2]); channel = parsed[1]; } catch (NumberFormatException e) { //mIRC version createDate = Integer.parseInt(parsed[1]); channel = parsed[0]; } //Set in channel getChannel(channel).setCreateTimestamp(createDate); } else if (code == RPL_MOTDSTART) //Example: 375 PircBotX :- wolfe.freenode.net Message of the Day - //Motd is starting, reset the StringBuilder getServerInfo().setMotd(""); else if (code == RPL_MOTD) //Example: PircBotX :- Welcome to wolfe.freenode.net in Manchester, England, Uk! Thanks to //This is part of the MOTD, add a new line getServerInfo().setMotd(getServerInfo().getMotd() + response.split(" ", 3) + "\n"); else if (code == RPL_ENDOFMOTD) //Example: PircBotX :End of /MOTD command. //End of MOTD, dispatch event getListenerManager().dispatchEvent(new MotdEvent(this, (getServerInfo().getMotd()))); //WARNING: Parsed array might be modified, recreate if you're going to use down here getListenerManager().dispatchEvent(new ServerResponseEvent(this, code, response)); } /** * Called when the mode of a channel is set. We process this in * order to call the appropriate onOp, onDeop, etc method before * finally calling the override-able onMode method. * <p> * Note that this method is private and is not intended to appear * in the javadoc generated documentation. * * @param target The channel or nick that the mode operation applies to. * @param sourceNick The nick of the user that set the mode. * @param sourceLogin The login of the user that set the mode. * @param sourceHostname The hostname of the user that set the mode. * @param mode The mode that has been set. */ protected void processMode(String target, String sourceNick, String sourceLogin, String sourceHostname, String mode) { User source = getUser(sourceNick); if (_channelPrefixes.indexOf(target.charAt(0)) >= 0) { // The mode of a channel is being changed. Channel channel = getChannel(target); StringTokenizer tok = new StringTokenizer(mode); String[] params = new String[tok.countTokens()]; int t = 0; while (tok.hasMoreTokens()) { params[t] = tok.nextToken(); t++; } char pn = ' '; int p = 1; // All of this is very large and ugly, but it's the only way of providing // what the users want :-/ for (int i = 0; i < params[0].length(); i++) { char atPos = params[0].charAt(i); if (atPos == '+' || atPos == '-') pn = atPos; else if (atPos == 'o') { User reciepeint = getUser(params[p]); if (pn == '+') { channel.addOp(source); getListenerManager().dispatchEvent(new OpEvent(this, channel, source, reciepeint)); } else { channel.removeOp(source); getListenerManager().dispatchEvent(new DeopEvent(this, channel, source, reciepeint)); } p++; } else if (atPos == 'v') { User reciepeint = getUser(params[p]); if (pn == '+') { channel.addVoice(source); getListenerManager().dispatchEvent(new VoiceEvent(this, channel, source, reciepeint)); } else { channel.removeVoice(source); getListenerManager().dispatchEvent(new DeVoiceEvent(this, channel, source, reciepeint)); } p++; } else if (atPos == 'k') { if (pn == '+') getListenerManager().dispatchEvent(new SetChannelKeyEvent(this, channel, source, params[p])); else getListenerManager().dispatchEvent(new RemoveChannelKeyEvent(this, channel, source, params[p])); p++; } else if (atPos == 'l') if (pn == '+') { getListenerManager().dispatchEvent(new SetChannelLimitEvent(this, channel, source, Integer.parseInt(params[p]))); p++; } else getListenerManager().dispatchEvent(new RemoveChannelLimitEvent(this, channel, source)); else if (atPos == 'b') { if (pn == '+') getListenerManager().dispatchEvent(new SetChannelBanEvent(this, channel, source, params[p])); else getListenerManager().dispatchEvent(new RemoveChannelBanEvent(this, channel, source, params[p])); p++; } else if (atPos == 't') if (pn == '+') getListenerManager().dispatchEvent(new SetTopicProtectionEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveTopicProtectionEvent(this, channel, source)); else if (atPos == 'n') if (pn == '+') getListenerManager().dispatchEvent(new SetNoExternalMessagesEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveNoExternalMessagesEvent(this, channel, source)); else if (atPos == 'i') if (pn == '+') getListenerManager().dispatchEvent(new SetInviteOnlyEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveInviteOnlyEvent(this, channel, source)); else if (atPos == 'm') if (pn == '+') getListenerManager().dispatchEvent(new SetModeratedEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveModeratedEvent(this, channel, source)); else if (atPos == 'p') if (pn == '+') getListenerManager().dispatchEvent(new SetPrivateEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemovePrivateEvent(this, channel, source)); else if (atPos == 's') if (pn == '+') getListenerManager().dispatchEvent(new SetSecretEvent(this, channel, source)); else getListenerManager().dispatchEvent(new RemoveSecretEvent(this, channel, source)); } getListenerManager().dispatchEvent(new ModeEvent(this, channel, source, mode)); } else { // The mode of a user is being changed. String nick = target; getListenerManager().dispatchEvent(new UserModeEvent(this, getUser(nick), source, mode)); } } /** * Sets the verbose mode. If verbose mode is set to true, then log entries * will be printed to the standard output. The default value is false and * will result in no output. For general development, we strongly recommend * setting the verbose mode to true. * * @param verbose true if verbose mode is to be used. Default is false. */ public void setVerbose(boolean verbose) { _verbose = verbose; } /** * Sets the name of the bot, which will be used as its nick when it * tries to join an IRC server. This should be set before joining * any servers, otherwise the default nick will be used. You would * typically call this method from the constructor of the class that * extends PircBotX. * <p> * The changeNick method should be used if you wish to change your nick * when you are connected to a server. * * @param name The new name of the Bot. */ public void setName(String name) { _name = name; } /** * Sets the internal nick of the bot. This is only to be called by the * PircBotX class in response to notification of nick changes that apply * to us. * * @param nick The new nick. */ protected void setNick(String nick) { _nick = nick; } /** * Sets the internal login of the Bot. This should be set before joining * any servers. * * @param login The new login of the Bot. */ public void setLogin(String login) { _login = login; } /** * Sets the internal version of the Bot. This should be set before joining * any servers. * * @param version The new version of the Bot. */ public void setVersion(String version) { _version = version; } /** * Sets the interal finger message. This should be set before joining * any servers. * * @param finger The new finger message for the Bot. */ public void setFinger(String finger) { _finger = finger; } /** * Gets the name of the PircBotX. This is the name that will be used as * as a nick when we try to join servers. * * @return The name of the PircBotX. */ public String getName() { return _name; } /** * Returns the current nick of the bot. Note that if you have just changed * your nick, this method will still return the old nick until confirmation * of the nick change is received from the server. * <p> * The nick returned by this method is maintained only by the PircBotX * class and is guaranteed to be correct in the context of the IRC server. * * @since PircBotX 1.0.0 * * @return The current nick of the bot. */ public String getNick() { return _nick; } /** * Gets the internal login of the PircBotX. * * @return The login of the PircBotX. */ public String getLogin() { return _login; } /** * Gets the internal version of the PircBotX. * * @return The version of the PircBotX. */ public String getVersion() { return _version; } /** * Gets the internal finger message of the PircBotX. * * @return The finger message of the PircBotX. */ public String getFinger() { return _finger; } /** * Returns whether or not the PircBotX is currently connected to a server. * The result of this method should only act as a rough guide, * as the result may not be valid by the time you act upon it. * * @return True if and only if the PircBotX is currently connected to a server. */ public boolean isConnected() { return _inputThread != null && _inputThread.isConnected(); } /** * Sets the number of milliseconds to delay between consecutive * messages when there are multiple messages waiting in the * outgoing message queue. This has a default value of 1000ms. * It is a good idea to stick to this default value, as it will * prevent your bot from spamming servers and facing the subsequent * wrath! However, if you do need to change this delay value (<b>not * recommended</b>), then this is the method to use. * * @param delay The number of milliseconds between each outgoing message. * */ public void setMessageDelay(long delay) { if (delay < 0) throw new IllegalArgumentException("Cannot have a negative time."); _messageDelay = delay; } /** * Returns the number of milliseconds that will be used to separate * consecutive messages to the server from the outgoing message queue. * * @return Number of milliseconds. */ public long getMessageDelay() { return _messageDelay; } /** * Gets the maximum length of any line that is sent via the IRC protocol. * The IRC RFC specifies that line lengths, including the trailing \r\n * must not exceed 512 bytes. Hence, there is currently no option to * change this value in PircBotX. All lines greater than this length * will be truncated before being sent to the IRC server. * * @return The maximum line length (currently fixed at 512) */ public int getMaxLineLength() { return InputThread.MAX_LINE_LENGTH; } /** * Gets the number of lines currently waiting in the outgoing message Queue. * If this returns 0, then the Queue is empty and any new message is likely * to be sent to the IRC server immediately. * * @since PircBotX 0.9.9 * * @return The number of lines in the outgoing message Queue. */ public int getOutgoingQueueSize() { return _outputThread.getQueueSize(); } /** * Returns the name of the last IRC server the PircBotX tried to connect to. * This does not imply that the connection attempt to the server was * successful (we suggest you look at the onConnect method). * A value of null is returned if the PircBotX has never tried to connect * to a server. * * @return The name of the last machine we tried to connect to. Returns * null if no connection attempts have ever been made. */ public String getServer() { return _server; } /** * Returns the port number of the last IRC server that the PircBotX tried * to connect to. * This does not imply that the connection attempt to the server was * successful (we suggest you look at the onConnect method). * A value of -1 is returned if the PircBotX has never tried to connect * to a server. * * @since PircBotX 0.9.9 * * @return The port number of the last IRC server we connected to. * Returns -1 if no connection attempts have ever been made. */ public int getPort() { return _port; } /** * Returns the last password that we used when connecting to an IRC server. * This does not imply that the connection attempt to the server was * successful (we suggest you look at the onConnect method). * A value of null is returned if the PircBotX has never tried to connect * to a server using a password. * * @since PircBotX 0.9.9 * * @return The last password that we used when connecting to an IRC server. * Returns null if we have not previously connected using a password. */ public String getPassword() { return _password; } /** * A convenient method that accepts an IP address represented as a * long and returns an integer array of size 4 representing the same * IP address. * * @since PircBotX 0.9.4 * * @param address the long value representing the IP address. * * @return An int[] of size 4. */ public int[] longToIp(long address) { int[] ip = new int[4]; for (int i = 3; i >= 0; i--) { ip[i] = (int) (address % 256); address = address / 256; } return ip; } /** * A convenient method that accepts an IP address represented by a byte[] * of size 4 and returns this as a long representation of the same IP * address. * * @since PircBotX 0.9.4 * * @param address the byte[] of size 4 representing the IP address. * * @return a long representation of the IP address. */ public long ipToLong(byte[] address) { if (address.length != 4) throw new IllegalArgumentException("byte array must be of length 4"); long ipNum = 0; long multiplier = 1; for (int i = 3; i >= 0; i--) { int byteVal = (address[i] + 256) % 256; ipNum += byteVal * multiplier; multiplier *= 256; } return ipNum; } /** * Sets the encoding charset to be used when sending or receiving lines * from the IRC server. If set to null, then the platform's default * charset is used. You should only use this method if you are * trying to send text to an IRC server in a different charset, e.g. * "GB2312" for Chinese encoding. If a PircBotX is currently connected * to a server, then it must reconnect before this change takes effect. * * @since PircBotX 1.0.4 * * @param charset The new encoding charset to be used by PircBotX. * * @throws UnsupportedEncodingException If the named charset is not * supported. */ public void setEncoding(String charset) throws UnsupportedEncodingException { // Just try to see if the charset is supported first... "".getBytes(charset); _charset = charset; } /** * Returns the encoding used to send and receive lines from * the IRC server, or null if not set. Use the setEncoding * method to change the encoding charset. * * @since PircBotX 1.0.4 * * @return The encoding used to send outgoing messages, or * null if not set. */ public String getEncoding() { return _charset; } /** * Returns the InetAddress used by the PircBotX. * This can be used to find the I.P. address from which the PircBotX is * connected to a server. * * @since PircBotX 1.4.4 * * @return The current local InetAddress, or null if never connected. */ public InetAddress getInetAddress() { return _inetAddress; } /** * Sets the InetAddress to be used when sending DCC chat or file transfers. * This can be very useful when you are running a bot on a machine which * is behind a firewall and you need to tell receiving clients to connect * to a NAT/router, which then forwards the connection. * * @since PircBotX 1.4.4 * * @param dccInetAddress The new InetAddress, or null to use the default. */ public void setDccInetAddress(InetAddress dccInetAddress) { _dccInetAddress = dccInetAddress; } /** * Returns the InetAddress used when sending DCC chat or file transfers. * If this is null, the default InetAddress will be used. * * @since PircBotX 1.4.4 * * @return The current DCC InetAddress, or null if left as default. */ public InetAddress getDccInetAddress() { return _dccInetAddress; } /** * Returns the set of port numbers to be used when sending a DCC chat * or file transfer. This is useful when you are behind a firewall and * need to set up port forwarding. The array of port numbers is traversed * in sequence until a free port is found to listen on. A DCC tranfer will * fail if all ports are already in use. * If set to null, <i>any</i> free port number will be used. * * @since PircBotX 1.4.4 * * @return An array of port numbers that PircBotX can use to send DCC * transfers, or null if any port is allowed. */ public int[] getDccPorts() { if (_dccPorts == null || _dccPorts.length == 0) return null; // Clone the array to prevent external modification. return (int[]) _dccPorts.clone(); } /** * Sets the choice of port numbers that can be used when sending a DCC chat * or file transfer. This is useful when you are behind a firewall and * need to set up port forwarding. The array of port numbers is traversed * in sequence until a free port is found to listen on. A DCC transfer will * fail if all ports are already in use. * If set to null, <i>any</i> free port number will be used. * * @since PircBotX 1.4.4 * * @param ports The set of port numbers that PircBotX may use for DCC * transfers, or null to let it use any free port (default). * */ public void setDccPorts(int[] ports) { if (ports == null || ports.length == 0) _dccPorts = null; else // Clone the array to prevent external modification. _dccPorts = (int[]) ports.clone(); } /** * Returns a String representation of this object. * You may find this useful for debugging purposes, particularly * if you are using more than one PircBotX instance to achieve * multiple server connectivity. The format of * this String may change between different versions of PircBotX * but is currently something of the form * <code> * Version{PircBotX x.y.z Java IRC Bot - www.jibble.org} * Connected{true} * Server{irc.dal.net} * Port{6667} * Password{} * </code> * * @since PircBotX 0.9.10 * * @return a String representation of this object. */ @Override public String toString() { return "Version{" + _version + "}" + " Connected{" + isConnected() + "}" + " Server{" + _server + "}" + " Port{" + _port + "}" + " Password{" + _password + "}"; } /** * Disposes of all thread resources used by this PircBotX. This may be * useful when writing bots or clients that use multiple servers (and * therefore multiple PircBotX instances) or when integrating a PircBotX * with an existing program. * <p> * Each PircBotX runs its own threads for dispatching messages from its * outgoing message queue and receiving messages from the server. * Calling dispose() ensures that these threads are * stopped, thus freeing up system resources and allowing the PircBotX * object to be garbage collected if there are no other references to * it. * <p> * Once a PircBotX object has been disposed, it should not be used again. * Attempting to use a PircBotX that has been disposed may result in * unpredictable behaviour. * * @since 1.2.2 */ public synchronized void dispose() { log("disposing..."); //Close the socket from here and let the threads die try { _socket.close(); } catch (Exception e) { //Something went wrong, interrupt to make sure they are closed _outputThread.interrupt(); _inputThread.interrupt(); } } /** * The number of milliseconds to wait before the socket times out on read * operations. This does not mean the socket is invalid. By default its 5 * minutes * @return the socketTimeout */ public int getSocketTimeout() { return socketTimeout; } /** * The number of milliseconds to wait before the socket times out on read * operations. This does not mean the socket is invalid. By default its 5 * minutes * @param socketTimeout the socketTimeout to set */ public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } /** * Returns an array of all channels that we are in. Note that if you * call this method immediately after joining a new channel, the new * channel may not appear in this array as it is not possible to tell * if the join was successful until a response is received from the * IRC server. * * @since PircBotX 1.0.0 * * @return An <i>unmodifiable</i> Set of all channels were connected to */ public Set<Channel> getChannels() { return _userChanInfo.getAValues(); } /** * Get all channels that the given user is connected to * @param user The user to lookup * @return An <i>unmodifiable</i> Set of user's in the channel */ public Set<Channel> getChannels(User user) { if (user == null) throw new NullPointerException("Can't get a null user"); return _userChanInfo.getAValues(user); } /** * Gets a channel or creates a <u>new</u> one. Never returns null * @param name The name of the channel * @return The channel object requested, never null */ public Channel getChannel(String name) { if (name == null) throw new NullPointerException("Can't get a null channel"); for (Channel curChan : _userChanInfo.getAValues()) if (curChan.getName().equals(name)) return curChan; //Channel does not exist, create one Channel chan = new Channel(this, name); _userChanInfo.putB(chan); return chan; } /** * Gets all the name's of all the channels that we are connected to * @return An <i>Unmodifiable</i> set of Channel names */ public Set<String> getChannelsNames() { return Collections.unmodifiableSet(new HashSet<String>() { { for (Channel curChan : _userChanInfo.getAValues()) add(curChan.getName()); } }); } /** * Check if we are still connected to the given channel. Useful for checking * the validity of existing Channel objects * @param chan A (potentially invalid) channel object * @return True if we are still connected to the channel, false if not */ public boolean channelExists(Channel chan) { return _userChanInfo.containsA(chan); } /** * Get all user's in the channel. * * There are some important things to note about this method:- * <ul> * <li>This method may not return a full list of users if you call it * before the complete nick list has arrived from the IRC server. * </li> * <li>If you wish to find out which users are in a channel as soon * as you join it, then you should listen for a {@link UserListEvent} * instead of calling this method, as the {@link UserListEvent} is only * dispatched as soon as the full user list has been received. * </li> * <li>This method will return immediately, as it does not require any * interaction with the IRC server. * </li> * <li>The bot must be in a channel to be able to know which users are * in it. * </li> * </ul> * * @since PircBotX 1.0.0 * * @param chan The channel object to search in * @return A Set of all user's in the channel * * @see UserListEvent */ public Set<User> getUsers(Channel chan) { if (chan == null) throw new NullPointerException("Can't get a null channel"); return _userChanInfo.getBValues(chan); } /** * Gets an existing user or creates a new one. * @param nick * @return The requested User. Never is null */ public User getUser(String nick) { if (nick == null) throw new NullPointerException("Can't get a null user"); for (User curUser : _userChanInfo.getBValues()) if (curUser.getNick().equals(nick)) return curUser; //User does not exist, create one User user = new User(this, nick); _userChanInfo.putA(user); return user; } /** * Check if a user exists * @param nick The nick of the user to lookup * @return True if they exist, false if not */ public boolean userExists(String nick) { for (User curUser : _userChanInfo.getBValues()) if (curUser.getNick().equals(nick)) return true; return false; } /** * @return the serverInfo */ public ServerInfo getServerInfo() { return serverInfo; } /** * Returns the current ListenerManager in use by this bot. * @return Current ListenerManager */ public ListenerManager getListenerManager() { return listenerManager; } /** * Sets a new ListenerManager. <b>NOTE:</b> The {@link CoreHooks} are added * when this method is called. If you do not want this, remove CoreHooks with * {@link ListenerManager#removeListener(org.pircbotx.hooks.Listener) } * @param listenerManager The listener manager */ public void setListenerManager(ListenerManager<? extends PircBotX> listenerManager) { this.listenerManager = listenerManager; //Check if corehooks already exist for (Listener curListener : listenerManager.getListeners()) if (curListener instanceof CoreHooks) return; listenerManager.addListener(new CoreHooks()); } /** * Returns the last SocketFactory that we used to connect to an IRC server. * This does not imply that the connection attempt to the server was * successful (we suggest you look at the onConnect method). * A value of null is returned if the PircBot has never tried to connect * to a server using a SocketFactory. * * @return The last SocketFactory that we used when connecting to an IRC server. * Returns null if we have not previously connected using a SocketFactory. */ public SocketFactory getSocketFactory() { return _socketFactory; } /** * Get current verbose mode * @return True if verbose is turned on, false if not */ public boolean isVerbose() { return _verbose; } /** * Get current auto nick change mode * @return True if auto nick change is turned on, false otherwise */ public boolean isAutoNickChange() { return _autoNickChange; } /** * Reset bot, clearing all internal fields */ void reset() { //Clear the user-channel map _userChanInfo.clear(); //Clear any existing channel list channelListBuilder.finish(); //Clear any information that might be provided in another connect() method _server = null; _port = -1; _password = null; _inetAddress = null; _socket = null; } /** * Using the specified eventClass, block until the Event occurs. Eg wait for * a response from a user, capturing the MessageEvent or PrivateMessageEvent. * <p> * <b>Warning:</b> The listener manager in use <i>must</i> support multithreading. * If not, the entire bot will freeze since its waiting in the same thread * that's reading input from the server. This means you <i>can't</i> use * {@link GenericListenerManager}. * @param eventClass The class representing the Event to capture * @return The requested event * @throws InterruptedException If the thread is interrupted, this exception * is thrown */ public <E extends Event> E waitFor(Class<? extends E> eventClass) throws InterruptedException { //Create a WaitListener for getting the event WaitListener waitListener = new WaitListener(); listenerManager.addListener(waitListener); //Call waitFor which blocks until the desired event is captured Event finalEvent = waitListener.waitFor(eventClass); //Remove listener since its no longer needed listenerManager.removeListener(waitListener); //Return requested listener return (E) finalEvent; } /** * A listener that waits for the specified event before returning. Used in * {@link PircBotX#waitFor(java.lang.Class) } */ protected class WaitListener implements Listener { protected CountDownLatch signal = new CountDownLatch(1); protected Class<? extends Event> eventClass; protected Event endEvent; public void onEvent(Event event) throws Exception { if (eventClass.isInstance(event)) { endEvent = event; //Unblock waitFor now that we have an event signal.countDown(); } } /** * Block until the Event represented by the given class is passed * @param event A class representing the event to wait for * @return The specified event * @throws InterruptedException If the thread is interrupted, this exception * is thrown */ public Event waitFor(Class<? extends Event> event) throws InterruptedException { eventClass = event; signal.await(); return endEvent; } } protected class ListBuilder<A> { @Getter @Setter private boolean running = false; private Set<A> channels = new HashSet(); public Set<A> finish() { running = false; Set<A> copy = new HashSet(channels); channels.clear(); return copy; } public void add(A entry) { running = true; channels.add(entry); } } }
true
true
protected void handleLine(String line) { log("<<<" + line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. getListenerManager().dispatchEvent(new ServerPingEvent(this, line.substring(5))); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else { // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; target = token; } } else { // We don't know what this line means. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); User source = getUser(sourceNick); //If the channel matches a prefix, then its a channel Channel channel = (_channelPrefixes.indexOf(target.charAt(0)) >= 0) ? null : getChannel(target); // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request getListenerManager().dispatchEvent(new VersionEvent(this, source, channel)); else if (request.startsWith("ACTION ")) // ACTION request getListenerManager().dispatchEvent(new ActionEvent(this, source, channel, request.substring(7))); else if (request.startsWith("PING ")) // PING request getListenerManager().dispatchEvent(new PingEvent(this, source, channel, request.substring(5))); else if (request.equals("TIME")) // TIME request getListenerManager().dispatchEvent(new TimeEvent(this, source, channel)); else if (request.equals("FINGER")) // FINGER request getListenerManager().dispatchEvent(new FingerEvent(this, source, channel)); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(source, request); if (!success) // The DccManager didn't know what to do with the line. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else // An unknown CTCP message - ignore it. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. getListenerManager().dispatchEvent(new MessageEvent(this, channel, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("PRIVMSG")) // This is a private message to us. getListenerManager().dispatchEvent(new PrivateMessageEvent(this, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("JOIN")) { // Someone is joining a channel. if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup (don't use channel var since channel doesn't exist yet) sendRawLine("WHO " + target); sendRawLine("MODE " + target); } User usr = getUser(sourceNick); //Only setup if nessesary if (usr.getHostmask() == null) { usr.setLogin(sourceLogin); usr.setHostmask(sourceHostname); } //user.addUser(usr); getListenerManager().dispatchEvent(new JoinEvent(this, channel, source)); } else if (command.equals("PART")) // Someone is parting from a channel. if (sourceNick.equals(getNick())) //We parted the channel _userChanInfo.deleteA(channel); else { //Just remove the user from memory _userChanInfo.dissociate(channel, getUser(sourceNick)); getListenerManager().dispatchEvent(new PartEvent(this, channel, source)); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; getUser(sourceNick).setNick(newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); getListenerManager().dispatchEvent(new NickChangeEvent(this, sourceNick, newNick, source)); } else if (command.equals("NOTICE")) // Someone is sending a notice. getListenerManager().dispatchEvent(new NoticeEvent(this, source, channel, line.substring(line.indexOf(" :") + 2))); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) //We just quit the server _userChanInfo.clear(); else //Someone else _userChanInfo.deleteB(getUser(sourceNick)); getListenerManager().dispatchEvent(new QuitEvent(this, source, line.substring(line.indexOf(" :") + 2))); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); User user = getUser(sourceNick); if (recipient.equals(getNick())) //We were just kicked _userChanInfo.deleteA(channel); else //Someone else _userChanInfo.dissociate(channel, user, true); getListenerManager().dispatchEvent(new KickEvent(this, channel, source, getUser(recipient), line.substring(line.indexOf(" :") + 2))); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) { // Someone is changing the topic. String topic = line.substring(line.indexOf(" :") + 2); long currentTime = System.currentTimeMillis(); channel.setTopic(topic); channel.setTopicSetter(sourceNick); channel.setTopicTimestamp(currentTime); getListenerManager().dispatchEvent(new TopicEvent(this, channel, topic, source, currentTime, true)); } else if (command.equals("INVITE")) { // Somebody is inviting somebody else into a channel. //Use line method instead of channel since channel is wrong getListenerManager().dispatchEvent(new InviteEvent(this, source, line.substring(line.indexOf(" :") + 2))); } else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); }
protected void handleLine(String line) { log("<<<" + line); // Check for server pings. if (line.startsWith("PING ")) { // Respond to the ping and return immediately. getListenerManager().dispatchEvent(new ServerPingEvent(this, line.substring(5))); return; } String sourceNick = ""; String sourceLogin = ""; String sourceHostname = ""; StringTokenizer tokenizer = new StringTokenizer(line); String senderInfo = tokenizer.nextToken(); String command = tokenizer.nextToken(); String target = null; int exclamation = senderInfo.indexOf("!"); int at = senderInfo.indexOf("@"); if (senderInfo.startsWith(":")) if (exclamation > 0 && at > 0 && exclamation < at) { sourceNick = senderInfo.substring(1, exclamation); sourceLogin = senderInfo.substring(exclamation + 1, at); sourceHostname = senderInfo.substring(at + 1); } else if (tokenizer.hasMoreTokens()) { String token = command; int code = -1; try { code = Integer.parseInt(token); } catch (NumberFormatException e) { // Keep the existing value. } if (code != -1) { String errorStr = token; String response = line.substring(line.indexOf(errorStr, senderInfo.length()) + 4, line.length()); processServerResponse(code, response); // Return from the method. return; } else { // This is not a server response. // It must be a nick without login and hostname. // (or maybe a NOTICE or suchlike from the server) sourceNick = senderInfo; target = token; } } else { // We don't know what this line means. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); // Return from the method; return; } command = command.toUpperCase(); if (sourceNick.startsWith(":")) sourceNick = sourceNick.substring(1); if (target == null) target = tokenizer.nextToken(); if (target.startsWith(":")) target = target.substring(1); User source = getUser(sourceNick); //If the channel matches a prefix, then its a channel Channel channel = (_channelPrefixes.indexOf(target.charAt(0)) >= 0) ? getChannel(target) : null ; // Check for CTCP requests. if (command.equals("PRIVMSG") && line.indexOf(":\u0001") > 0 && line.endsWith("\u0001")) { String request = line.substring(line.indexOf(":\u0001") + 2, line.length() - 1); if (request.equals("VERSION")) // VERSION request getListenerManager().dispatchEvent(new VersionEvent(this, source, channel)); else if (request.startsWith("ACTION ")) // ACTION request getListenerManager().dispatchEvent(new ActionEvent(this, source, channel, request.substring(7))); else if (request.startsWith("PING ")) // PING request getListenerManager().dispatchEvent(new PingEvent(this, source, channel, request.substring(5))); else if (request.equals("TIME")) // TIME request getListenerManager().dispatchEvent(new TimeEvent(this, source, channel)); else if (request.equals("FINGER")) // FINGER request getListenerManager().dispatchEvent(new FingerEvent(this, source, channel)); else if ((tokenizer = new StringTokenizer(request)).countTokens() >= 5 && tokenizer.nextToken().equals("DCC")) { // This is a DCC request. boolean success = _dccManager.processRequest(source, request); if (!success) // The DccManager didn't know what to do with the line. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else // An unknown CTCP message - ignore it. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); } else if (command.equals("PRIVMSG") && _channelPrefixes.indexOf(target.charAt(0)) >= 0) // This is a normal message to a channel. getListenerManager().dispatchEvent(new MessageEvent(this, channel, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("PRIVMSG")) // This is a private message to us. getListenerManager().dispatchEvent(new PrivateMessageEvent(this, source, line.substring(line.indexOf(" :") + 2))); else if (command.equals("JOIN")) { // Someone is joining a channel. if (sourceNick.equalsIgnoreCase(_nick)) { //Its us, do some setup (don't use channel var since channel doesn't exist yet) sendRawLine("WHO " + target); sendRawLine("MODE " + target); } User usr = getUser(sourceNick); //Only setup if nessesary if (usr.getHostmask() == null) { usr.setLogin(sourceLogin); usr.setHostmask(sourceHostname); } //user.addUser(usr); getListenerManager().dispatchEvent(new JoinEvent(this, channel, source)); } else if (command.equals("PART")) // Someone is parting from a channel. if (sourceNick.equals(getNick())) //We parted the channel _userChanInfo.deleteA(channel); else { //Just remove the user from memory _userChanInfo.dissociate(channel, getUser(sourceNick)); getListenerManager().dispatchEvent(new PartEvent(this, channel, source)); } else if (command.equals("NICK")) { // Somebody is changing their nick. String newNick = target; getUser(sourceNick).setNick(newNick); if (sourceNick.equals(getNick())) // Update our nick if it was us that changed nick. setNick(newNick); getListenerManager().dispatchEvent(new NickChangeEvent(this, sourceNick, newNick, source)); } else if (command.equals("NOTICE")) // Someone is sending a notice. getListenerManager().dispatchEvent(new NoticeEvent(this, source, channel, line.substring(line.indexOf(" :") + 2))); else if (command.equals("QUIT")) { // Someone has quit from the IRC server. if (sourceNick.equals(getNick())) //We just quit the server _userChanInfo.clear(); else //Someone else _userChanInfo.deleteB(getUser(sourceNick)); getListenerManager().dispatchEvent(new QuitEvent(this, source, line.substring(line.indexOf(" :") + 2))); } else if (command.equals("KICK")) { // Somebody has been kicked from a channel. String recipient = tokenizer.nextToken(); User user = getUser(sourceNick); if (recipient.equals(getNick())) //We were just kicked _userChanInfo.deleteA(channel); else //Someone else _userChanInfo.dissociate(channel, user, true); getListenerManager().dispatchEvent(new KickEvent(this, channel, source, getUser(recipient), line.substring(line.indexOf(" :") + 2))); } else if (command.equals("MODE")) { // Somebody is changing the mode on a channel or user. String mode = line.substring(line.indexOf(target, 2) + target.length() + 1); if (mode.startsWith(":")) mode = mode.substring(1); processMode(target, sourceNick, sourceLogin, sourceHostname, mode); } else if (command.equals("TOPIC")) { // Someone is changing the topic. String topic = line.substring(line.indexOf(" :") + 2); long currentTime = System.currentTimeMillis(); channel.setTopic(topic); channel.setTopicSetter(sourceNick); channel.setTopicTimestamp(currentTime); getListenerManager().dispatchEvent(new TopicEvent(this, channel, topic, source, currentTime, true)); } else if (command.equals("INVITE")) { // Somebody is inviting somebody else into a channel. //Use line method instead of channel since channel is wrong getListenerManager().dispatchEvent(new InviteEvent(this, source, line.substring(line.indexOf(" :") + 2))); } else // If we reach this point, then we've found something that the PircBotX // Doesn't currently deal with. getListenerManager().dispatchEvent(new UnknownEvent(this, line)); }
diff --git a/src/java/org/apache/nutch/mapred/TaskRunner.java b/src/java/org/apache/nutch/mapred/TaskRunner.java index fd95bef7..a4acd17a 100644 --- a/src/java/org/apache/nutch/mapred/TaskRunner.java +++ b/src/java/org/apache/nutch/mapred/TaskRunner.java @@ -1,180 +1,182 @@ /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.mapred; import org.apache.nutch.io.*; import org.apache.nutch.ipc.*; import org.apache.nutch.util.*; import org.apache.nutch.fs.*; import java.io.*; import java.net.*; import java.util.*; import java.util.logging.*; /** Base class that runs a task in a separate process. Tasks are run in a * separate process in order to isolate the map/reduce system code from bugs in * user supplied map and reduce functions. */ abstract class TaskRunner extends Thread { public static final Logger LOG = LogFormatter.getLogger("org.apache.nutch.mapred.TaskRunner"); private Process process; private Task t; private TaskTracker tracker; protected NutchConf nutchConf; public TaskRunner(Task t, TaskTracker tracker, NutchConf nutchConf) { this.t = t; this.tracker = tracker; this.nutchConf = nutchConf; } public Task getTask() { return t; } public TaskTracker getTracker() { return tracker; } /** Called to assemble this task's input. This method is run in the parent * process before the child is spawned. It should not execute user code, * only system code. */ public void prepare() throws IOException {} /** Called when this task's output is no longer needed. * This method is run in the parent process after the child exits. It should * not execute user code, only system code. */ public void close() throws IOException {} public final void run() { try { prepare(); String sep = System.getProperty("path.separator"); File workDir = new File(new File(t.getJobFile()).getParent(), "work"); workDir.mkdirs(); StringBuffer classPath = new StringBuffer(); // start with same classpath as parent process classPath.append(System.getProperty("java.class.path")); classPath.append(sep); JobConf job = new JobConf(t.getJobFile()); String jar = job.getJar(); if (jar != null) { // if jar exists, it into workDir runChild(new String[] { "unzip", jar}, workDir); File[] libs = new File(workDir, "lib").listFiles(); - for (int i = 0; i < libs.length; i++) { - classPath.append(sep); // add libs from jar to classpath - classPath.append(libs[i]); + if (libs != null) { + for (int i = 0; i < libs.length; i++) { + classPath.append(sep); // add libs from jar to classpath + classPath.append(libs[i]); + } } classPath.append(sep); classPath.append(new File(workDir, "classes")); classPath.append(sep); classPath.append(workDir); } File jvm = // use same jvm as parent new File(new File(System.getProperty("java.home"), "bin"), "java"); // run java runChild(new String[] { jvm.toString(), //"-Xrunhprof:cpu=samples,file="+t.getTaskId()+".prof", "-Xmx"+job.get("mapred.child.heap.size", "200m"), "-cp", classPath.toString(), TaskTracker.Child.class.getName(), // main is Child tracker.taskReportPort+"", // pass umbilical port t.getTaskId() // pass task identifier }, workDir); } catch (FSError e) { LOG.log(Level.SEVERE, "FSError", e); try { tracker.fsError(e.getMessage()); } catch (IOException ie) { LOG.log(Level.SEVERE, t.getTaskId()+" reporting FSError", ie); } } catch (Throwable throwable) { LOG.log(Level.WARNING, t.getTaskId()+" Child Error", throwable); ByteArrayOutputStream baos = new ByteArrayOutputStream(); throwable.printStackTrace(new PrintStream(baos)); try { tracker.reportDiagnosticInfo(t.getTaskId(), baos.toString()); } catch (IOException e) { LOG.log(Level.WARNING, t.getTaskId()+" Reporting Diagnostics", e); } } finally { tracker.reportTaskFinished(t.getTaskId()); } } /** * Run the child process */ private void runChild(String[] args, File dir) throws IOException { this.process = Runtime.getRuntime().exec(args, null, dir); try { StringBuffer errorBuf = new StringBuffer(); new Thread() { public void run() { logStream(process.getErrorStream()); // copy log output } }.start(); logStream(process.getInputStream()); // normally empty if (this.process.waitFor() != 0) { throw new IOException("Task process exit with nonzero status."); } } catch (InterruptedException e) { throw new IOException(e.toString()); } finally { kill(); } } /** * Kill the child process */ public void kill() { if (process != null) { process.destroy(); } } /** */ private void logStream(InputStream output) { try { BufferedReader in = new BufferedReader(new InputStreamReader(output)); String line; while ((line = in.readLine()) != null) { LOG.info(t.getTaskId()+" "+line); } } catch (IOException e) { LOG.log(Level.WARNING, t.getTaskId()+" Error reading child output", e); } finally { try { output.close(); } catch (IOException e) { LOG.log(Level.WARNING, t.getTaskId()+" Error closing child output", e); } } } }
true
true
public final void run() { try { prepare(); String sep = System.getProperty("path.separator"); File workDir = new File(new File(t.getJobFile()).getParent(), "work"); workDir.mkdirs(); StringBuffer classPath = new StringBuffer(); // start with same classpath as parent process classPath.append(System.getProperty("java.class.path")); classPath.append(sep); JobConf job = new JobConf(t.getJobFile()); String jar = job.getJar(); if (jar != null) { // if jar exists, it into workDir runChild(new String[] { "unzip", jar}, workDir); File[] libs = new File(workDir, "lib").listFiles(); for (int i = 0; i < libs.length; i++) { classPath.append(sep); // add libs from jar to classpath classPath.append(libs[i]); } classPath.append(sep); classPath.append(new File(workDir, "classes")); classPath.append(sep); classPath.append(workDir); } File jvm = // use same jvm as parent new File(new File(System.getProperty("java.home"), "bin"), "java"); // run java runChild(new String[] { jvm.toString(), //"-Xrunhprof:cpu=samples,file="+t.getTaskId()+".prof", "-Xmx"+job.get("mapred.child.heap.size", "200m"), "-cp", classPath.toString(), TaskTracker.Child.class.getName(), // main is Child tracker.taskReportPort+"", // pass umbilical port t.getTaskId() // pass task identifier }, workDir); } catch (FSError e) { LOG.log(Level.SEVERE, "FSError", e); try { tracker.fsError(e.getMessage()); } catch (IOException ie) { LOG.log(Level.SEVERE, t.getTaskId()+" reporting FSError", ie); } } catch (Throwable throwable) { LOG.log(Level.WARNING, t.getTaskId()+" Child Error", throwable); ByteArrayOutputStream baos = new ByteArrayOutputStream(); throwable.printStackTrace(new PrintStream(baos)); try { tracker.reportDiagnosticInfo(t.getTaskId(), baos.toString()); } catch (IOException e) { LOG.log(Level.WARNING, t.getTaskId()+" Reporting Diagnostics", e); } } finally { tracker.reportTaskFinished(t.getTaskId()); } }
public final void run() { try { prepare(); String sep = System.getProperty("path.separator"); File workDir = new File(new File(t.getJobFile()).getParent(), "work"); workDir.mkdirs(); StringBuffer classPath = new StringBuffer(); // start with same classpath as parent process classPath.append(System.getProperty("java.class.path")); classPath.append(sep); JobConf job = new JobConf(t.getJobFile()); String jar = job.getJar(); if (jar != null) { // if jar exists, it into workDir runChild(new String[] { "unzip", jar}, workDir); File[] libs = new File(workDir, "lib").listFiles(); if (libs != null) { for (int i = 0; i < libs.length; i++) { classPath.append(sep); // add libs from jar to classpath classPath.append(libs[i]); } } classPath.append(sep); classPath.append(new File(workDir, "classes")); classPath.append(sep); classPath.append(workDir); } File jvm = // use same jvm as parent new File(new File(System.getProperty("java.home"), "bin"), "java"); // run java runChild(new String[] { jvm.toString(), //"-Xrunhprof:cpu=samples,file="+t.getTaskId()+".prof", "-Xmx"+job.get("mapred.child.heap.size", "200m"), "-cp", classPath.toString(), TaskTracker.Child.class.getName(), // main is Child tracker.taskReportPort+"", // pass umbilical port t.getTaskId() // pass task identifier }, workDir); } catch (FSError e) { LOG.log(Level.SEVERE, "FSError", e); try { tracker.fsError(e.getMessage()); } catch (IOException ie) { LOG.log(Level.SEVERE, t.getTaskId()+" reporting FSError", ie); } } catch (Throwable throwable) { LOG.log(Level.WARNING, t.getTaskId()+" Child Error", throwable); ByteArrayOutputStream baos = new ByteArrayOutputStream(); throwable.printStackTrace(new PrintStream(baos)); try { tracker.reportDiagnosticInfo(t.getTaskId(), baos.toString()); } catch (IOException e) { LOG.log(Level.WARNING, t.getTaskId()+" Reporting Diagnostics", e); } } finally { tracker.reportTaskFinished(t.getTaskId()); } }
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentResolver.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentResolver.java index 4a1ebee2..422b6d64 100644 --- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentResolver.java +++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ComponentResolver.java @@ -1,89 +1,91 @@ /******************************************************************************* * Copyright (c) 2001, 2005 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.wst.common.componentcore.internal.util; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.wst.common.componentcore.ComponentCore; import org.eclipse.wst.common.componentcore.resources.IVirtualFile; import org.eclipse.wst.common.componentcore.resources.IVirtualResource; import org.eclipse.wst.common.uriresolver.internal.provisional.URIResolverExtension; public class ComponentResolver implements URIResolverExtension { private static boolean _DEBUG = false; private static final String FILE_PROTOCOL = "file://"; public String resolve(IFile file, String baseLocation, String publicId, String systemId) { if (_DEBUG) { System.out.print(getClass().getName() + ": resolve \"" + systemId + "\" from \"" + baseLocation + "\""); } if (baseLocation == null || systemId == null || file == null) { if (_DEBUG) { System.out.println(); } return null; } try { URL testURL = new URL(systemId); if (testURL != null) { // an absolute system ID, no need to "resolve" it if (_DEBUG) { System.out.println("reference is a URL"); } return null; } } catch (MalformedURLException e) { // Continue resolving } boolean prependFilePrefix = baseLocation.startsWith(FILE_PROTOCOL) && baseLocation.length() > 7; String resolvedPath = null; IVirtualResource[] virtualResources = ComponentCore.createResources(file); // only return results for Flexible projects if (virtualResources != null) { for (int i = 0; i < virtualResources.length && resolvedPath == null; i++) { IPath resolvedRuntimePath = null; if (systemId.startsWith("/")) { resolvedRuntimePath = new Path(systemId); } else { - resolvedRuntimePath = virtualResources[i].getRuntimePath().removeLastSegments(1).append(systemId); + return null; + // resolvedRuntimePath = + // virtualResources[i].getRuntimePath().removeLastSegments(1).append(systemId); } IVirtualFile virtualFile = ComponentCore.createFile(file.getProject(), virtualResources[i].getComponent().getName(), resolvedRuntimePath); IFile resolvedFile = virtualFile.getUnderlyingFile(); if (resolvedFile != null && resolvedFile.getLocation() != null) { if (prependFilePrefix) { resolvedPath = FILE_PROTOCOL + resolvedFile.getLocation().toString(); } else { resolvedPath = resolvedFile.getLocation().toString(); } } } } else { if (_DEBUG) { System.out.print(" (not in flexible project) "); } } if (_DEBUG) { System.out.println(" -> \"" + resolvedPath + "\""); } return resolvedPath; } }
true
true
public String resolve(IFile file, String baseLocation, String publicId, String systemId) { if (_DEBUG) { System.out.print(getClass().getName() + ": resolve \"" + systemId + "\" from \"" + baseLocation + "\""); } if (baseLocation == null || systemId == null || file == null) { if (_DEBUG) { System.out.println(); } return null; } try { URL testURL = new URL(systemId); if (testURL != null) { // an absolute system ID, no need to "resolve" it if (_DEBUG) { System.out.println("reference is a URL"); } return null; } } catch (MalformedURLException e) { // Continue resolving } boolean prependFilePrefix = baseLocation.startsWith(FILE_PROTOCOL) && baseLocation.length() > 7; String resolvedPath = null; IVirtualResource[] virtualResources = ComponentCore.createResources(file); // only return results for Flexible projects if (virtualResources != null) { for (int i = 0; i < virtualResources.length && resolvedPath == null; i++) { IPath resolvedRuntimePath = null; if (systemId.startsWith("/")) { resolvedRuntimePath = new Path(systemId); } else { resolvedRuntimePath = virtualResources[i].getRuntimePath().removeLastSegments(1).append(systemId); } IVirtualFile virtualFile = ComponentCore.createFile(file.getProject(), virtualResources[i].getComponent().getName(), resolvedRuntimePath); IFile resolvedFile = virtualFile.getUnderlyingFile(); if (resolvedFile != null && resolvedFile.getLocation() != null) { if (prependFilePrefix) { resolvedPath = FILE_PROTOCOL + resolvedFile.getLocation().toString(); } else { resolvedPath = resolvedFile.getLocation().toString(); } } } } else { if (_DEBUG) { System.out.print(" (not in flexible project) "); } } if (_DEBUG) { System.out.println(" -> \"" + resolvedPath + "\""); } return resolvedPath; }
public String resolve(IFile file, String baseLocation, String publicId, String systemId) { if (_DEBUG) { System.out.print(getClass().getName() + ": resolve \"" + systemId + "\" from \"" + baseLocation + "\""); } if (baseLocation == null || systemId == null || file == null) { if (_DEBUG) { System.out.println(); } return null; } try { URL testURL = new URL(systemId); if (testURL != null) { // an absolute system ID, no need to "resolve" it if (_DEBUG) { System.out.println("reference is a URL"); } return null; } } catch (MalformedURLException e) { // Continue resolving } boolean prependFilePrefix = baseLocation.startsWith(FILE_PROTOCOL) && baseLocation.length() > 7; String resolvedPath = null; IVirtualResource[] virtualResources = ComponentCore.createResources(file); // only return results for Flexible projects if (virtualResources != null) { for (int i = 0; i < virtualResources.length && resolvedPath == null; i++) { IPath resolvedRuntimePath = null; if (systemId.startsWith("/")) { resolvedRuntimePath = new Path(systemId); } else { return null; // resolvedRuntimePath = // virtualResources[i].getRuntimePath().removeLastSegments(1).append(systemId); } IVirtualFile virtualFile = ComponentCore.createFile(file.getProject(), virtualResources[i].getComponent().getName(), resolvedRuntimePath); IFile resolvedFile = virtualFile.getUnderlyingFile(); if (resolvedFile != null && resolvedFile.getLocation() != null) { if (prependFilePrefix) { resolvedPath = FILE_PROTOCOL + resolvedFile.getLocation().toString(); } else { resolvedPath = resolvedFile.getLocation().toString(); } } } } else { if (_DEBUG) { System.out.print(" (not in flexible project) "); } } if (_DEBUG) { System.out.println(" -> \"" + resolvedPath + "\""); } return resolvedPath; }
diff --git a/upt/webapp/src/gov/nih/nci/security/upt/actions/CommonDBAction.java b/upt/webapp/src/gov/nih/nci/security/upt/actions/CommonDBAction.java index 609260e6..72c2c698 100755 --- a/upt/webapp/src/gov/nih/nci/security/upt/actions/CommonDBAction.java +++ b/upt/webapp/src/gov/nih/nci/security/upt/actions/CommonDBAction.java @@ -1,508 +1,509 @@ /* * Created on Dec 3, 2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package gov.nih.nci.security.upt.actions; /** * *<!-- LICENSE_TEXT_START --> * *The NCICB Common Security Module's User Provisioning Tool (UPT) Software License, *Version 3.0 Copyright 2004-2005 Ekagra Software Technologies Limited ('Ekagra') * *Copyright Notice. The software subject to this notice and license includes both *human readable source code form and machine readable, binary, object code form *(the 'UPT Software'). The UPT Software was developed in conjunction with the *National Cancer Institute ('NCI') by NCI employees and employees of Ekagra. To *the extent government employees are authors, any rights in such works shall be *subject to Title 17 of the United States Code, section 105. * *This UPT Software License (the 'License') is between NCI and You. 'You (or *'Your') shall mean a person or an entity, and all other entities that control, *are controlled by, or are under common control with the entity. 'Control' for *purposes of this definition means (i) the direct or indirect power to cause the *direction or management of such entity, whether by contract or otherwise, or *(ii) ownership of fifty percent (50%) or more of the outstanding shares, or *(iii) beneficial ownership of such entity. * *This License is granted provided that You agree to the conditions described *below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up, *no-charge, irrevocable, transferable and royalty-free right and license in its *rights in the UPT Software to (i) use, install, access, operate, execute, copy, *modify, translate, market, publicly display, publicly perform, and prepare *derivative works of the UPT Software; (ii) distribute and have distributed to *and by third parties the UPT Software and any modifications and derivative works *thereof; and (iii) sublicense the foregoing rights set out in (i) and (ii) to *third parties, including the right to license such rights to further third *parties. For sake of clarity, and not by way of limitation, NCI shall have no *right of accounting or right of payment from You or Your sublicensees for the *rights granted under this License. This License is granted at no charge to You. * *1. Your redistributions of the source code for the Software must retain the *above copyright notice, this list of conditions and the disclaimer and *limitation of liability of Article 6 below. Your redistributions in object code *form must reproduce the above copyright notice, this list of conditions and the *disclaimer of Article 6 in the documentation and/or other materials provided *with the distribution, if any. *2. Your end-user documentation included with the redistribution, if any, must *include the following acknowledgment: 'This product includes software developed *by Ekagra and the National Cancer Institute.' If You do not include such *end-user documentation, You shall include this acknowledgment in the Software *itself, wherever such third-party acknowledgments normally appear. * *3. You may not use the names 'The National Cancer Institute', 'NCI' 'Ekagra *Software Technologies Limited' and 'Ekagra' to endorse or promote products *derived from this Software. This License does not authorize You to use any *trademarks, service marks, trade names, logos or product names of either NCI or *Ekagra, except as required to comply with the terms of this License. * *4. For sake of clarity, and not by way of limitation, You may incorporate this *Software into Your proprietary programs and into any third party proprietary *programs. However, if You incorporate the Software into third party proprietary *programs, You agree that You are solely responsible for obtaining any permission *from such third parties required to incorporate the Software into such third *party proprietary programs and for informing Your sublicensees, including *without limitation Your end-users, of their obligation to secure any required *permissions from such third parties before incorporating the Software into such *third party proprietary software programs. In the event that You fail to obtain *such permissions, You agree to indemnify NCI for any claims against NCI by such *third parties, except to the extent prohibited by law, resulting from Your *failure to obtain such permissions. * *5. For sake of clarity, and not by way of limitation, You may add Your own *copyright statement to Your modifications and to the derivative works, and You *may provide additional or different license terms and conditions in Your *sublicenses of modifications of the Software, or any derivative works of the *Software as a whole, provided Your use, reproduction, and distribution of the *Work otherwise complies with the conditions stated in this License. * *6. THIS SOFTWARE IS PROVIDED 'AS IS,' AND ANY EXPRESSED OR IMPLIED WARRANTIES, *(INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, *NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO *EVENT SHALL THE NATIONAL CANCER INSTITUTE, EKAGRA, OR THEIR AFFILIATES 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. * *<!-- LICENSE_TEXT_END --> * */ import java.util.ArrayList; import org.apache.log4j.Logger; import gov.nih.nci.logging.api.user.UserInfoHelper; import gov.nih.nci.security.exceptions.CSException; import gov.nih.nci.security.upt.constants.DisplayConstants; import gov.nih.nci.security.upt.constants.ForwardConstants; import gov.nih.nci.security.upt.forms.BaseDBForm; import gov.nih.nci.security.upt.forms.LoginForm; import gov.nih.nci.security.upt.viewobjects.SearchResult; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.actions.DispatchAction; /** * @author Kunal Modi (Ekagra Software Technologies Ltd.) * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class CommonDBAction extends DispatchAction { private static final Logger logDB = Logger.getLogger(CommonDBAction.class); public ActionForward loadHome(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|loadHome|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } session.removeAttribute(DisplayConstants.CURRENT_ACTION); session.removeAttribute(DisplayConstants.CURRENT_FORM); session.removeAttribute(DisplayConstants.SEARCH_RESULT); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|loadHome|Success|Load the Home Page||"); return (mapping.findForward(ForwardConstants.LOAD_HOME_SUCCESS)); } public ActionForward loadAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|loadAdd|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } baseDBForm.resetForm(); session.setAttribute(DisplayConstants.CURRENT_ACTION, DisplayConstants.ADD); session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|loadAdd|Success|Loading the Add Page||"); return (mapping.findForward(ForwardConstants.LOAD_ADD_SUCCESS)); } public ActionForward loadSearch(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|loadSearch|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } baseDBForm.resetForm(); session.setAttribute(DisplayConstants.CURRENT_ACTION, DisplayConstants.SEARCH); session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|loadSearch|Success|Loading the Search Page||"); return (mapping.findForward(ForwardConstants.LOAD_SEARCH_SUCCESS)); } public ActionForward loadSearchResult(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|loadSearchResult|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } // VNP: Added this to handle Original search results for popup searches. if(session.getAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT) != null){ session.removeAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT); } if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|loadSearchResult|Success|Loading the Search Result Page||"); return (mapping.findForward(ForwardConstants.LOAD_SEARCH_RESULT_SUCCESS)); } /** * Added this method to handle pre-popup search results. */ public ActionForward loadOriginalSearchResult(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|loadSearchResult|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } if(session.getAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT) != null){ session.setAttribute(DisplayConstants.SEARCH_RESULT,session.getAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT)); session.removeAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT); } if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|loadSearchResult|Success|Loading the Search Result Page||"); return (mapping.findForward(ForwardConstants.LOAD_SEARCH_RESULT_SUCCESS)); } public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|create|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } UserInfoHelper.setUserInfo(((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(), session.getId()); try { errors = form.validate(mapping, request); if(!errors.isEmpty()) { saveErrors(request,errors); session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|create|Failure|Error validating the "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); return mapping.getInputForward(); } baseDBForm.buildDBObject(request); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(DisplayConstants.MESSAGE_ID, "Add Successful")); saveMessages( request, messages ); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|create|Failure|Error Adding the "+baseDBForm.getFormName()+" object|" +form.toString()+"|"+ cse.getMessage()); } session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|create|Success|Adding a new "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); return (mapping.findForward(ForwardConstants.CREATE_SUCCESS)); } public ActionForward read(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|read|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } if (baseDBForm.getPrimaryId() == null || baseDBForm.getPrimaryId().equalsIgnoreCase("")) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, "A record needs to be selected first to view details" )); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|read|Failure|No Primary Id for "+baseDBForm.getFormName()+" object||"); return (mapping.findForward(ForwardConstants.READ_FAILURE)); } try { baseDBForm.buildDisplayForm(request); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|read|Failure|Error Reading the "+baseDBForm.getFormName()+" object|" +form.toString()+"|"+ cse.getMessage()); } session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|read|Success|Success reading "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); return (mapping.findForward(ForwardConstants.READ_SUCCESS)); } public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|update|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } UserInfoHelper.setUserInfo(((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(), session.getId()); try { errors = form.validate(mapping, request); if(!errors.isEmpty()) { saveErrors(request,errors); session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|update|Failure|Error validating the "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); return mapping.getInputForward(); } baseDBForm.buildDBObject(request); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(DisplayConstants.MESSAGE_ID, "Update Successful")); saveMessages( request, messages ); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|update|Failure|Error Updating the "+baseDBForm.getFormName()+" object|" +form.toString()+"|"+ cse.getMessage()); } session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|update|Success|Updating existing "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); return (mapping.findForward(ForwardConstants.UPDATE_SUCCESS)); } public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|delete|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } UserInfoHelper.setUserInfo(((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(), session.getId()); try { baseDBForm.removeDBObject(request); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(DisplayConstants.MESSAGE_ID, "Delete Successful")); saveMessages( request, messages ); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|delete|Failure|Error Deleting the "+baseDBForm.getFormName()+" object|" +form.toString()+"|"+ cse.getMessage()); } session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|delete|Success|Success Deleting "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); return (mapping.findForward(ForwardConstants.DELETE_SUCCESS)); } public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|search|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } UserInfoHelper.setUserInfo(((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(), session.getId()); try { SearchResult searchResult = baseDBForm.searchObjects(request,errors,messages); if ( searchResult.getSearchResultObjects() == null || searchResult.getSearchResultObjects().isEmpty()) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, "The search criteria returned zero results")); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|search|Failure|No Records found for "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); baseDBForm.resetForm(); return (mapping.findForward(ForwardConstants.SEARCH_FAILURE)); } if (searchResult.getSearchResultMessage() != null && !(searchResult.getSearchResultMessage().trim().equalsIgnoreCase(""))) { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(DisplayConstants.MESSAGE_ID, searchResult.getSearchResultMessage())); saveMessages( request, messages ); } if(session.getAttribute(DisplayConstants.SEARCH_RESULT)!=null){ - session.setAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT, session.getAttribute(DisplayConstants.SEARCH_RESULT) ); + if(session.getAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT)==null) + session.setAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT, session.getAttribute(DisplayConstants.SEARCH_RESULT) ); } session.setAttribute(DisplayConstants.SEARCH_RESULT, searchResult); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|search|Failure|Error Searching the "+baseDBForm.getFormName()+" object|" +form.toString()+"|"+ cse.getMessage()); } session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|search|Success|Success in searching "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); return (mapping.findForward(ForwardConstants.SEARCH_SUCCESS)); } }
true
true
public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|search|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } UserInfoHelper.setUserInfo(((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(), session.getId()); try { SearchResult searchResult = baseDBForm.searchObjects(request,errors,messages); if ( searchResult.getSearchResultObjects() == null || searchResult.getSearchResultObjects().isEmpty()) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, "The search criteria returned zero results")); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|search|Failure|No Records found for "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); baseDBForm.resetForm(); return (mapping.findForward(ForwardConstants.SEARCH_FAILURE)); } if (searchResult.getSearchResultMessage() != null && !(searchResult.getSearchResultMessage().trim().equalsIgnoreCase(""))) { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(DisplayConstants.MESSAGE_ID, searchResult.getSearchResultMessage())); saveMessages( request, messages ); } if(session.getAttribute(DisplayConstants.SEARCH_RESULT)!=null){ session.setAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT, session.getAttribute(DisplayConstants.SEARCH_RESULT) ); } session.setAttribute(DisplayConstants.SEARCH_RESULT, searchResult); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|search|Failure|Error Searching the "+baseDBForm.getFormName()+" object|" +form.toString()+"|"+ cse.getMessage()); } session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|search|Success|Success in searching "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); return (mapping.findForward(ForwardConstants.SEARCH_SUCCESS)); }
public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); ActionMessages messages = new ActionMessages(); HttpSession session = request.getSession(); BaseDBForm baseDBForm = (BaseDBForm)form; if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) { if (logDB.isDebugEnabled()) logDB.debug("||"+baseDBForm.getFormName()+"|search|Failure|No Session or User Object Forwarding to the Login Page||"); return mapping.findForward(ForwardConstants.LOGIN_PAGE); } UserInfoHelper.setUserInfo(((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId(), session.getId()); try { SearchResult searchResult = baseDBForm.searchObjects(request,errors,messages); if ( searchResult.getSearchResultObjects() == null || searchResult.getSearchResultObjects().isEmpty()) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, "The search criteria returned zero results")); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|search|Failure|No Records found for "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); baseDBForm.resetForm(); return (mapping.findForward(ForwardConstants.SEARCH_FAILURE)); } if (searchResult.getSearchResultMessage() != null && !(searchResult.getSearchResultMessage().trim().equalsIgnoreCase(""))) { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(DisplayConstants.MESSAGE_ID, searchResult.getSearchResultMessage())); saveMessages( request, messages ); } if(session.getAttribute(DisplayConstants.SEARCH_RESULT)!=null){ if(session.getAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT)==null) session.setAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT, session.getAttribute(DisplayConstants.SEARCH_RESULT) ); } session.setAttribute(DisplayConstants.SEARCH_RESULT, searchResult); } catch (CSException cse) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, cse.getMessage())); saveErrors( request,errors ); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|search|Failure|Error Searching the "+baseDBForm.getFormName()+" object|" +form.toString()+"|"+ cse.getMessage()); } session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm); if (logDB.isDebugEnabled()) logDB.debug(session.getId()+"|"+((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId()+ "|"+baseDBForm.getFormName()+"|search|Success|Success in searching "+baseDBForm.getFormName()+" object|" +form.toString()+"|"); return (mapping.findForward(ForwardConstants.SEARCH_SUCCESS)); }
diff --git a/sventon/src/main/java/org/sventon/web/ctrl/template/GetLatestRevisionsController.java b/sventon/src/main/java/org/sventon/web/ctrl/template/GetLatestRevisionsController.java index 60b78f69..b91af539 100644 --- a/sventon/src/main/java/org/sventon/web/ctrl/template/GetLatestRevisionsController.java +++ b/sventon/src/main/java/org/sventon/web/ctrl/template/GetLatestRevisionsController.java @@ -1,68 +1,68 @@ /* * ==================================================================== * Copyright (c) 2005-2009 sventon project. All rights reserved. * * This software is licensed as described in the file LICENSE, which * you should have received as part of this distribution. The terms * are also available at http://www.sventon.org. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.sventon.web.ctrl.template; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.sventon.model.UserRepositoryContext; import org.sventon.web.command.BaseCommand; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.io.SVNRepository; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Gets the <i>N</i> latest revision details. * * @author [email protected] */ public final class GetLatestRevisionsController extends AbstractTemplateController { /** * {@inheritDoc} */ @SuppressWarnings("unchecked") protected ModelAndView svnHandle(final SVNRepository repository, final BaseCommand command, final long headRevision, final UserRepositoryContext userRepositoryContext, final HttpServletRequest request, final HttpServletResponse response, final BindException exception) throws Exception { final Map<String, Object> model = new HashMap<String, Object>(); final List<SVNLogEntry> revisions = new ArrayList<SVNLogEntry>(); final long revisionCount = userRepositoryContext.getLatestRevisionsDisplayCount(); try { logger.debug("Getting [" + revisionCount + "] latest revisions"); - revisions.addAll(getRepositoryService().getRevisions(command.getName(), repository, -1, FIRST_REVISION, "/", - revisionCount, false)); + revisions.addAll(getRepositoryService().getRevisions(command.getName(), repository, headRevision, FIRST_REVISION, + "/", revisionCount, false)); logger.debug("Got [" + revisions.size() + "] revisions"); } catch (SVNException svnex) { if (SVNErrorCode.FS_NO_SUCH_REVISION == svnex.getErrorMessage().getErrorCode()) { logger.info(svnex.getMessage()); model.put("errorMessage", "There are no commits in this repository yet."); } else { logger.error(svnex.getMessage()); model.put("errorMessage", svnex.getMessage()); } } model.put("revisions", revisions); return new ModelAndView(getViewName(), model); } }
true
true
protected ModelAndView svnHandle(final SVNRepository repository, final BaseCommand command, final long headRevision, final UserRepositoryContext userRepositoryContext, final HttpServletRequest request, final HttpServletResponse response, final BindException exception) throws Exception { final Map<String, Object> model = new HashMap<String, Object>(); final List<SVNLogEntry> revisions = new ArrayList<SVNLogEntry>(); final long revisionCount = userRepositoryContext.getLatestRevisionsDisplayCount(); try { logger.debug("Getting [" + revisionCount + "] latest revisions"); revisions.addAll(getRepositoryService().getRevisions(command.getName(), repository, -1, FIRST_REVISION, "/", revisionCount, false)); logger.debug("Got [" + revisions.size() + "] revisions"); } catch (SVNException svnex) { if (SVNErrorCode.FS_NO_SUCH_REVISION == svnex.getErrorMessage().getErrorCode()) { logger.info(svnex.getMessage()); model.put("errorMessage", "There are no commits in this repository yet."); } else { logger.error(svnex.getMessage()); model.put("errorMessage", svnex.getMessage()); } } model.put("revisions", revisions); return new ModelAndView(getViewName(), model); }
protected ModelAndView svnHandle(final SVNRepository repository, final BaseCommand command, final long headRevision, final UserRepositoryContext userRepositoryContext, final HttpServletRequest request, final HttpServletResponse response, final BindException exception) throws Exception { final Map<String, Object> model = new HashMap<String, Object>(); final List<SVNLogEntry> revisions = new ArrayList<SVNLogEntry>(); final long revisionCount = userRepositoryContext.getLatestRevisionsDisplayCount(); try { logger.debug("Getting [" + revisionCount + "] latest revisions"); revisions.addAll(getRepositoryService().getRevisions(command.getName(), repository, headRevision, FIRST_REVISION, "/", revisionCount, false)); logger.debug("Got [" + revisions.size() + "] revisions"); } catch (SVNException svnex) { if (SVNErrorCode.FS_NO_SUCH_REVISION == svnex.getErrorMessage().getErrorCode()) { logger.info(svnex.getMessage()); model.put("errorMessage", "There are no commits in this repository yet."); } else { logger.error(svnex.getMessage()); model.put("errorMessage", svnex.getMessage()); } } model.put("revisions", revisions); return new ModelAndView(getViewName(), model); }
diff --git a/project/datamart/src/test/java/com/kesho/datamart/repository/StudentsDAOTest.java b/project/datamart/src/test/java/com/kesho/datamart/repository/StudentsDAOTest.java index 144de33..09e09d2 100644 --- a/project/datamart/src/test/java/com/kesho/datamart/repository/StudentsDAOTest.java +++ b/project/datamart/src/test/java/com/kesho/datamart/repository/StudentsDAOTest.java @@ -1,274 +1,273 @@ package com.kesho.datamart.repository; import com.kesho.datamart.dbtest.DatabaseSetupRule; import com.kesho.datamart.domain.CLASS; import com.kesho.datamart.domain.Gender; import com.kesho.datamart.entity.*; import com.kesho.datamart.service.DBUtil; import org.dbunit.dataset.DataSetException; import org.joda.time.LocalDate; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.orm.jpa.JpaObjectRetrievalFailureException; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import javax.inject.Inject; import java.sql.SQLException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; @ContextConfiguration(locations = { "classpath:repository-context.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class StudentsDAOTest { @Rule public final DatabaseSetupRule dbSetup = DatabaseSetupRule.setUpDataFor("kesho", "students-it-data.xml"); @Inject private StudentsDAO repo; @Inject private JpaTransactionManager transactionManager; @Test public void shouldSaveStudent() throws DataSetException, SQLException { LocalDate startDate = LocalDate.now(); Student student = new Student(); student.setFirstName("s1"); Family f = new Family(); f.setId(1L); - f.setName("name"); student.setFamily(f); student.setActive(true); student.setGender(Gender.M); student.setHasDisability(true); student.setHomeLocation("s1home"); student.setContactNumber("12345"); student.setStartDate(startDate); student.setSponsored(true); student.setYearOfBirth(2000); final Student s = repo.save(student); assertNotNull("Student should have an id", s.getId()); TransactionCallback<Student> callback = new TransactionCallback<Student>() { @Override public Student doInTransaction(TransactionStatus status) { return repo.findOne(s.getId()); } }; TransactionTemplate txTemplate = new TransactionTemplate(transactionManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); //TODO: import jpa dialect // txTemplate.setIsolationLevel(Isolation.READ_COMMITTED.value()); Student saved = txTemplate.execute(callback); assertThat(saved.getFirstName(), is("s1")); - assertThat(saved.getFamily().getName(), is("sn1")); + assertThat(saved.getFamily().getName(), is("a")); assertThat(saved.isActive(), is(true)); assertThat(saved.getGender(), is(Gender.M)); assertThat(saved.hasDisability(), is(true)); assertThat(saved.getHomeLocation(), is("s1home")); assertThat(saved.getContactNumber(), is("12345")); assertThat(saved.getStartDate(), is(startDate)); assertThat(saved.isSponsored(), is(true)); assertThat(saved.getYearOfBirth(), is(2000)); assertThat("Expected 1 row", dbSetup.getConnection().createQueryTable("students", String.format("select * from STUDENTS where id=%d", s.getId())).getRowCount(), is(1)); } @Test public void shouldFindStudent() { Student student = repo.findOne(2L); assertNotNull(student); assertThat("Should match first name", student.getFirstName(), is("fn")); } @Test public void shouldDeleteStudent() throws DataSetException, SQLException { repo.delete(2L); assertThat("Expected no rows", dbSetup.getConnection().createQueryTable("students", "select * from STUDENTS where id=2").getRowCount(), is(0)); } //TODO: redo education history tests // @Test // public void shuoldCascadeInsertLog() throws DataSetException, SQLException { // Student student = new Student(); // StudentLog log = new StudentLog(); // log.setComment("test log"); // student.addLog(log); // Student s = repo.save(student); // assertNotNull("Student should have an id", s.getId()); // assertThat("Student should have one log", s.getLogs().size(), is(1)); // assertThat("Expected student log row", dbSetup.getConnection().createQueryTable("STUDENT_LOG", String.format("select * from STUDENT_LOG where student_id=%d", s.getId())).getRowCount(), is(1)); // // Object logComment = dbSetup.getConnection().createQueryTable("student_log", String.format("select * from STUDENT_LOG where student_id=%d", s.getId())).getValue(0, "LOG"); // assertThat("Expected comment", log.getComment(), is(logComment)); // } // @Test // public void shuoldCascadeInsertMultipleLogs() throws DataSetException, SQLException { // Student student = new Student(); // StudentLog log1 = new StudentLog(); // log1.setComment("log1"); // student.addLog(log1); // // StudentLog log2 = new StudentLog(); // log2.setComment("log2"); // student.addLog(log2); // Student s = repo.save(student); // // assertNotNull("Student should have an id", s.getId()); // assertThat("Student should have 2 logs", s.getLogs().size(), is(2)); // // assertThat("Expected student log row", dbSetup.getConnection().createQueryTable("student_log", String.format("select * from STUDENT_LOG where student_id=%d", s.getId())).getRowCount(), is(2)); // } // @Test // public void shouldDeleteLogsOnUpdate() throws DataSetException, SQLException { // Student student = new Student(); // StudentLog log = new StudentLog(); // log.setComment("test log"); // student.addLog(log); // Student s = repo.save(student); // // s.getLogs().remove(0); // s = repo.save(s); // // assertThat("Expected student log row", dbSetup.getConnection().createQueryTable("student_log", String.format("select * from STUDENT_LOG where student_id=%d", s.getId())).getRowCount(), is(0)); // } // // @Test // public void shouldCascadeDeleteLogs() throws DataSetException, SQLException { // Student student = new Student(); // StudentLog log = new StudentLog(); // log.setComment("test log"); // student.addLog(log); // Student s = repo.save(student); // // repo.delete(s.getId()); // // assertThat("Expected student log row", dbSetup.getConnection().createQueryTable("student_log", String.format("select * from STUDENT_LOG where student_id=%d", s.getId())).getRowCount(), is(0)); // } // // @Test // public void shouldCascadeUpdateLog() throws DataSetException, SQLException { // Student student = new Student(); // StudentLog log = new StudentLog(); // log.setComment("test log"); // student.addLog(log); // Student s = repo.save(student); // // s.getLogs().get(0).setComment("new comment"); // s = repo.save(s); // // assertThat("Expected comment", dbSetup.getConnection().createQueryTable("student_log", String.format("select LOG from STUDENT_LOG where student_id=%d", s.getId())).getValue(0, "LOG").toString(), is("new comment")); // } // @Test // public void shouldCascadeInsertEducationHistory() throws DataSetException, SQLException { // Student student = repo.findwithJoin(2L); // School school = new School(); // school.setId(1L); // // EducationHistory eh = new EducationHistory(); // eh.setCurrentClass(CLASS.YEAR1); // eh.setLevel("Level1"); // eh.setPredictedEndDate(LocalDate.now()); // eh.setPredictedEndDate(LocalDate.now().plusYears(1)); // eh.setStudentId(student.getId()); // eh.setSchool(school); // // EducationHistory eh1 = new EducationHistory(); // //eh1.setCurrentClass(CLASS.YEAR2); // eh1.setLevel("Level2"); // //eh1.setPredictedEndDate(LocalDate.now()); // //eh1.setPredictedEndDate(LocalDate.now().plusYears(1)); // eh1.setStudentId(student.getId()); // //eh1.setSchool(school); // // student.addToEducationHistory(eh); // student.addToEducationHistory(eh1); // student = repo.save(student); // // assertThat("Expected EDUCATION_HISTORY", dbSetup.getConnection().createQueryTable("EDUCATION_HISTORY", String.format("select * from EDUCATION_HISTORY where student_id=%d order by level asc", student.getId())).getValue(0, "level").toString(), is("Level1")); // assertThat("Expected EDUCATION_HISTORY", dbSetup.getConnection().createQueryTable("EDUCATION_HISTORY", String.format("select * from EDUCATION_HISTORY where student_id=%d order by level asc", student.getId())).getValue(0, "class").toString(), is(CLASS.YEAR1.name())); // assertThat("Expected EDUCATION_HISTORY", dbSetup.getConnection().createQueryTable("EDUCATION_HISTORY", String.format("select * from EDUCATION_HISTORY where student_id=%d order by level asc", student.getId())).getValue(1, "level").toString(), is("Level2")); // assertThat("Expected EDUCATION_HISTORY", dbSetup.getConnection().createQueryTable("EDUCATION_HISTORY", String.format("select * from EDUCATION_HISTORY where student_id=%d order by level asc", student.getId())).getValue(1, "class").toString(), is(CLASS.YEAR2.name())); // // //assertThat(student.getEducationHistory().iterator().next().getSchool().getFamilyName(), is("school1")); // } // @Test // public void shouldCascadeDeleteEducationHistory() throws DataSetException, SQLException { // Student student = repo.findwithJoin(2L); // School school = new School(); // school.setId(1L); // // EducationHistory eh = new EducationHistory(); // //eh.setCurrentClass(CLASS.YEAR1); // eh.setLevel("Level1"); // //eh.setPredictedEndDate(LocalDate.now()); // //eh.setPredictedEndDate(LocalDate.now().plusYears(1)); // eh.setStudentId(student.getId()); // //eh.setSchool(school); // // student.addToEducationHistory(eh); // student = repo.save(student); // // repo.delete(student); // // assertThat("Expected EDUCATION_HISTORY", dbSetup.getConnection().createQueryTable("EDUCATION_HISTORY", String.format("select * from EDUCATION_HISTORY where student_id=%d", student.getId())).getRowCount(), is(0)); // } // @Test // public void shouldNotCascadeDeleteEducationHistoryToSchool() throws DataSetException, SQLException { // Student student = repo.findwithJoin(2L); // School school = new School(); // school.setId(1L); // // EducationHistory eh = new EducationHistory(); // //eh.setCurrentClass(CLASS.YEAR1); // eh.setLevel("Level1"); // //eh.setPredictedEndDate(LocalDate.now()); // //eh.setPredictedEndDate(LocalDate.now().plusYears(1)); // eh.setStudentId(student.getId()); // //eh.setSchool(school); // student.addToEducationHistory(eh); // student = repo.save(student); // // repo.delete(student); // // assertThat("Expected EDUCATION_HISTORY", dbSetup.getConnection().createQueryTable("EDUCATION_HISTORY", String.format("select * from EDUCATION_HISTORY where student_id=%d", student.getId())).getRowCount(), is(0)); // assertThat("Expected EDUCATION_HISTORY", dbSetup.getConnection().createTable("SCHOOLS").getRowCount(), is(1)); // // } // @Test(expected = JpaObjectRetrievalFailureException.class) // public void shouldNotCascadeInsertEducationHistoryToSchool() throws DataSetException, SQLException { // Student student = repo.findwithJoin(2L); // School school = new School(); // school.setId(Long.MAX_VALUE); // // EducationHistory eh = new EducationHistory(); // //eh.setCurrentClass(CLASS.YEAR1); // eh.setLevel("Level1"); // //eh.setPredictedEndDate(LocalDate.now()); // //eh.setPredictedEndDate(LocalDate.now().plusYears(1)); // //eh.setSchool(school); // student.addToEducationHistory(eh); // student = repo.save(student); // } }
false
true
public void shouldSaveStudent() throws DataSetException, SQLException { LocalDate startDate = LocalDate.now(); Student student = new Student(); student.setFirstName("s1"); Family f = new Family(); f.setId(1L); f.setName("name"); student.setFamily(f); student.setActive(true); student.setGender(Gender.M); student.setHasDisability(true); student.setHomeLocation("s1home"); student.setContactNumber("12345"); student.setStartDate(startDate); student.setSponsored(true); student.setYearOfBirth(2000); final Student s = repo.save(student); assertNotNull("Student should have an id", s.getId()); TransactionCallback<Student> callback = new TransactionCallback<Student>() { @Override public Student doInTransaction(TransactionStatus status) { return repo.findOne(s.getId()); } }; TransactionTemplate txTemplate = new TransactionTemplate(transactionManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); //TODO: import jpa dialect // txTemplate.setIsolationLevel(Isolation.READ_COMMITTED.value()); Student saved = txTemplate.execute(callback); assertThat(saved.getFirstName(), is("s1")); assertThat(saved.getFamily().getName(), is("sn1")); assertThat(saved.isActive(), is(true)); assertThat(saved.getGender(), is(Gender.M)); assertThat(saved.hasDisability(), is(true)); assertThat(saved.getHomeLocation(), is("s1home")); assertThat(saved.getContactNumber(), is("12345")); assertThat(saved.getStartDate(), is(startDate)); assertThat(saved.isSponsored(), is(true)); assertThat(saved.getYearOfBirth(), is(2000)); assertThat("Expected 1 row", dbSetup.getConnection().createQueryTable("students", String.format("select * from STUDENTS where id=%d", s.getId())).getRowCount(), is(1)); }
public void shouldSaveStudent() throws DataSetException, SQLException { LocalDate startDate = LocalDate.now(); Student student = new Student(); student.setFirstName("s1"); Family f = new Family(); f.setId(1L); student.setFamily(f); student.setActive(true); student.setGender(Gender.M); student.setHasDisability(true); student.setHomeLocation("s1home"); student.setContactNumber("12345"); student.setStartDate(startDate); student.setSponsored(true); student.setYearOfBirth(2000); final Student s = repo.save(student); assertNotNull("Student should have an id", s.getId()); TransactionCallback<Student> callback = new TransactionCallback<Student>() { @Override public Student doInTransaction(TransactionStatus status) { return repo.findOne(s.getId()); } }; TransactionTemplate txTemplate = new TransactionTemplate(transactionManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); //TODO: import jpa dialect // txTemplate.setIsolationLevel(Isolation.READ_COMMITTED.value()); Student saved = txTemplate.execute(callback); assertThat(saved.getFirstName(), is("s1")); assertThat(saved.getFamily().getName(), is("a")); assertThat(saved.isActive(), is(true)); assertThat(saved.getGender(), is(Gender.M)); assertThat(saved.hasDisability(), is(true)); assertThat(saved.getHomeLocation(), is("s1home")); assertThat(saved.getContactNumber(), is("12345")); assertThat(saved.getStartDate(), is(startDate)); assertThat(saved.isSponsored(), is(true)); assertThat(saved.getYearOfBirth(), is(2000)); assertThat("Expected 1 row", dbSetup.getConnection().createQueryTable("students", String.format("select * from STUDENTS where id=%d", s.getId())).getRowCount(), is(1)); }
diff --git a/datastore/src/test/java/org/jboss/test/capedwarf/datastore/test/AllocateIdsTestCase.java b/datastore/src/test/java/org/jboss/test/capedwarf/datastore/test/AllocateIdsTestCase.java index ff07bbd1..8ad98ad4 100644 --- a/datastore/src/test/java/org/jboss/test/capedwarf/datastore/test/AllocateIdsTestCase.java +++ b/datastore/src/test/java/org/jboss/test/capedwarf/datastore/test/AllocateIdsTestCase.java @@ -1,77 +1,78 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.capedwarf.datastore.test; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyRange; import org.jboss.arquillian.junit.Arquillian; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author <a href="mailto:[email protected]">Ales Justin</a> */ @RunWith(Arquillian.class) public class AllocateIdsTestCase extends AbstractTest { @Test public void testAllocateId() throws Exception { long initialValue = getInitialValue("SomeKind"); KeyRange keys = service.allocateIds("SomeKind", 10L); Assert.assertNotNull(keys); Key start = keys.getStart(); Assert.assertNotNull(start); Assert.assertEquals(1 + initialValue, start.getId()); Key end = keys.getEnd(); Assert.assertNotNull(end); Assert.assertEquals(10 + initialValue, end.getId()); } @Test public void testCheckKeyRange() throws Exception { long initialValue = getInitialValue("OtherKind"); KeyRange kr1 = new KeyRange(null, "OtherKind", 1 + initialValue, 5 + initialValue); DatastoreService.KeyRangeState state1 = service.allocateIdRange(kr1); Assert.assertNotNull(state1); // imo, it could be either -- depending on the impl Assert.assertTrue(DatastoreService.KeyRangeState.CONTENTION == state1 || DatastoreService.KeyRangeState.EMPTY == state1); KeyRange kr2 = service.allocateIds("OtherKind", 6); Assert.assertNotNull(kr2); KeyRange kr3 = new KeyRange(null, "OtherKind", 2 + initialValue, 5 + initialValue); DatastoreService.KeyRangeState state2 = service.allocateIdRange(kr3); Assert.assertNotNull(state2); - Assert.assertSame(DatastoreService.KeyRangeState.COLLISION, state2); + // can it be both, depending on the impl? + Assert.assertTrue(DatastoreService.KeyRangeState.COLLISION == state2 || DatastoreService.KeyRangeState.CONTENTION == state2); } private long getInitialValue(String kind) { return service.allocateIds(kind, 1L).getStart().getId(); } }
true
true
public void testCheckKeyRange() throws Exception { long initialValue = getInitialValue("OtherKind"); KeyRange kr1 = new KeyRange(null, "OtherKind", 1 + initialValue, 5 + initialValue); DatastoreService.KeyRangeState state1 = service.allocateIdRange(kr1); Assert.assertNotNull(state1); // imo, it could be either -- depending on the impl Assert.assertTrue(DatastoreService.KeyRangeState.CONTENTION == state1 || DatastoreService.KeyRangeState.EMPTY == state1); KeyRange kr2 = service.allocateIds("OtherKind", 6); Assert.assertNotNull(kr2); KeyRange kr3 = new KeyRange(null, "OtherKind", 2 + initialValue, 5 + initialValue); DatastoreService.KeyRangeState state2 = service.allocateIdRange(kr3); Assert.assertNotNull(state2); Assert.assertSame(DatastoreService.KeyRangeState.COLLISION, state2); }
public void testCheckKeyRange() throws Exception { long initialValue = getInitialValue("OtherKind"); KeyRange kr1 = new KeyRange(null, "OtherKind", 1 + initialValue, 5 + initialValue); DatastoreService.KeyRangeState state1 = service.allocateIdRange(kr1); Assert.assertNotNull(state1); // imo, it could be either -- depending on the impl Assert.assertTrue(DatastoreService.KeyRangeState.CONTENTION == state1 || DatastoreService.KeyRangeState.EMPTY == state1); KeyRange kr2 = service.allocateIds("OtherKind", 6); Assert.assertNotNull(kr2); KeyRange kr3 = new KeyRange(null, "OtherKind", 2 + initialValue, 5 + initialValue); DatastoreService.KeyRangeState state2 = service.allocateIdRange(kr3); Assert.assertNotNull(state2); // can it be both, depending on the impl? Assert.assertTrue(DatastoreService.KeyRangeState.COLLISION == state2 || DatastoreService.KeyRangeState.CONTENTION == state2); }
diff --git a/WEB-INF/src/org/cdlib/xtf/util/DiskHashReader.java b/WEB-INF/src/org/cdlib/xtf/util/DiskHashReader.java index 55d21c87..76603b09 100644 --- a/WEB-INF/src/org/cdlib/xtf/util/DiskHashReader.java +++ b/WEB-INF/src/org/cdlib/xtf/util/DiskHashReader.java @@ -1,142 +1,142 @@ package org.cdlib.xtf.util; /** * Copyright (c) 2004, Regents of the University of California * 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 University of California nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import java.io.IOException; /** * Provides quick access to a disk-based hash table created by * a {@link DiskHashWriter}. * * @author Martin Haye */ public class DiskHashReader { /** Size of the header we expect to find */ static final int headerSize = 12; /** Subfile to read the hash from */ private Subfile subfile; /** Number of hash slots in the subfile */ private int nSlots; /** Size of each hash slot */ private int slotSize; /** Buffer used to read hash slot bytes */ private byte[] slotBytes; /** Used to decode hash slot values */ private PackedByteBuf slotBuf; /** * Read in the header of of the hash from the given subfile. * * @param subfile Must have been created by DiskHashWriter.outputTo() */ public DiskHashReader( Subfile subfile ) throws IOException { this.subfile = subfile; // Read the header. byte[] magic = new byte[4]; subfile.read( magic ); if( magic[0] != 'h' || magic[1] != 'a' || magic[2] != 's' || magic[3] != 'h' ) throw new IOException( "Subfile isn't a proper DiskHash" ); nSlots = subfile.readInt(); slotSize = subfile.readInt(); // Allocate the slot buffer. slotBytes = new byte[slotSize]; slotBuf = new PackedByteBuf( slotBytes ); } // constructor /** * Closes the reader (and its associated subfile). */ public void close() { try { subfile.close(); } catch( Exception e ) { } subfile = null; } // close() /** * Locate the entry for the given string key. If not found, returns null. * @param key key to look for */ public PackedByteBuf find( String key ) throws IOException { // Don't allow empty string as a key, since it's used to mark // the end of a slot. // if( key.length() == 0 ) key = " "; // Find the location of the slot data. If zero, we can fail now. int slotNum = (key.hashCode() & 0xffffff) % nSlots; subfile.seek( headerSize + (slotNum * 4) ); int slotOffset = subfile.readInt(); if( slotOffset == 0 ) return null; assert (slotOffset+slotSize) <= subfile.length() : "Corrupt hash offset"; // Read the slot data (may be too much, but will always be enough). subfile.seek( slotOffset ); subfile.readFully( slotBytes ); - slotBuf.reset(); + slotBuf.setBytes( slotBytes ); // Now scan the entries while( true ) { // Get the name. If empty, give up. String name = slotBuf.readString(); if( name.length() == 0 ) return null; // Does it match? If not, advance to the next slot. if( !name.equals(key) ) { slotBuf.skipBuffer(); continue; } // Got a match! return slotBuf.readBuffer(); } // while } // find() } // class DiskHashReader
true
true
public PackedByteBuf find( String key ) throws IOException { // Don't allow empty string as a key, since it's used to mark // the end of a slot. // if( key.length() == 0 ) key = " "; // Find the location of the slot data. If zero, we can fail now. int slotNum = (key.hashCode() & 0xffffff) % nSlots; subfile.seek( headerSize + (slotNum * 4) ); int slotOffset = subfile.readInt(); if( slotOffset == 0 ) return null; assert (slotOffset+slotSize) <= subfile.length() : "Corrupt hash offset"; // Read the slot data (may be too much, but will always be enough). subfile.seek( slotOffset ); subfile.readFully( slotBytes ); slotBuf.reset(); // Now scan the entries while( true ) { // Get the name. If empty, give up. String name = slotBuf.readString(); if( name.length() == 0 ) return null; // Does it match? If not, advance to the next slot. if( !name.equals(key) ) { slotBuf.skipBuffer(); continue; } // Got a match! return slotBuf.readBuffer(); } // while } // find()
public PackedByteBuf find( String key ) throws IOException { // Don't allow empty string as a key, since it's used to mark // the end of a slot. // if( key.length() == 0 ) key = " "; // Find the location of the slot data. If zero, we can fail now. int slotNum = (key.hashCode() & 0xffffff) % nSlots; subfile.seek( headerSize + (slotNum * 4) ); int slotOffset = subfile.readInt(); if( slotOffset == 0 ) return null; assert (slotOffset+slotSize) <= subfile.length() : "Corrupt hash offset"; // Read the slot data (may be too much, but will always be enough). subfile.seek( slotOffset ); subfile.readFully( slotBytes ); slotBuf.setBytes( slotBytes ); // Now scan the entries while( true ) { // Get the name. If empty, give up. String name = slotBuf.readString(); if( name.length() == 0 ) return null; // Does it match? If not, advance to the next slot. if( !name.equals(key) ) { slotBuf.skipBuffer(); continue; } // Got a match! return slotBuf.readBuffer(); } // while } // find()
diff --git a/Stimpack/Stimpack-war/src/java/beans/UserManager.java b/Stimpack/Stimpack-war/src/java/beans/UserManager.java index faca410..80c3e59 100644 --- a/Stimpack/Stimpack-war/src/java/beans/UserManager.java +++ b/Stimpack/Stimpack-war/src/java/beans/UserManager.java @@ -1,86 +1,86 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package beans; import ejb.Student; import ejb.Teacher; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; /** * * @author Rowan */ @ManagedBean @SessionScoped public class UserManager { private Student student; private Teacher teacher; public UserManager() { } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public boolean loggedIn() { if (student != null || teacher != null) { return true; } return false; } public void logout() { student = null; teacher = null; } public String getUsername() { if (isStudent()) - return getClass().getUsername(); + return student.getUsername(); else if (isTeacher()) return teacher.getUsername(); return null; } // Return "Student", "Teacher" or "Administrator" public String getType() { return getUser().getClass().getSimpleName(); } public Object getUser() { if (student != null) return student; if (teacher != null) return teacher; return null; } public boolean isStudent() { if (getUser() instanceof Student) return true; return false; } public boolean isTeacher() { if (getUser() instanceof Teacher) return true; return false; } }
true
true
public String getUsername() { if (isStudent()) return getClass().getUsername(); else if (isTeacher()) return teacher.getUsername(); return null; }
public String getUsername() { if (isStudent()) return student.getUsername(); else if (isTeacher()) return teacher.getUsername(); return null; }
diff --git a/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/data/RequestScope.java b/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/data/RequestScope.java index a67cd96e6..20fe89636 100644 --- a/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/data/RequestScope.java +++ b/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/data/RequestScope.java @@ -1,179 +1,181 @@ /******************************************************************************* * Copyright (c) 2010 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.help.internal.webapp.data; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.help.HelpSystem; import org.eclipse.help.base.AbstractHelpScope; import org.eclipse.help.internal.base.HelpBasePlugin; import org.eclipse.help.internal.base.HelpBaseResources; import org.eclipse.help.internal.base.IHelpBaseConstants; import org.eclipse.help.internal.base.scope.FilterScope; import org.eclipse.help.internal.base.scope.IntersectionScope; import org.eclipse.help.internal.base.scope.ScopeRegistry; import org.eclipse.help.internal.base.scope.UniversalScope; import org.eclipse.help.internal.base.scope.WorkingSetScope; import org.eclipse.help.internal.webapp.servlet.WebappWorkingSetManager; import org.osgi.service.prefs.BackingStoreException; public class RequestScope { private static final String SCOPE_PARAMETER_NAME = "scope"; //$NON-NLS-1$ private static final String SCOPE_COOKIE_NAME = "filter"; //$NON-NLS-1$ /** * Gets a scope object based upon the preferences and request * @param isSearchFilter is true if this filter will be used to filter search results. * Search results are already filtered by search scope and if this parameter is true search * scopes will not be considered * @return */ public static AbstractHelpScope getScope(HttpServletRequest req, HttpServletResponse resp, boolean isSearchFilter ) { AbstractHelpScope[] scopeArray; scopeArray = getActiveScopes(req, resp, isSearchFilter); switch (scopeArray.length) { case 0: return new UniversalScope(); case 1: return scopeArray[0]; default: return new IntersectionScope( scopeArray); } } public static AbstractHelpScope[] getActiveScopes(HttpServletRequest req, HttpServletResponse resp, boolean isSearchFilter) { AbstractHelpScope[] scopeArray; String scopeString; List scopes = new ArrayList(); if (!HelpSystem.isShared()) { scopes.add(new FilterScope()); // Workbench is always filtered } scopeString = getScopeString(req); if (scopeString != null) { StringTokenizer tokenizer = new StringTokenizer(scopeString, "/"); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { String nextScope = tokenizer.nextToken().trim(); AbstractHelpScope scope = ScopeRegistry.getInstance().getScope(nextScope); if (scope != null) { scopes.add(scope); } } } // Add filter by search scope if (!isSearchFilter) { // Try for a working set try { WebappWorkingSetManager manager = new WebappWorkingSetManager(req, resp, UrlUtil.getLocale(req, resp)); String wset = manager.getCurrentWorkingSet(); - WorkingSetScope workingSetScope = new WorkingSetScope( - wset, manager, HelpBaseResources.SearchScopeFilterName); - scopes.add(workingSetScope); + if (wset != null && wset.length() > 0) { + WorkingSetScope workingSetScope = new WorkingSetScope(wset, + manager, HelpBaseResources.SearchScopeFilterName); + scopes.add(workingSetScope); + } } catch (Exception e) { } } scopeArray = (AbstractHelpScope[]) scopes.toArray(new AbstractHelpScope[scopes.size()]); return scopeArray; } private static String getScopeString(HttpServletRequest req) { String scopeString; if (HelpSystem.isShared()) { scopeString = getScopeFromCookies(req); } else { scopeString = getScopeFromPreferences(); if (scopeString == null) { scopeString = ScopeRegistry.ENABLEMENT_SCOPE_ID; } } return scopeString; } public static String getFilterButtonState() { boolean scope = Platform.getPreferencesService().getBoolean (HelpBasePlugin.PLUGIN_ID, IHelpBaseConstants.P_KEY_FILTER_DIALOG, false, null); if (scope && ScopeRegistry.getInstance().getScopes().length > 0) { return "off"; //$NON-NLS-1$ } return "hidden"; //$NON-NLS-1$ } public static void setScopeFromRequest(HttpServletRequest request, HttpServletResponse response) { // See if there is a scope parameter, if so save as cookie or preference String[] scope = request.getParameterValues(SCOPE_PARAMETER_NAME); String scopeString = null; // save scope (in session cookie) for later use in a user session // If there are multiple values separate them with a '/' if (scope != null) { scopeString = scope[0]; for (int s = 1; s < scope.length; s++) { scopeString += '/'; scopeString += scope[s]; } saveScope(scopeString, response); } } public static void saveScope(String scope, HttpServletResponse response) { if (HelpSystem.isShared()) { if (response != null) { Cookie scopeCookie = new Cookie(SCOPE_COOKIE_NAME, scope); response.addCookie(scopeCookie); } } else { InstanceScope instanceScope = new InstanceScope(); IEclipsePreferences pref = instanceScope.getNode(HelpBasePlugin.PLUGIN_ID); pref.put(IHelpBaseConstants.P_KEY_HELP_SCOPE, scope); try { pref.flush(); } catch (BackingStoreException e) { } } } private static String getScopeFromCookies(HttpServletRequest request) { // check if scope was passed earlier in this session Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int c = 0; c < cookies.length; c++) { if (SCOPE_COOKIE_NAME.equals(cookies[c].getName())) { return cookies[c].getValue(); } } } return null; } private static String getScopeFromPreferences() { String scope = Platform.getPreferencesService().getString (HelpBasePlugin.PLUGIN_ID, IHelpBaseConstants.P_KEY_HELP_SCOPE, null, null); return scope; } public static boolean filterBySearchScope(HttpServletRequest request) { return true; } }
true
true
public static AbstractHelpScope[] getActiveScopes(HttpServletRequest req, HttpServletResponse resp, boolean isSearchFilter) { AbstractHelpScope[] scopeArray; String scopeString; List scopes = new ArrayList(); if (!HelpSystem.isShared()) { scopes.add(new FilterScope()); // Workbench is always filtered } scopeString = getScopeString(req); if (scopeString != null) { StringTokenizer tokenizer = new StringTokenizer(scopeString, "/"); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { String nextScope = tokenizer.nextToken().trim(); AbstractHelpScope scope = ScopeRegistry.getInstance().getScope(nextScope); if (scope != null) { scopes.add(scope); } } } // Add filter by search scope if (!isSearchFilter) { // Try for a working set try { WebappWorkingSetManager manager = new WebappWorkingSetManager(req, resp, UrlUtil.getLocale(req, resp)); String wset = manager.getCurrentWorkingSet(); WorkingSetScope workingSetScope = new WorkingSetScope( wset, manager, HelpBaseResources.SearchScopeFilterName); scopes.add(workingSetScope); } catch (Exception e) { } } scopeArray = (AbstractHelpScope[]) scopes.toArray(new AbstractHelpScope[scopes.size()]); return scopeArray; }
public static AbstractHelpScope[] getActiveScopes(HttpServletRequest req, HttpServletResponse resp, boolean isSearchFilter) { AbstractHelpScope[] scopeArray; String scopeString; List scopes = new ArrayList(); if (!HelpSystem.isShared()) { scopes.add(new FilterScope()); // Workbench is always filtered } scopeString = getScopeString(req); if (scopeString != null) { StringTokenizer tokenizer = new StringTokenizer(scopeString, "/"); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { String nextScope = tokenizer.nextToken().trim(); AbstractHelpScope scope = ScopeRegistry.getInstance().getScope(nextScope); if (scope != null) { scopes.add(scope); } } } // Add filter by search scope if (!isSearchFilter) { // Try for a working set try { WebappWorkingSetManager manager = new WebappWorkingSetManager(req, resp, UrlUtil.getLocale(req, resp)); String wset = manager.getCurrentWorkingSet(); if (wset != null && wset.length() > 0) { WorkingSetScope workingSetScope = new WorkingSetScope(wset, manager, HelpBaseResources.SearchScopeFilterName); scopes.add(workingSetScope); } } catch (Exception e) { } } scopeArray = (AbstractHelpScope[]) scopes.toArray(new AbstractHelpScope[scopes.size()]); return scopeArray; }
diff --git a/src/java/org/infoglue/deliver/applications/actions/ViewPageAction.java b/src/java/org/infoglue/deliver/applications/actions/ViewPageAction.java index c695b93a5..2844884f8 100755 --- a/src/java/org/infoglue/deliver/applications/actions/ViewPageAction.java +++ b/src/java/org/infoglue/deliver/applications/actions/ViewPageAction.java @@ -1,631 +1,631 @@ /* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2, as published by the * Free Software Foundation. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple * Place, Suite 330 / Boston, MA 02111-1307 / USA. * * =============================================================================== */ package org.infoglue.deliver.applications.actions; import org.exolab.castor.jdo.Database; import org.infoglue.cms.applications.common.actions.InfoGlueAbstractAction; import org.infoglue.cms.applications.common.actions.WebworkAbstractAction; import org.infoglue.deliver.applications.databeans.DatabaseWrapper; import org.infoglue.deliver.applications.databeans.DeliveryContext; import org.infoglue.deliver.controllers.kernel.impl.simple.*; import org.infoglue.deliver.invokers.ComponentBasedHTMLPageInvoker; import org.infoglue.deliver.invokers.DecoratedComponentBasedHTMLPageInvoker; import org.infoglue.deliver.invokers.HTMLPageInvoker; import org.infoglue.deliver.invokers.PageInvoker; import org.infoglue.deliver.portal.PortalService; import org.infoglue.deliver.services.StatisticsService; import org.infoglue.deliver.util.BrowserBean; import org.infoglue.deliver.util.CacheController; import org.infoglue.cms.controllers.kernel.impl.simple.AccessRightController; import org.infoglue.cms.controllers.kernel.impl.simple.CastorDatabaseService; import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeController; import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeTypeDefinitionController; import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeVersionControllerProxy; import org.infoglue.cms.security.InfoGluePrincipal; import org.infoglue.cms.services.*; import org.infoglue.cms.util.*; import org.infoglue.cms.exception.*; import org.infoglue.cms.entities.structure.SiteNode; import org.infoglue.cms.entities.structure.SiteNodeVO; import org.infoglue.cms.entities.structure.SiteNodeVersionVO; import org.infoglue.cms.entities.management.LanguageVO; import org.infoglue.cms.entities.management.RepositoryVO; import org.infoglue.cms.entities.management.SiteNodeTypeDefinitionVO; import java.net.URLEncoder; import java.security.Principal; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; /** * This is the main delivery action. Gets called when the user clicks on a link that goes inside the site. * * @author Mattias Bogeblad */ public class ViewPageAction extends InfoGlueAbstractAction { //These are the standard parameters which uniquely defines which page to show. private Integer siteNodeId = null; private Integer contentId = null; private Integer languageId = null; private boolean showSimple = false; //This parameter are set if you want to access a certain repository startpage private String repositoryName = null; //A cached nodeDeliveryController protected NodeDeliveryController nodeDeliveryController = null; protected IntegrationDeliveryController integrationDeliveryController = null; protected TemplateController templateController = null; private static final boolean USE_LANGUAGE_FALLBACK = true; private static final boolean DO_NOT_USE_LANGUAGE_FALLBACK = false; //The browserbean private BrowserBean browserBean = null; private Principal principal = null; //A possibility to set the referer address private String referer = null; public static long contentVersionTime = 0; public static long serviceBindingTime = 0; public static long contentAttributeTime = 0; public static long boundContentTime = 0; public static long inheritedServiceBindingTime = 0; public static long selectMatchingEntitiesTime = 0; public static long isValidTime = 0; public static long qualifyersTime = 0; public static long sortQualifyersTime = 0; public static long commitTime = 0; public static long rollbackTime = 0; public static long closeTime = 0; /** * The constructor for this action - contains nothing right now. */ public ViewPageAction() { } /** * This method is the application entry-point. The parameters has been set through the setters * and now we just have to render the appropriate output. */ public String doExecute() throws Exception { //CacheController.evictWaitingCache(); long start = new Date().getTime(); long elapsedTime = 0; CmsLogger.logInfo("************************************************"); CmsLogger.logInfo("* ViewPageAction was called.... *"); CmsLogger.logInfo("************************************************"); DatabaseWrapper dbWrapper = new DatabaseWrapper(CastorDatabaseService.getDatabase()); //Database db = CastorDatabaseService.getDatabase(); beginTransaction(dbWrapper.getDatabase()); try { validateAndModifyInputParameters(dbWrapper.getDatabase()); String pageKey = "" + this.siteNodeId + "_" + this.languageId + "_" + this.contentId + "_" + browserBean.getUseragent(); CmsLogger.logInfo("pageKey:" + pageKey); String pagePath = null; this.nodeDeliveryController = NodeDeliveryController.getNodeDeliveryController(this.siteNodeId, this.languageId, this.contentId); this.integrationDeliveryController = IntegrationDeliveryController.getIntegrationDeliveryController(this.siteNodeId, this.languageId, this.contentId); this.templateController = getTemplateController(dbWrapper, getSiteNodeId(), getLanguageId(), getContentId(), getRequest(), (InfoGluePrincipal)this.principal); boolean isUserRedirected = false; Integer protectedSiteNodeVersionId = this.nodeDeliveryController.getProtectedSiteNodeVersionId(dbWrapper.getDatabase(), siteNodeId); CmsLogger.logInfo("protectedSiteNodeVersionId:" + protectedSiteNodeVersionId); if(protectedSiteNodeVersionId != null) isUserRedirected = handleExtranetLogic(dbWrapper.getDatabase(), protectedSiteNodeVersionId); CmsLogger.logInfo("handled extranet users"); // ---- // -- portlet // ---- // -- check if the portal is active String portalEnabled = CmsPropertyHandler.getProperty("enablePortal") ; boolean portalActive = ((portalEnabled != null) && portalEnabled.equals("true")); if (portalActive) { CmsLogger.logInfo("---> Checking for portlet action"); PortalService service = new PortalService(); //TODO: catch PortalException? boolean actionExecuted = service.service(getRequest(), getResponse()); // -- if an action was executed return NONE as a redirect is issued if (actionExecuted) { CmsLogger.logInfo("---> PortletAction was executed, returning NONE as a redirect has been issued"); //TODO: maybe statistics service should run here CmsLogger.logWarning("No statistics have been run for this request"); return NONE; } } CmsLogger.logInfo("handled portal action"); if(!isUserRedirected) { CmsLogger.logInfo("this.templateController.getPrincipal():" + this.templateController.getPrincipal()); DeliveryContext deliveryContext = DeliveryContext.getDeliveryContext(/*(InfoGluePrincipal)this.principal*/); deliveryContext.setRepositoryName(this.repositoryName); deliveryContext.setSiteNodeId(this.siteNodeId); deliveryContext.setContentId(this.contentId); deliveryContext.setLanguageId(this.languageId); deliveryContext.setPageKey(pageKey); deliveryContext.setSession(this.getSession()); deliveryContext.setWebworkAbstractAction(this); deliveryContext.setHttpServletRequest(this.getRequest()); deliveryContext.setHttpServletResponse(this.getResponse()); SiteNode siteNode = nodeDeliveryController.getSiteNode(dbWrapper.getDatabase(), this.siteNodeId); if(siteNode == null) throw new SystemException("There was no page with this id."); - String invokerClassName = siteNode.getSiteNodeTypeDefinition().getInvokerClassName(); - if(invokerClassName == null && invokerClassName.equals("")) + if(siteNode.getSiteNodeTypeDefinition() == null || siteNode.getSiteNodeTypeDefinition().getInvokerClassName() == null || siteNode.getSiteNodeTypeDefinition().getInvokerClassName().equals("")) { - throw new SystemException("There was no page invoker class assigned to this page type."); + throw new SystemException("There was no page invoker class assigned to the site node " + siteNode.getName()); } else { try { + String invokerClassName = siteNode.getSiteNodeTypeDefinition().getInvokerClassName(); PageInvoker pageInvoker = (PageInvoker)Class.forName(invokerClassName).newInstance(); pageInvoker.setParameters(dbWrapper, this.getRequest(), this.getResponse(), this.templateController, deliveryContext); pageInvoker.deliverPage(); } catch(ClassNotFoundException e) { throw new SystemException("An error was thrown when trying to use the page invoker class assigned to this page type:" + e.getMessage(), e); } } } elapsedTime = new Date().getTime() - start; CmsLogger.logWarning("The page delivery took " + elapsedTime + "ms"); //CmsLogger.logWarning("Of that is " + contentAttributeTime + "ms from contentAttribute fetching..."); //CmsLogger.logWarning("and " + contentVersionTime + "ms from contentVersion fetching..."); //CmsLogger.logWarning("and " + serviceBindingTime + "ms from serviceBinding fetching..."); //CmsLogger.logWarning("and " + boundContentTime + "ms from boundContent fetching..."); //CmsLogger.logWarning("and " + inheritedServiceBindingTime + "ms from inheritedServiceBindingTime fetching..."); //CmsLogger.logWarning("and " + selectMatchingEntitiesTime + "ms from selectMatchingEntities fetching..."); //CmsLogger.logWarning("and " + isValidTime + "ms from isValidTime fetching..."); //CmsLogger.logWarning("and " + qualifyersTime + "ms from qualifyers fetching..."); //CmsLogger.logWarning("and " + sortQualifyersTime + "ms from sortQualifyers fetching..."); //CmsLogger.logWarning("and " + commitTime + "ms from commitTime fetching..."); //CmsLogger.logWarning("and " + rollbackTime + "ms from rollbackTime fetching..."); //CmsLogger.logWarning("and " + closeTime + "ms from closeTime fetching..."); contentAttributeTime = 0; contentVersionTime = 0; serviceBindingTime = 0; boundContentTime = 0; inheritedServiceBindingTime = 0; selectMatchingEntitiesTime = 0; isValidTime = 0; qualifyersTime = 0; sortQualifyersTime = 0; commitTime = 0; rollbackTime = 0; closeTime = 0; CmsLogger.logWarning("The memory consumption was " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + "(" + Runtime.getRuntime().totalMemory() + "/" + Runtime.getRuntime().maxMemory() + ") bytes"); StatisticsService.getStatisticsService().registerRequest(getRequest(), getResponse(), pagePath, elapsedTime); closeTransaction(dbWrapper.getDatabase()); } catch(Exception e) { CmsLogger.logSevere("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(dbWrapper.getDatabase()); throw new SystemException(e.getMessage()); } return NONE; } /** * This method the renderer for the component editor. */ public String doRenderDecoratedPage() throws Exception { long start = new Date().getTime(); long elapsedTime = 0; CmsLogger.logInfo("************************************************"); CmsLogger.logInfo("* ViewPageAction was called.... *"); CmsLogger.logInfo("************************************************"); DatabaseWrapper dbWrapper = new DatabaseWrapper(CastorDatabaseService.getDatabase()); //Database db = CastorDatabaseService.getDatabase(); beginTransaction(dbWrapper.getDatabase()); try { validateAndModifyInputParameters(dbWrapper.getDatabase()); String pageKey = "" + this.siteNodeId + "_" + this.languageId + "_" + this.contentId + "_" + browserBean.getUseragent() + "_" + this.showSimple + "_pagecomponentDecorated"; CmsLogger.logInfo("A pageKey:" + pageKey); String pagePath = null; this.nodeDeliveryController = NodeDeliveryController.getNodeDeliveryController(this.siteNodeId, this.languageId, this.contentId); this.integrationDeliveryController = IntegrationDeliveryController.getIntegrationDeliveryController(this.siteNodeId, this.languageId, this.contentId); this.templateController = getTemplateController(dbWrapper, getSiteNodeId(), getLanguageId(), getContentId(), getRequest(), (InfoGluePrincipal)this.principal); boolean isUserRedirected = false; Integer protectedSiteNodeVersionId = this.nodeDeliveryController.getProtectedSiteNodeVersionId(dbWrapper.getDatabase(), siteNodeId); CmsLogger.logInfo("protectedSiteNodeVersionId:" + protectedSiteNodeVersionId); if(protectedSiteNodeVersionId != null) isUserRedirected = handleExtranetLogic(dbWrapper.getDatabase(), protectedSiteNodeVersionId); CmsLogger.logInfo("handled extranet users"); if(!isUserRedirected) { CmsLogger.logInfo("this.templateController.getPrincipal():" + this.templateController.getPrincipal()); DeliveryContext deliveryContext = DeliveryContext.getDeliveryContext(/*this.templateController.getPrincipal()*/); deliveryContext.setRepositoryName(this.repositoryName); deliveryContext.setSiteNodeId(this.siteNodeId); deliveryContext.setLanguageId(this.languageId); deliveryContext.setContentId(this.contentId); deliveryContext.setShowSimple(this.showSimple); deliveryContext.setPageKey(pageKey); deliveryContext.setSession(this.getSession()); deliveryContext.setWebworkAbstractAction(this); deliveryContext.setHttpServletRequest(this.getRequest()); deliveryContext.setHttpServletResponse(this.getResponse()); SiteNode siteNode = nodeDeliveryController.getSiteNode(dbWrapper.getDatabase(), this.siteNodeId); if(siteNode == null) throw new SystemException("There was no page with this id."); String invokerClassName = siteNode.getSiteNodeTypeDefinition().getInvokerClassName(); if(invokerClassName == null && invokerClassName.equals("")) { throw new SystemException("There was no page invoker class assigned to this page type."); } else { try { PageInvoker pageInvoker = (PageInvoker)Class.forName(invokerClassName).newInstance(); pageInvoker = pageInvoker.getDecoratedPageInvoker(); pageInvoker.setParameters(dbWrapper, this.getRequest(), this.getResponse(), this.templateController, deliveryContext); pageInvoker.deliverPage(); } catch(ClassNotFoundException e) { throw new SystemException("An error was thrown when trying to use the page invoker class assigned to this page type:" + e.getMessage(), e); } } } elapsedTime = new Date().getTime() - start; CmsLogger.logWarning("The page delivery took " + elapsedTime + "ms"); StatisticsService.getStatisticsService().registerRequest(getRequest(), getResponse(), pagePath, elapsedTime); closeTransaction(dbWrapper.getDatabase()); } catch(Exception e) { CmsLogger.logSevere("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(dbWrapper.getDatabase()); throw new SystemException(e.getMessage()); } return NONE; } /** * This method should be much more sophisticated later and include a check to see if there is a * digital asset uploaded which is more specialized and can be used to act as serverside logic to the template. * The method also consideres wheter or not to invoke the preview-version with administrative functioality or the * normal site-delivery version. */ public TemplateController getTemplateController(DatabaseWrapper dbWrapper, Integer siteNodeId, Integer languageId, Integer contentId, HttpServletRequest request, InfoGluePrincipal infoGluePrincipal) throws SystemException, Exception { TemplateController templateController = new BasicTemplateController(dbWrapper, infoGluePrincipal); templateController.setStandardRequestParameters(siteNodeId, languageId, contentId); templateController.setHttpRequest(request); templateController.setBrowserBean(browserBean); templateController.setDeliveryControllers(this.nodeDeliveryController, null, this.integrationDeliveryController); String operatingMode = CmsPropertyHandler.getProperty("operatingMode"); String editOnSite = CmsPropertyHandler.getProperty("editOnSite"); boolean isEditOnSightDisabled = templateController.getIsEditOnSightDisabled(); if(!isEditOnSightDisabled && operatingMode != null && (operatingMode.equals("0") || operatingMode.equals("1") || operatingMode.equals("2")) && editOnSite != null && editOnSite.equalsIgnoreCase("true")) { templateController = new EditOnSiteBasicTemplateController(dbWrapper, infoGluePrincipal); templateController.setStandardRequestParameters(siteNodeId, languageId, contentId); templateController.setHttpRequest(request); templateController.setBrowserBean(browserBean); templateController.setDeliveryControllers(this.nodeDeliveryController, null, this.integrationDeliveryController); } return templateController; } /** * Here we do all modifications needed on the request. For example we read the startpage if no * siteNodeId is given and stuff like that. Also a good place to put url-rewriting. * Rules so far includes: defaulting to the first repository if not specified and also defaulting to * masterlanguage for that site if not specifying. */ private void validateAndModifyInputParameters(Database db) throws SystemException, Exception { this.browserBean = new BrowserBean(); this.browserBean.setRequest(getRequest()); if(getSiteNodeId() == null) { if(getRepositoryName() == null) { setRepositoryName(RepositoryDeliveryController.getRepositoryDeliveryController().getMasterRepository(db).getName()); } SiteNodeVO rootSiteNodeVO = NodeDeliveryController.getRootSiteNode(db, getRepositoryName()); if(rootSiteNodeVO == null) throw new SystemException("There was no repository called " + getRepositoryName() + " or no pages were available in that repository"); setSiteNodeId(rootSiteNodeVO.getSiteNodeId()); } if(getLanguageId() == null) { LanguageVO browserLanguageVO = LanguageDeliveryController.getLanguageDeliveryController().getLanguageIfRepositorySupportsIt(db, browserBean.getLanguageCode(), getSiteNodeId()); if(browserLanguageVO != null) { setLanguageId(browserLanguageVO.getLanguageId()); } else { LanguageVO masterLanguageVO = LanguageDeliveryController.getLanguageDeliveryController().getMasterLanguageForSiteNode(db, this.getSiteNodeId()); if(masterLanguageVO == null) throw new SystemException("There was no master language for the siteNode " + getSiteNodeId()); setLanguageId(masterLanguageVO.getLanguageId()); } } this.principal = (Principal)this.getHttpSession().getAttribute("infogluePrincipal"); if(this.principal == null) { try { this.principal = (Principal)CacheController.getCachedObject("userCache", "anonymous"); if(this.principal == null) { Map arguments = new HashMap(); arguments.put("j_username", "anonymous"); arguments.put("j_password", "anonymous"); this.principal = ExtranetController.getController().getAuthenticatedPrincipal(db, arguments); if(principal != null) CacheController.cacheObject("userCache", "anonymous", this.principal); } //this.principal = ExtranetController.getController().getAuthenticatedPrincipal("anonymous", "anonymous"); } catch(Exception e) { throw new SystemException("There was no anonymous user found in the system. There must be - add the user anonymous/anonymous and try again.", e); } } } /** * This method validates that the current page is accessible to the requesting user. * It fetches information from the page metainfo about if the page is protected and if it is * validates the users credentials against the extranet database, */ public boolean handleExtranetLogic(Database db, Integer protectedSiteNodeVersionId) throws SystemException, Exception { boolean isRedirected = false; try { String referer = this.getRequest().getHeader("Referer"); CmsLogger.logInfo("referer:" + referer); if(referer == null) referer = "/"; Principal principal = (Principal)this.getHttpSession().getAttribute("infogluePrincipal"); CmsLogger.logInfo("principal:" + principal); if(principal == null) { try { principal = (Principal)CacheController.getCachedObject("userCache", "anonymous"); if(principal == null) { Map arguments = new HashMap(); arguments.put("j_username", "anonymous"); arguments.put("j_password", "anonymous"); principal = ExtranetController.getController().getAuthenticatedPrincipal(arguments); if(principal != null) CacheController.cacheObject("userCache", "anonymous", principal); } if(principal != null) { this.getHttpSession().setAttribute("infogluePrincipal", principal); SiteNodeVersionVO siteNodeVersionVO = this.nodeDeliveryController.getActiveSiteNodeVersionVO(db, siteNodeId); boolean isAuthorized = AccessRightController.getController().getIsPrincipalAuthorized(db, (InfoGluePrincipal)principal, "SiteNodeVersion.Read", siteNodeVersionVO.getId().toString()); if(!isAuthorized) { CmsLogger.logInfo("SiteNode is protected and user was not found - sending him to login page."); String url = "ExtranetLogin!loginForm.action?returnAddress=" + URLEncoder.encode(this.getRequest().getRequestURL().toString() + "?" + this.getRequest().getQueryString() + "&referer=" + URLEncoder.encode(referer, "UTF-8") + "&date=" + System.currentTimeMillis(), "UTF-8"); getResponse().sendRedirect(url); isRedirected = true; } } } catch(Exception e) { throw new SystemException("There was no anonymous user found in the system. There must be - add the user anonymous/anonymous and try again.", e); } } else { CmsLogger.logInfo("protectedSiteNodeVersionId:" + protectedSiteNodeVersionId); //Integer protectedSiteNodeVersionId = this.nodeDeliveryController.getProtectedSiteNodeVersionId(siteNodeId); Map arguments = new HashMap(); arguments.put("j_username", "anonymous"); arguments.put("j_password", "anonymous"); if(protectedSiteNodeVersionId != null && !AccessRightController.getController().getIsPrincipalAuthorized((InfoGluePrincipal)principal, "SiteNodeVersion.Read", protectedSiteNodeVersionId.toString()) && !AccessRightController.getController().getIsPrincipalAuthorized((InfoGluePrincipal)ExtranetController.getController().getAuthenticatedPrincipal(arguments), "SiteNodeVersion.Read", protectedSiteNodeVersionId.toString())) { if(this.referer == null) this.referer = this.getRequest().getHeader("Referer"); if(principal.getName().equals("anonymous")) { CmsLogger.logInfo("SiteNode is protected and user was anonymous - sending him to login page."); String url = "ExtranetLogin!loginForm.action?returnAddress=" + URLEncoder.encode(this.getRequest().getRequestURL().toString() + "?" + this.getRequest().getQueryString() + "&referer=" + URLEncoder.encode(referer, "UTF-8") + "&date=" + System.currentTimeMillis(), "UTF-8"); getResponse().sendRedirect(url); isRedirected = true; } else { CmsLogger.logInfo("SiteNode is protected and user has no access - sending him to no access page."); //final String url = "ExtranetLogin!noAccess.action?returnAddress=" + java.net.URLEncoder.encode(this.getRequest().getRequestURL().toString() + "?" + this.getRequest().getQueryString(), "UTF-8"); String url = "ExtranetLogin!noAccess.action?referer=" + URLEncoder.encode(this.referer, "UTF-8") + "&date=" + System.currentTimeMillis(); getResponse().sendRedirect(url); isRedirected = true; } } } } catch(SystemException se) { se.printStackTrace(); throw se; } catch(Exception e) { e.printStackTrace(); } return isRedirected; } /** * Setters and getters for all things sent to the page in the request */ public java.lang.Integer getSiteNodeId() { return this.siteNodeId; } public void setSiteNodeId(Integer siteNodeId) { this.siteNodeId = siteNodeId; } public Integer getContentId() { return this.contentId; } public void setContentId(Integer contentId) { this.contentId = contentId; } public Integer getLanguageId() { return this.languageId; } public void setLanguageId(Integer languageId) { this.languageId = languageId; } public String getRepositoryName() { return this.repositoryName; } public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } public String getReferer() { return referer; } public void setReferer(String referer) { this.referer = referer; } public void setShowSimple(boolean showSimple) { this.showSimple = showSimple; } }
false
true
public String doExecute() throws Exception { //CacheController.evictWaitingCache(); long start = new Date().getTime(); long elapsedTime = 0; CmsLogger.logInfo("************************************************"); CmsLogger.logInfo("* ViewPageAction was called.... *"); CmsLogger.logInfo("************************************************"); DatabaseWrapper dbWrapper = new DatabaseWrapper(CastorDatabaseService.getDatabase()); //Database db = CastorDatabaseService.getDatabase(); beginTransaction(dbWrapper.getDatabase()); try { validateAndModifyInputParameters(dbWrapper.getDatabase()); String pageKey = "" + this.siteNodeId + "_" + this.languageId + "_" + this.contentId + "_" + browserBean.getUseragent(); CmsLogger.logInfo("pageKey:" + pageKey); String pagePath = null; this.nodeDeliveryController = NodeDeliveryController.getNodeDeliveryController(this.siteNodeId, this.languageId, this.contentId); this.integrationDeliveryController = IntegrationDeliveryController.getIntegrationDeliveryController(this.siteNodeId, this.languageId, this.contentId); this.templateController = getTemplateController(dbWrapper, getSiteNodeId(), getLanguageId(), getContentId(), getRequest(), (InfoGluePrincipal)this.principal); boolean isUserRedirected = false; Integer protectedSiteNodeVersionId = this.nodeDeliveryController.getProtectedSiteNodeVersionId(dbWrapper.getDatabase(), siteNodeId); CmsLogger.logInfo("protectedSiteNodeVersionId:" + protectedSiteNodeVersionId); if(protectedSiteNodeVersionId != null) isUserRedirected = handleExtranetLogic(dbWrapper.getDatabase(), protectedSiteNodeVersionId); CmsLogger.logInfo("handled extranet users"); // ---- // -- portlet // ---- // -- check if the portal is active String portalEnabled = CmsPropertyHandler.getProperty("enablePortal") ; boolean portalActive = ((portalEnabled != null) && portalEnabled.equals("true")); if (portalActive) { CmsLogger.logInfo("---> Checking for portlet action"); PortalService service = new PortalService(); //TODO: catch PortalException? boolean actionExecuted = service.service(getRequest(), getResponse()); // -- if an action was executed return NONE as a redirect is issued if (actionExecuted) { CmsLogger.logInfo("---> PortletAction was executed, returning NONE as a redirect has been issued"); //TODO: maybe statistics service should run here CmsLogger.logWarning("No statistics have been run for this request"); return NONE; } } CmsLogger.logInfo("handled portal action"); if(!isUserRedirected) { CmsLogger.logInfo("this.templateController.getPrincipal():" + this.templateController.getPrincipal()); DeliveryContext deliveryContext = DeliveryContext.getDeliveryContext(/*(InfoGluePrincipal)this.principal*/); deliveryContext.setRepositoryName(this.repositoryName); deliveryContext.setSiteNodeId(this.siteNodeId); deliveryContext.setContentId(this.contentId); deliveryContext.setLanguageId(this.languageId); deliveryContext.setPageKey(pageKey); deliveryContext.setSession(this.getSession()); deliveryContext.setWebworkAbstractAction(this); deliveryContext.setHttpServletRequest(this.getRequest()); deliveryContext.setHttpServletResponse(this.getResponse()); SiteNode siteNode = nodeDeliveryController.getSiteNode(dbWrapper.getDatabase(), this.siteNodeId); if(siteNode == null) throw new SystemException("There was no page with this id."); String invokerClassName = siteNode.getSiteNodeTypeDefinition().getInvokerClassName(); if(invokerClassName == null && invokerClassName.equals("")) { throw new SystemException("There was no page invoker class assigned to this page type."); } else { try { PageInvoker pageInvoker = (PageInvoker)Class.forName(invokerClassName).newInstance(); pageInvoker.setParameters(dbWrapper, this.getRequest(), this.getResponse(), this.templateController, deliveryContext); pageInvoker.deliverPage(); } catch(ClassNotFoundException e) { throw new SystemException("An error was thrown when trying to use the page invoker class assigned to this page type:" + e.getMessage(), e); } } } elapsedTime = new Date().getTime() - start; CmsLogger.logWarning("The page delivery took " + elapsedTime + "ms"); //CmsLogger.logWarning("Of that is " + contentAttributeTime + "ms from contentAttribute fetching..."); //CmsLogger.logWarning("and " + contentVersionTime + "ms from contentVersion fetching..."); //CmsLogger.logWarning("and " + serviceBindingTime + "ms from serviceBinding fetching..."); //CmsLogger.logWarning("and " + boundContentTime + "ms from boundContent fetching..."); //CmsLogger.logWarning("and " + inheritedServiceBindingTime + "ms from inheritedServiceBindingTime fetching..."); //CmsLogger.logWarning("and " + selectMatchingEntitiesTime + "ms from selectMatchingEntities fetching..."); //CmsLogger.logWarning("and " + isValidTime + "ms from isValidTime fetching..."); //CmsLogger.logWarning("and " + qualifyersTime + "ms from qualifyers fetching..."); //CmsLogger.logWarning("and " + sortQualifyersTime + "ms from sortQualifyers fetching..."); //CmsLogger.logWarning("and " + commitTime + "ms from commitTime fetching..."); //CmsLogger.logWarning("and " + rollbackTime + "ms from rollbackTime fetching..."); //CmsLogger.logWarning("and " + closeTime + "ms from closeTime fetching..."); contentAttributeTime = 0; contentVersionTime = 0; serviceBindingTime = 0; boundContentTime = 0; inheritedServiceBindingTime = 0; selectMatchingEntitiesTime = 0; isValidTime = 0; qualifyersTime = 0; sortQualifyersTime = 0; commitTime = 0; rollbackTime = 0; closeTime = 0; CmsLogger.logWarning("The memory consumption was " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + "(" + Runtime.getRuntime().totalMemory() + "/" + Runtime.getRuntime().maxMemory() + ") bytes"); StatisticsService.getStatisticsService().registerRequest(getRequest(), getResponse(), pagePath, elapsedTime); closeTransaction(dbWrapper.getDatabase()); } catch(Exception e) { CmsLogger.logSevere("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(dbWrapper.getDatabase()); throw new SystemException(e.getMessage()); } return NONE; }
public String doExecute() throws Exception { //CacheController.evictWaitingCache(); long start = new Date().getTime(); long elapsedTime = 0; CmsLogger.logInfo("************************************************"); CmsLogger.logInfo("* ViewPageAction was called.... *"); CmsLogger.logInfo("************************************************"); DatabaseWrapper dbWrapper = new DatabaseWrapper(CastorDatabaseService.getDatabase()); //Database db = CastorDatabaseService.getDatabase(); beginTransaction(dbWrapper.getDatabase()); try { validateAndModifyInputParameters(dbWrapper.getDatabase()); String pageKey = "" + this.siteNodeId + "_" + this.languageId + "_" + this.contentId + "_" + browserBean.getUseragent(); CmsLogger.logInfo("pageKey:" + pageKey); String pagePath = null; this.nodeDeliveryController = NodeDeliveryController.getNodeDeliveryController(this.siteNodeId, this.languageId, this.contentId); this.integrationDeliveryController = IntegrationDeliveryController.getIntegrationDeliveryController(this.siteNodeId, this.languageId, this.contentId); this.templateController = getTemplateController(dbWrapper, getSiteNodeId(), getLanguageId(), getContentId(), getRequest(), (InfoGluePrincipal)this.principal); boolean isUserRedirected = false; Integer protectedSiteNodeVersionId = this.nodeDeliveryController.getProtectedSiteNodeVersionId(dbWrapper.getDatabase(), siteNodeId); CmsLogger.logInfo("protectedSiteNodeVersionId:" + protectedSiteNodeVersionId); if(protectedSiteNodeVersionId != null) isUserRedirected = handleExtranetLogic(dbWrapper.getDatabase(), protectedSiteNodeVersionId); CmsLogger.logInfo("handled extranet users"); // ---- // -- portlet // ---- // -- check if the portal is active String portalEnabled = CmsPropertyHandler.getProperty("enablePortal") ; boolean portalActive = ((portalEnabled != null) && portalEnabled.equals("true")); if (portalActive) { CmsLogger.logInfo("---> Checking for portlet action"); PortalService service = new PortalService(); //TODO: catch PortalException? boolean actionExecuted = service.service(getRequest(), getResponse()); // -- if an action was executed return NONE as a redirect is issued if (actionExecuted) { CmsLogger.logInfo("---> PortletAction was executed, returning NONE as a redirect has been issued"); //TODO: maybe statistics service should run here CmsLogger.logWarning("No statistics have been run for this request"); return NONE; } } CmsLogger.logInfo("handled portal action"); if(!isUserRedirected) { CmsLogger.logInfo("this.templateController.getPrincipal():" + this.templateController.getPrincipal()); DeliveryContext deliveryContext = DeliveryContext.getDeliveryContext(/*(InfoGluePrincipal)this.principal*/); deliveryContext.setRepositoryName(this.repositoryName); deliveryContext.setSiteNodeId(this.siteNodeId); deliveryContext.setContentId(this.contentId); deliveryContext.setLanguageId(this.languageId); deliveryContext.setPageKey(pageKey); deliveryContext.setSession(this.getSession()); deliveryContext.setWebworkAbstractAction(this); deliveryContext.setHttpServletRequest(this.getRequest()); deliveryContext.setHttpServletResponse(this.getResponse()); SiteNode siteNode = nodeDeliveryController.getSiteNode(dbWrapper.getDatabase(), this.siteNodeId); if(siteNode == null) throw new SystemException("There was no page with this id."); if(siteNode.getSiteNodeTypeDefinition() == null || siteNode.getSiteNodeTypeDefinition().getInvokerClassName() == null || siteNode.getSiteNodeTypeDefinition().getInvokerClassName().equals("")) { throw new SystemException("There was no page invoker class assigned to the site node " + siteNode.getName()); } else { try { String invokerClassName = siteNode.getSiteNodeTypeDefinition().getInvokerClassName(); PageInvoker pageInvoker = (PageInvoker)Class.forName(invokerClassName).newInstance(); pageInvoker.setParameters(dbWrapper, this.getRequest(), this.getResponse(), this.templateController, deliveryContext); pageInvoker.deliverPage(); } catch(ClassNotFoundException e) { throw new SystemException("An error was thrown when trying to use the page invoker class assigned to this page type:" + e.getMessage(), e); } } } elapsedTime = new Date().getTime() - start; CmsLogger.logWarning("The page delivery took " + elapsedTime + "ms"); //CmsLogger.logWarning("Of that is " + contentAttributeTime + "ms from contentAttribute fetching..."); //CmsLogger.logWarning("and " + contentVersionTime + "ms from contentVersion fetching..."); //CmsLogger.logWarning("and " + serviceBindingTime + "ms from serviceBinding fetching..."); //CmsLogger.logWarning("and " + boundContentTime + "ms from boundContent fetching..."); //CmsLogger.logWarning("and " + inheritedServiceBindingTime + "ms from inheritedServiceBindingTime fetching..."); //CmsLogger.logWarning("and " + selectMatchingEntitiesTime + "ms from selectMatchingEntities fetching..."); //CmsLogger.logWarning("and " + isValidTime + "ms from isValidTime fetching..."); //CmsLogger.logWarning("and " + qualifyersTime + "ms from qualifyers fetching..."); //CmsLogger.logWarning("and " + sortQualifyersTime + "ms from sortQualifyers fetching..."); //CmsLogger.logWarning("and " + commitTime + "ms from commitTime fetching..."); //CmsLogger.logWarning("and " + rollbackTime + "ms from rollbackTime fetching..."); //CmsLogger.logWarning("and " + closeTime + "ms from closeTime fetching..."); contentAttributeTime = 0; contentVersionTime = 0; serviceBindingTime = 0; boundContentTime = 0; inheritedServiceBindingTime = 0; selectMatchingEntitiesTime = 0; isValidTime = 0; qualifyersTime = 0; sortQualifyersTime = 0; commitTime = 0; rollbackTime = 0; closeTime = 0; CmsLogger.logWarning("The memory consumption was " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + "(" + Runtime.getRuntime().totalMemory() + "/" + Runtime.getRuntime().maxMemory() + ") bytes"); StatisticsService.getStatisticsService().registerRequest(getRequest(), getResponse(), pagePath, elapsedTime); closeTransaction(dbWrapper.getDatabase()); } catch(Exception e) { CmsLogger.logSevere("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(dbWrapper.getDatabase()); throw new SystemException(e.getMessage()); } return NONE; }
diff --git a/AMBroSIA/src/game/timeToLive.java b/AMBroSIA/src/game/timeToLive.java index 8e830f2..aeb1886 100644 --- a/AMBroSIA/src/game/timeToLive.java +++ b/AMBroSIA/src/game/timeToLive.java @@ -1,69 +1,69 @@ package game; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.log4j.Logger; /** * The Time to live class contains code that checks the time to live of certain * objects (such as bonus drops, projectiles) and removes them from the game * once it is time for them to be removed. * * @author Michael */ public class timeToLive implements Runnable { private GameState gameState; private final static Logger log = Logger.getLogger(timeToLive.class.getName()); public timeToLive(GameState gs) { gameState = gs; log.setLevel(Logic.LOG_LEVEL); } @Override public void run() { checkTTL(); } private void checkTTL() { //work on all bonus drops, explosions, projectiles TTLLogic(gameState.getBonusDrops()); TTLLogic(gameState.getExplosions()); TTLLogic(gameState.getProjectiles()); } private void TTLLogic(List<? extends MapObjectTTL> objectList) { if (!objectList.isEmpty()) { log.debug("Starting TTL Check"); - ArrayList<Object> toRemove = new ArrayList(); + ArrayList<Object> toRemove = new ArrayList<Object>(); for (MapObjectTTL object : objectList) { //TTL is in seconds : if it still has life left we simply set it for the next one, else, it's gone if (object.getTTL() > 0) { object.setTTL(object.getTTL() - 1); } else { toRemove.add(object); } } //now that we have a list of objects, we remove them //deal with types as appropriate. OK to pull first entry always because we make sure befor that the list is not empty if (objectList.get(0) instanceof Projectile) { gameState.removeListOfProjectiles(toRemove); } else if (objectList.get(0) instanceof MapObjectTTL) { gameState.removeListOfExplosions(toRemove); } //last possibility else { gameState.removeListOfBonusDrops(toRemove); } } } }
true
true
private void TTLLogic(List<? extends MapObjectTTL> objectList) { if (!objectList.isEmpty()) { log.debug("Starting TTL Check"); ArrayList<Object> toRemove = new ArrayList(); for (MapObjectTTL object : objectList) { //TTL is in seconds : if it still has life left we simply set it for the next one, else, it's gone if (object.getTTL() > 0) { object.setTTL(object.getTTL() - 1); } else { toRemove.add(object); } } //now that we have a list of objects, we remove them //deal with types as appropriate. OK to pull first entry always because we make sure befor that the list is not empty if (objectList.get(0) instanceof Projectile) { gameState.removeListOfProjectiles(toRemove); } else if (objectList.get(0) instanceof MapObjectTTL) { gameState.removeListOfExplosions(toRemove); } //last possibility else { gameState.removeListOfBonusDrops(toRemove); } } }
private void TTLLogic(List<? extends MapObjectTTL> objectList) { if (!objectList.isEmpty()) { log.debug("Starting TTL Check"); ArrayList<Object> toRemove = new ArrayList<Object>(); for (MapObjectTTL object : objectList) { //TTL is in seconds : if it still has life left we simply set it for the next one, else, it's gone if (object.getTTL() > 0) { object.setTTL(object.getTTL() - 1); } else { toRemove.add(object); } } //now that we have a list of objects, we remove them //deal with types as appropriate. OK to pull first entry always because we make sure befor that the list is not empty if (objectList.get(0) instanceof Projectile) { gameState.removeListOfProjectiles(toRemove); } else if (objectList.get(0) instanceof MapObjectTTL) { gameState.removeListOfExplosions(toRemove); } //last possibility else { gameState.removeListOfBonusDrops(toRemove); } } }
diff --git a/de.walware.statet.r.ui/src/de/walware/statet/r/internal/ui/preferences/REditorPreferencePage.java b/de.walware.statet.r.ui/src/de/walware/statet/r/internal/ui/preferences/REditorPreferencePage.java index c06f2aaa..d020a224 100644 --- a/de.walware.statet.r.ui/src/de/walware/statet/r/internal/ui/preferences/REditorPreferencePage.java +++ b/de.walware.statet.r.ui/src/de/walware/statet/r/internal/ui/preferences/REditorPreferencePage.java @@ -1,351 +1,354 @@ /******************************************************************************* * Copyright (c) 2007-2011 WalWare/StatET-Project (www.walware.de/goto/statet). * 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: * Stephan Wahlbrink - initial API and implementation *******************************************************************************/ package de.walware.statet.r.internal.ui.preferences; import java.util.HashMap; import java.util.Map; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.observable.Realm; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Text; import de.walware.ecommons.IStatusChangeListener; import de.walware.ecommons.databinding.NumberValidator; import de.walware.ecommons.preferences.Preference; import de.walware.ecommons.preferences.ui.ConfigurationBlockPreferencePage; import de.walware.ecommons.preferences.ui.ManagedConfigurationBlock; import de.walware.ecommons.ui.util.LayoutUtil; import de.walware.statet.r.internal.ui.RUIPreferenceInitializer; import de.walware.statet.r.internal.ui.editors.DefaultRFoldingPreferences; import de.walware.statet.r.ui.editors.REditorOptions; /** * Preference page for 'R Editor Options' */ public class REditorPreferencePage extends ConfigurationBlockPreferencePage<REditorConfigurationBlock> { public REditorPreferencePage() { } @Override protected REditorConfigurationBlock createConfigurationBlock() { return new REditorConfigurationBlock(createStatusChangedListener()); } } class REditorConfigurationBlock extends ManagedConfigurationBlock { private Button fSmartInsertControl; private Button[] fSmartInsertOnPasteControl; private Button[] fSmartInsertCloseCurlyBracketsControl; private Button[] fSmartInsertCloseRoundBracketsControl; private Button[] fSmartInsertCloseSquareBracketsControl; private Button[] fSmartInsertCloseSpecialControl; private Button[] fSmartInsertCloseStringsControl; private Button fFoldingEnableControl; private Button fFoldingDefaultAllBlocksControl; private Text fFoldingDefaultMinLines; private Button fFoldingDefaultRoxygenControl; private Button fFoldingDefaultRoxygenInitiallyControl; private Text fFoldingDefaultRoxygenMinLines; private Button fMarkOccurrencesControl; private Button fProblemsEnableControl; private Button fSpellEnableControl; public REditorConfigurationBlock(final IStatusChangeListener statusListener) { super(null, statusListener); } @Override protected void createBlockArea(final Composite pageComposite) { // Preferences final Map<Preference, String> prefs = new HashMap<Preference, String>(); prefs.put(REditorOptions.PREF_SMARTINSERT_BYDEFAULT_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_ONPASTE_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSECURLY_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSEROUND_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSESQUARE_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSESPECIAL_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSESTRINGS_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSECURLY_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSEROUND_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESQUARE_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESPECIAL_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESTRINGS_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_FOLDING_ENABLED, null); prefs.put(DefaultRFoldingPreferences.PREF_OTHERBLOCKS_ENABLED, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_MINLINES_NUM, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_ROXYGEN_ENABLED, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_ROXYGEN_COLLAPSE_INITIALLY_ENABLED, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_ROXYGEN_MINLINES_NUM, DefaultRFoldingPreferences.GROUP_ID); prefs.put(REditorOptions.PREF_MARKOCCURRENCES_ENABLED, null); prefs.put(REditorOptions.PREF_PROBLEMCHECKING_ENABLED, null); prefs.put(REditorOptions.PREF_SPELLCHECKING_ENABLED, REditorOptions.GROUP_ID); setupPreferenceManager(prefs); // Controls Group group; int n; group = new Group(pageComposite, SWT.NONE); group.setText(Messages.REditorOptions_SmartInsert_label+':'); group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); n = 5; group.setLayout(LayoutUtil.applyGroupDefaults(new GridLayout(), n)); fSmartInsertControl = new Button(group, SWT.CHECK); fSmartInsertControl.setText(Messages.REditorOptions_SmartInsert_AsDefault_label); fSmartInsertControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, n, 1)); { final Link link = addLinkControl(group, Messages.REditorOptions_SmartInsert_description); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, n, 1); gd.widthHint = 300; link.setLayoutData(gd); } LayoutUtil.addGDDummy(group); LayoutUtil.addGDDummy(group); { Label label = new Label(group, SWT.CENTER); label.setText(Messages.REditorOptions_SmartInsert_ForEditor_header); label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); label = new Label(group, SWT.CENTER); label.setText(Messages.REditorOptions_SmartInsert_ForConsole_header); label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); } final Label dummy = new Label(group, SWT.NONE); dummy.setVisible(false); dummy.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 7)); fSmartInsertOnPasteControl = createOption(group, Messages.REditorOptions_SmartInsert_OnPaste_label, null, false); fSmartInsertCloseCurlyBracketsControl = createOption(group, Messages.REditorOptions_SmartInsert_CloseAuto_label, Messages.REditorOptions_SmartInsert_CloseCurly_label, true); fSmartInsertCloseRoundBracketsControl = createOption(group, null, Messages.REditorOptions_SmartInsert_CloseRound_label, true); fSmartInsertCloseSquareBracketsControl = createOption(group, null, Messages.REditorOptions_SmartInsert_CloseSquare_label, true); fSmartInsertCloseSpecialControl = createOption(group, null, Messages.REditorOptions_SmartInsert_ClosePercent_label, true); fSmartInsertCloseStringsControl = createOption(group, null, Messages.REditorOptions_SmartInsert_CloseString_label, true); // Code Folding LayoutUtil.addSmallFiller(pageComposite, false); { fFoldingEnableControl = new Button(pageComposite, SWT.CHECK); fFoldingEnableControl.setText(Messages.REditorOptions_Folding_Enable_label); fFoldingEnableControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); } final Composite foldingOptions = new Composite(pageComposite, SWT.NONE); { final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.horizontalIndent = LayoutUtil.defaultIndent(); foldingOptions.setLayoutData(gd); foldingOptions.setLayout(LayoutUtil.applyCompositeDefaults(new GridLayout(), 2)); } { fFoldingDefaultAllBlocksControl = new Button(foldingOptions, SWT.CHECK); fFoldingDefaultAllBlocksControl.setText(Messages.REditorOptions_Folding_EnableForAllBlocks_label); fFoldingDefaultAllBlocksControl.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); } { final Label label = new Label(foldingOptions, SWT.LEFT); + final GridData gd = new GridData(SWT.FILL, SWT.CENTER, false, false); + gd.horizontalIndent = LayoutUtil.defaultIndent(); + label.setLayoutData(gd); label.setText(Messages.REditorOptions_Folding_MinNumOfLines_label); - label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); - fFoldingDefaultMinLines = new Text(foldingOptions, SWT.SINGLE | SWT.BORDER); + } + { fFoldingDefaultMinLines = new Text(foldingOptions, SWT.SINGLE | SWT.BORDER); final GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, false); gd.widthHint = LayoutUtil.hintWidth(fFoldingDefaultMinLines, 2); fFoldingDefaultMinLines.setLayoutData(gd); } { fFoldingDefaultRoxygenControl = new Button(foldingOptions, SWT.CHECK); fFoldingDefaultRoxygenControl.setText(Messages.REditorOptions_Folding_EnableForRoxygen_label); fFoldingDefaultRoxygenControl.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); } { final Label label = new Label(foldingOptions, SWT.LEFT); - label.setText(Messages.REditorOptions_Folding_MinNumOfLines_label); final GridData gd = new GridData(SWT.FILL, SWT.CENTER, false, false); gd.horizontalIndent = LayoutUtil.defaultIndent(); label.setLayoutData(gd); + label.setText(Messages.REditorOptions_Folding_MinNumOfLines_label); } { fFoldingDefaultRoxygenMinLines = new Text(foldingOptions, SWT.SINGLE | SWT.BORDER); final GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, false); gd.widthHint = LayoutUtil.hintWidth(fFoldingDefaultRoxygenMinLines, 2); fFoldingDefaultRoxygenMinLines.setLayoutData(gd); } { fFoldingDefaultRoxygenInitiallyControl = new Button(foldingOptions, SWT.CHECK); fFoldingDefaultRoxygenInitiallyControl.setText(Messages.REditorOptions_Folding_EnableForRoxygen_Initially_label); final GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); gd.horizontalIndent = LayoutUtil.defaultIndent(); fFoldingDefaultRoxygenInitiallyControl.setLayoutData(gd); } // Annotation LayoutUtil.addSmallFiller(pageComposite, false); { fMarkOccurrencesControl = new Button(pageComposite, SWT.CHECK); fMarkOccurrencesControl.setText(Messages.REditorOptions_MarkOccurrences_Enable_label); fMarkOccurrencesControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); final Link link = addLinkControl(pageComposite, Messages.REditorOptions_MarkOccurrences_Appearance_info); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.widthHint = 300; gd.horizontalIndent = LayoutUtil.defaultIndent(); link.setLayoutData(gd); } LayoutUtil.addSmallFiller(pageComposite, false); { fProblemsEnableControl = new Button(pageComposite, SWT.CHECK); fProblemsEnableControl.setText(Messages.REditorOptions_ProblemChecking_Enable_label); fProblemsEnableControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); } LayoutUtil.addSmallFiller(pageComposite, false); { fSpellEnableControl = new Button(pageComposite, SWT.CHECK); fSpellEnableControl.setText(Messages.REditorOptions_SpellChecking_Enable_label); fSpellEnableControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); final Link link = addLinkControl(pageComposite, Messages.REditorOptions_SpellChecking_note); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.widthHint = 300; gd.horizontalIndent = LayoutUtil.defaultIndent(); link.setLayoutData(gd); } // Binding initBindings(); updateControls(); } private Button[] createOption(final Composite composite, final String text1, final String text2, final boolean console) { GridData gd; if (text1 != null) { final Label label = new Label(composite, SWT.NONE); if (text2 == null) { label.setText(text1+':'); gd = new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1); } else { label.setText(text1); gd = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); } label.setLayoutData(gd); } else { LayoutUtil.addGDDummy(composite); } if (text2 != null) { final Label label = new Label(composite, SWT.NONE); label.setText(text2+':'); gd = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); label.setLayoutData(gd); } final Button button0 = new Button(composite, SWT.CHECK); gd = new GridData(SWT.CENTER, SWT.CENTER, false, false); button0.setLayoutData(gd); final Button button1 = new Button(composite, SWT.CHECK); gd = new GridData(SWT.CENTER, SWT.CENTER, false, false); button1.setLayoutData(gd); if (!console) { button1.setEnabled(false); } return new Button[] { button0, button1 }; } @Override protected void addBindings(final DataBindingContext dbc, final Realm realm) { dbc.bindValue(SWTObservables.observeSelection(fSmartInsertControl), createObservable(REditorOptions.PREF_SMARTINSERT_BYDEFAULT_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertOnPasteControl[0]), createObservable(REditorOptions.PREF_SMARTINSERT_ONPASTE_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseCurlyBracketsControl[0]), createObservable(REditorOptions.PREF_SMARTINSERT_CLOSECURLY_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseRoundBracketsControl[0]), createObservable(REditorOptions.PREF_SMARTINSERT_CLOSEROUND_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseSquareBracketsControl[0]), createObservable(REditorOptions.PREF_SMARTINSERT_CLOSESQUARE_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseSpecialControl[0]), createObservable(REditorOptions.PREF_SMARTINSERT_CLOSESPECIAL_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseStringsControl[0]), createObservable(REditorOptions.PREF_SMARTINSERT_CLOSESTRINGS_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseCurlyBracketsControl[1]), createObservable(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSECURLY_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseRoundBracketsControl[1]), createObservable(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSEROUND_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseSquareBracketsControl[1]), createObservable(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESQUARE_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseSpecialControl[1]), createObservable(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESPECIAL_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSmartInsertCloseStringsControl[1]), createObservable(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESTRINGS_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fFoldingEnableControl), createObservable(REditorOptions.PREF_FOLDING_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fFoldingDefaultAllBlocksControl), createObservable(DefaultRFoldingPreferences.PREF_OTHERBLOCKS_ENABLED), null, null); dbc.bindValue(SWTObservables.observeText(fFoldingDefaultMinLines, SWT.Modify), createObservable(DefaultRFoldingPreferences.PREF_MINLINES_NUM), new UpdateValueStrategy().setAfterGetValidator(new NumberValidator(2, 1000, Messages.REditorOptions_Folding_MinNumOfLines_error_message)), null); dbc.bindValue(SWTObservables.observeSelection(fFoldingDefaultRoxygenControl), createObservable(DefaultRFoldingPreferences.PREF_ROXYGEN_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fFoldingDefaultRoxygenInitiallyControl), createObservable(DefaultRFoldingPreferences.PREF_ROXYGEN_COLLAPSE_INITIALLY_ENABLED), null, null); dbc.bindValue(SWTObservables.observeText(fFoldingDefaultRoxygenMinLines, SWT.Modify), createObservable(DefaultRFoldingPreferences.PREF_ROXYGEN_MINLINES_NUM), new UpdateValueStrategy().setAfterGetValidator(new NumberValidator(2, 1000, Messages.REditorOptions_Folding_MinNumOfLines_error_message)), null); dbc.bindValue(SWTObservables.observeSelection(fMarkOccurrencesControl), createObservable(REditorOptions.PREF_MARKOCCURRENCES_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fProblemsEnableControl), createObservable(REditorOptions.PREF_PROBLEMCHECKING_ENABLED), null, null); dbc.bindValue(SWTObservables.observeSelection(fSpellEnableControl), createObservable(REditorOptions.PREF_SPELLCHECKING_ENABLED), null, null); } }
false
true
protected void createBlockArea(final Composite pageComposite) { // Preferences final Map<Preference, String> prefs = new HashMap<Preference, String>(); prefs.put(REditorOptions.PREF_SMARTINSERT_BYDEFAULT_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_ONPASTE_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSECURLY_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSEROUND_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSESQUARE_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSESPECIAL_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSESTRINGS_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSECURLY_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSEROUND_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESQUARE_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESPECIAL_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESTRINGS_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_FOLDING_ENABLED, null); prefs.put(DefaultRFoldingPreferences.PREF_OTHERBLOCKS_ENABLED, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_MINLINES_NUM, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_ROXYGEN_ENABLED, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_ROXYGEN_COLLAPSE_INITIALLY_ENABLED, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_ROXYGEN_MINLINES_NUM, DefaultRFoldingPreferences.GROUP_ID); prefs.put(REditorOptions.PREF_MARKOCCURRENCES_ENABLED, null); prefs.put(REditorOptions.PREF_PROBLEMCHECKING_ENABLED, null); prefs.put(REditorOptions.PREF_SPELLCHECKING_ENABLED, REditorOptions.GROUP_ID); setupPreferenceManager(prefs); // Controls Group group; int n; group = new Group(pageComposite, SWT.NONE); group.setText(Messages.REditorOptions_SmartInsert_label+':'); group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); n = 5; group.setLayout(LayoutUtil.applyGroupDefaults(new GridLayout(), n)); fSmartInsertControl = new Button(group, SWT.CHECK); fSmartInsertControl.setText(Messages.REditorOptions_SmartInsert_AsDefault_label); fSmartInsertControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, n, 1)); { final Link link = addLinkControl(group, Messages.REditorOptions_SmartInsert_description); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, n, 1); gd.widthHint = 300; link.setLayoutData(gd); } LayoutUtil.addGDDummy(group); LayoutUtil.addGDDummy(group); { Label label = new Label(group, SWT.CENTER); label.setText(Messages.REditorOptions_SmartInsert_ForEditor_header); label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); label = new Label(group, SWT.CENTER); label.setText(Messages.REditorOptions_SmartInsert_ForConsole_header); label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); } final Label dummy = new Label(group, SWT.NONE); dummy.setVisible(false); dummy.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 7)); fSmartInsertOnPasteControl = createOption(group, Messages.REditorOptions_SmartInsert_OnPaste_label, null, false); fSmartInsertCloseCurlyBracketsControl = createOption(group, Messages.REditorOptions_SmartInsert_CloseAuto_label, Messages.REditorOptions_SmartInsert_CloseCurly_label, true); fSmartInsertCloseRoundBracketsControl = createOption(group, null, Messages.REditorOptions_SmartInsert_CloseRound_label, true); fSmartInsertCloseSquareBracketsControl = createOption(group, null, Messages.REditorOptions_SmartInsert_CloseSquare_label, true); fSmartInsertCloseSpecialControl = createOption(group, null, Messages.REditorOptions_SmartInsert_ClosePercent_label, true); fSmartInsertCloseStringsControl = createOption(group, null, Messages.REditorOptions_SmartInsert_CloseString_label, true); // Code Folding LayoutUtil.addSmallFiller(pageComposite, false); { fFoldingEnableControl = new Button(pageComposite, SWT.CHECK); fFoldingEnableControl.setText(Messages.REditorOptions_Folding_Enable_label); fFoldingEnableControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); } final Composite foldingOptions = new Composite(pageComposite, SWT.NONE); { final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.horizontalIndent = LayoutUtil.defaultIndent(); foldingOptions.setLayoutData(gd); foldingOptions.setLayout(LayoutUtil.applyCompositeDefaults(new GridLayout(), 2)); } { fFoldingDefaultAllBlocksControl = new Button(foldingOptions, SWT.CHECK); fFoldingDefaultAllBlocksControl.setText(Messages.REditorOptions_Folding_EnableForAllBlocks_label); fFoldingDefaultAllBlocksControl.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); } { final Label label = new Label(foldingOptions, SWT.LEFT); label.setText(Messages.REditorOptions_Folding_MinNumOfLines_label); label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); fFoldingDefaultMinLines = new Text(foldingOptions, SWT.SINGLE | SWT.BORDER); final GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, false); gd.widthHint = LayoutUtil.hintWidth(fFoldingDefaultMinLines, 2); fFoldingDefaultMinLines.setLayoutData(gd); } { fFoldingDefaultRoxygenControl = new Button(foldingOptions, SWT.CHECK); fFoldingDefaultRoxygenControl.setText(Messages.REditorOptions_Folding_EnableForRoxygen_label); fFoldingDefaultRoxygenControl.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); } { final Label label = new Label(foldingOptions, SWT.LEFT); label.setText(Messages.REditorOptions_Folding_MinNumOfLines_label); final GridData gd = new GridData(SWT.FILL, SWT.CENTER, false, false); gd.horizontalIndent = LayoutUtil.defaultIndent(); label.setLayoutData(gd); } { fFoldingDefaultRoxygenMinLines = new Text(foldingOptions, SWT.SINGLE | SWT.BORDER); final GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, false); gd.widthHint = LayoutUtil.hintWidth(fFoldingDefaultRoxygenMinLines, 2); fFoldingDefaultRoxygenMinLines.setLayoutData(gd); } { fFoldingDefaultRoxygenInitiallyControl = new Button(foldingOptions, SWT.CHECK); fFoldingDefaultRoxygenInitiallyControl.setText(Messages.REditorOptions_Folding_EnableForRoxygen_Initially_label); final GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); gd.horizontalIndent = LayoutUtil.defaultIndent(); fFoldingDefaultRoxygenInitiallyControl.setLayoutData(gd); } // Annotation LayoutUtil.addSmallFiller(pageComposite, false); { fMarkOccurrencesControl = new Button(pageComposite, SWT.CHECK); fMarkOccurrencesControl.setText(Messages.REditorOptions_MarkOccurrences_Enable_label); fMarkOccurrencesControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); final Link link = addLinkControl(pageComposite, Messages.REditorOptions_MarkOccurrences_Appearance_info); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.widthHint = 300; gd.horizontalIndent = LayoutUtil.defaultIndent(); link.setLayoutData(gd); } LayoutUtil.addSmallFiller(pageComposite, false); { fProblemsEnableControl = new Button(pageComposite, SWT.CHECK); fProblemsEnableControl.setText(Messages.REditorOptions_ProblemChecking_Enable_label); fProblemsEnableControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); } LayoutUtil.addSmallFiller(pageComposite, false); { fSpellEnableControl = new Button(pageComposite, SWT.CHECK); fSpellEnableControl.setText(Messages.REditorOptions_SpellChecking_Enable_label); fSpellEnableControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); final Link link = addLinkControl(pageComposite, Messages.REditorOptions_SpellChecking_note); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.widthHint = 300; gd.horizontalIndent = LayoutUtil.defaultIndent(); link.setLayoutData(gd); } // Binding initBindings(); updateControls(); }
protected void createBlockArea(final Composite pageComposite) { // Preferences final Map<Preference, String> prefs = new HashMap<Preference, String>(); prefs.put(REditorOptions.PREF_SMARTINSERT_BYDEFAULT_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_ONPASTE_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSECURLY_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSEROUND_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSESQUARE_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSESPECIAL_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_SMARTINSERT_CLOSESTRINGS_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSECURLY_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSEROUND_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESQUARE_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESPECIAL_ENABLED, REditorOptions.GROUP_ID); prefs.put(RUIPreferenceInitializer.CONSOLE_SMARTINSERT_CLOSESTRINGS_ENABLED, REditorOptions.GROUP_ID); prefs.put(REditorOptions.PREF_FOLDING_ENABLED, null); prefs.put(DefaultRFoldingPreferences.PREF_OTHERBLOCKS_ENABLED, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_MINLINES_NUM, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_ROXYGEN_ENABLED, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_ROXYGEN_COLLAPSE_INITIALLY_ENABLED, DefaultRFoldingPreferences.GROUP_ID); prefs.put(DefaultRFoldingPreferences.PREF_ROXYGEN_MINLINES_NUM, DefaultRFoldingPreferences.GROUP_ID); prefs.put(REditorOptions.PREF_MARKOCCURRENCES_ENABLED, null); prefs.put(REditorOptions.PREF_PROBLEMCHECKING_ENABLED, null); prefs.put(REditorOptions.PREF_SPELLCHECKING_ENABLED, REditorOptions.GROUP_ID); setupPreferenceManager(prefs); // Controls Group group; int n; group = new Group(pageComposite, SWT.NONE); group.setText(Messages.REditorOptions_SmartInsert_label+':'); group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); n = 5; group.setLayout(LayoutUtil.applyGroupDefaults(new GridLayout(), n)); fSmartInsertControl = new Button(group, SWT.CHECK); fSmartInsertControl.setText(Messages.REditorOptions_SmartInsert_AsDefault_label); fSmartInsertControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, n, 1)); { final Link link = addLinkControl(group, Messages.REditorOptions_SmartInsert_description); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, n, 1); gd.widthHint = 300; link.setLayoutData(gd); } LayoutUtil.addGDDummy(group); LayoutUtil.addGDDummy(group); { Label label = new Label(group, SWT.CENTER); label.setText(Messages.REditorOptions_SmartInsert_ForEditor_header); label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); label = new Label(group, SWT.CENTER); label.setText(Messages.REditorOptions_SmartInsert_ForConsole_header); label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); } final Label dummy = new Label(group, SWT.NONE); dummy.setVisible(false); dummy.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 7)); fSmartInsertOnPasteControl = createOption(group, Messages.REditorOptions_SmartInsert_OnPaste_label, null, false); fSmartInsertCloseCurlyBracketsControl = createOption(group, Messages.REditorOptions_SmartInsert_CloseAuto_label, Messages.REditorOptions_SmartInsert_CloseCurly_label, true); fSmartInsertCloseRoundBracketsControl = createOption(group, null, Messages.REditorOptions_SmartInsert_CloseRound_label, true); fSmartInsertCloseSquareBracketsControl = createOption(group, null, Messages.REditorOptions_SmartInsert_CloseSquare_label, true); fSmartInsertCloseSpecialControl = createOption(group, null, Messages.REditorOptions_SmartInsert_ClosePercent_label, true); fSmartInsertCloseStringsControl = createOption(group, null, Messages.REditorOptions_SmartInsert_CloseString_label, true); // Code Folding LayoutUtil.addSmallFiller(pageComposite, false); { fFoldingEnableControl = new Button(pageComposite, SWT.CHECK); fFoldingEnableControl.setText(Messages.REditorOptions_Folding_Enable_label); fFoldingEnableControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); } final Composite foldingOptions = new Composite(pageComposite, SWT.NONE); { final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.horizontalIndent = LayoutUtil.defaultIndent(); foldingOptions.setLayoutData(gd); foldingOptions.setLayout(LayoutUtil.applyCompositeDefaults(new GridLayout(), 2)); } { fFoldingDefaultAllBlocksControl = new Button(foldingOptions, SWT.CHECK); fFoldingDefaultAllBlocksControl.setText(Messages.REditorOptions_Folding_EnableForAllBlocks_label); fFoldingDefaultAllBlocksControl.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); } { final Label label = new Label(foldingOptions, SWT.LEFT); final GridData gd = new GridData(SWT.FILL, SWT.CENTER, false, false); gd.horizontalIndent = LayoutUtil.defaultIndent(); label.setLayoutData(gd); label.setText(Messages.REditorOptions_Folding_MinNumOfLines_label); } { fFoldingDefaultMinLines = new Text(foldingOptions, SWT.SINGLE | SWT.BORDER); final GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, false); gd.widthHint = LayoutUtil.hintWidth(fFoldingDefaultMinLines, 2); fFoldingDefaultMinLines.setLayoutData(gd); } { fFoldingDefaultRoxygenControl = new Button(foldingOptions, SWT.CHECK); fFoldingDefaultRoxygenControl.setText(Messages.REditorOptions_Folding_EnableForRoxygen_label); fFoldingDefaultRoxygenControl.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); } { final Label label = new Label(foldingOptions, SWT.LEFT); final GridData gd = new GridData(SWT.FILL, SWT.CENTER, false, false); gd.horizontalIndent = LayoutUtil.defaultIndent(); label.setLayoutData(gd); label.setText(Messages.REditorOptions_Folding_MinNumOfLines_label); } { fFoldingDefaultRoxygenMinLines = new Text(foldingOptions, SWT.SINGLE | SWT.BORDER); final GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, false); gd.widthHint = LayoutUtil.hintWidth(fFoldingDefaultRoxygenMinLines, 2); fFoldingDefaultRoxygenMinLines.setLayoutData(gd); } { fFoldingDefaultRoxygenInitiallyControl = new Button(foldingOptions, SWT.CHECK); fFoldingDefaultRoxygenInitiallyControl.setText(Messages.REditorOptions_Folding_EnableForRoxygen_Initially_label); final GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); gd.horizontalIndent = LayoutUtil.defaultIndent(); fFoldingDefaultRoxygenInitiallyControl.setLayoutData(gd); } // Annotation LayoutUtil.addSmallFiller(pageComposite, false); { fMarkOccurrencesControl = new Button(pageComposite, SWT.CHECK); fMarkOccurrencesControl.setText(Messages.REditorOptions_MarkOccurrences_Enable_label); fMarkOccurrencesControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); final Link link = addLinkControl(pageComposite, Messages.REditorOptions_MarkOccurrences_Appearance_info); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.widthHint = 300; gd.horizontalIndent = LayoutUtil.defaultIndent(); link.setLayoutData(gd); } LayoutUtil.addSmallFiller(pageComposite, false); { fProblemsEnableControl = new Button(pageComposite, SWT.CHECK); fProblemsEnableControl.setText(Messages.REditorOptions_ProblemChecking_Enable_label); fProblemsEnableControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); } LayoutUtil.addSmallFiller(pageComposite, false); { fSpellEnableControl = new Button(pageComposite, SWT.CHECK); fSpellEnableControl.setText(Messages.REditorOptions_SpellChecking_Enable_label); fSpellEnableControl.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); final Link link = addLinkControl(pageComposite, Messages.REditorOptions_SpellChecking_note); final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); gd.widthHint = 300; gd.horizontalIndent = LayoutUtil.defaultIndent(); link.setLayoutData(gd); } // Binding initBindings(); updateControls(); }
diff --git a/detlef/src/net/x4a42/volksempfaenger/feedparser/FeedParser.java b/detlef/src/net/x4a42/volksempfaenger/feedparser/FeedParser.java index 521209d..efc9530 100644 --- a/detlef/src/net/x4a42/volksempfaenger/feedparser/FeedParser.java +++ b/detlef/src/net/x4a42/volksempfaenger/feedparser/FeedParser.java @@ -1,689 +1,693 @@ package net.x4a42.volksempfaenger.feedparser; import java.io.IOException; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.EmptyStackException; import java.util.Locale; import java.util.Stack; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import net.x4a42.volksempfaenger.Utils; import net.x4a42.volksempfaenger.feedparser.Enums.AtomRel; import net.x4a42.volksempfaenger.feedparser.Enums.Mime; import net.x4a42.volksempfaenger.feedparser.Enums.Namespace; import net.x4a42.volksempfaenger.feedparser.Enums.Tag; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class FeedParser { public static void parseEvented(Reader reader, FeedParserListener listener) throws FeedParserException, IOException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser; FeedHandler handler = new FeedHandler(listener); parser = factory.newSAXParser(); parser.parse(new InputSource(reader), handler); if (!handler.isFeed) { throw new NotAFeedException(); } } catch (ParserConfigurationException e) { throw new FeedParserException(e); } catch (SAXException e) { throw new FeedParserException(e); } catch (NullPointerException e) { throw new FeedParserException("NullPointerException inside Parser", e); } } public static Feed parse(Reader reader) throws FeedParserException, IOException { LegacyFeedParserListener listener = new LegacyFeedParserListener(); FeedParser.parseEvented(reader, listener); return listener.feed; } private static class LegacyFeedParserListener implements FeedParserListener { public Feed feed; private final ArrayList<FeedItem> feedItems = new ArrayList<FeedItem>(); private final ArrayList<Enclosure> enclosures = new ArrayList<Enclosure>(); @Override public void onFeedItem(FeedItem feedItem) { feedItems.add(feedItem); feedItem.enclosures.addAll(enclosures); enclosures.clear(); } @Override public void onFeed(Feed feed) { this.feed = feed; feed.items.addAll(feedItems); feedItems.clear(); } @Override public void onEnclosure(Enclosure enclosure) { enclosures.add(enclosure); } } private static class FeedHandler extends DefaultHandler { public boolean isFeed = false; private final Feed feed = new Feed(); private FeedItem feedItem = new FeedItem(); private Enclosure enclosure = new Enclosure(); private final Stack<Tag> parents = new Stack<Tag>(); private boolean skipMode = false; private boolean xhtmlMode = false; private boolean currentRssItemHasHtml = false; private boolean currentItemHasITunesSummaryAlternative = false; private boolean currentAtomItemHasPublished = false; private boolean hasITunesImage = false; private int skipDepth = 0; private final StringBuilder buffer = new StringBuilder(); private static final String ATOM_ATTR_HREF = "href"; private static final String ATOM_ATTR_REL = "rel"; private static final String ATOM_ATTR_TYPE = "type"; private static final String ATOM_ATTR_LENGTH = "length"; private static final String ATOM_ATTR_TITLE = "title"; private static final String RSS_ATTR_URL = "url"; private static final String RSS_ATTR_TYPE = "type"; private static final String RSS_ATTR_LENGTH = "length"; private final FeedParserListener listener; public FeedHandler(FeedParserListener listener) { super(); this.listener = listener; } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (skipMode) { skipDepth++; } else { Namespace ns = getNamespace(uri); Tag tag = getTag(ns, localName); if (!isFeed) { // is current element one of the toplevel elements if (((ns == Namespace.ATOM) && tag == Tag.ATOM_FEED) || ((ns == Namespace.NONE) && tag == Tag.RSS_TOPLEVEL) || ((ns == Namespace.RSS) && tag == Tag.RSS_TOPLEVEL)) { isFeed = true; } } if (ns == Namespace.ATOM) { onStartTagAtom(tag, atts); } else if (ns == Namespace.NONE || ns == Namespace.RSS || ns == Namespace.RSS_CONTENT) { onStartTagRss(tag, atts); } else if (ns == Namespace.XHTML && xhtmlMode) { onStartTagXHtml(localName, atts); } else if (ns == Namespace.ITUNES) { onStartTagITunes(tag, atts); } else { skipMode = true; skipDepth = 0; return; } parents.push(tag); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (skipMode) { return; } if (!safePeek(Tag.UNKNOWN) || xhtmlMode) { if (safePeek(Tag.RSS_DESCRIPTION) && currentRssItemHasHtml) { // we already have an HTML version of this, so just ignore // the plaintext return; } buffer.append(ch, start, length); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (skipMode) { if (skipDepth == 0) { skipMode = false; } else { skipDepth--; } } else { Namespace ns = getNamespace(uri); Tag tag; try { tag = parents.pop(); } catch (EmptyStackException e) { return; } if (ns == Namespace.ATOM) { onEndTagAtom(tag); } else if (ns == Namespace.NONE || ns == Namespace.RSS || ns == Namespace.RSS_CONTENT) { onEndTagRss(tag); } else if (ns == Namespace.XHTML && xhtmlMode) { onEndTagXHtml(localName); } else if (ns == Namespace.ITUNES) { onEndTagITunes(tag); } if (tag != Tag.UNKNOWN) { // clear buffer buffer.setLength(0); } } } private void onStartTagAtom(Tag tag, Attributes atts) { switch (tag) { case ATOM_ENTRY: feedItem = new FeedItem(); feedItem.feed = feed; currentItemHasITunesSummaryAlternative = false; currentAtomItemHasPublished = false; break; case ATOM_CONTENT: if (atts.getValue(ATOM_ATTR_TYPE).equals("xhtml")) { xhtmlMode = true; } case ATOM_LINK: String relString = atts.getValue(ATOM_ATTR_REL); AtomRel rel = AtomRel.UNKNOWN; if (relString != null) { rel = getAtomRel(relString); relString = null; } switch (rel) { case ENCLOSURE: if (safePeek(Tag.ATOM_ENTRY)) { enclosure = new Enclosure(); enclosure.feedItem = feedItem; enclosure.url = atts.getValue(ATOM_ATTR_HREF); enclosure.mime = atts.getValue(ATOM_ATTR_TYPE); enclosure.title = atts.getValue(ATOM_ATTR_TITLE); String length = atts.getValue(ATOM_ATTR_LENGTH); enclosure.size = safeParseLong(length); onEnclosure(); } break; case ALTERNATE: String mimeString = atts.getValue(ATOM_ATTR_TYPE); Mime type = Mime.UNKNOWN; if (mimeString != null) { type = getMime(mimeString); mimeString = null; } if (safePeek(Tag.ATOM_ENTRY)) { if (type == Mime.UNKNOWN || type == Mime.HTML || type == Mime.XHTML) { // actually there can be multiple // "alternate links" // this uses the LAST alternate link as the // URL for // the FeedItem feedItem.url = atts.getValue(ATOM_ATTR_HREF); } } else if (safePeek(Tag.ATOM_FEED)) { if (type == Mime.UNKNOWN || type == Mime.HTML || type == Mime.XHTML) { // same issue as above with multiple // alternate links feed.website = atts.getValue(ATOM_ATTR_HREF); } } break; case SELF: - if (safePeek(Tag.ATOM_FEED)) { + // I changed the tag below from Tag.ATOM_FEED to + // Tag.RSS_CHANNEL. + // I think this fixes an upstream bug: + // http://volksempfaenger.0x4a42.net/dev/ticket/216 + if (safePeek(Tag.RSS_CHANNEL)) { feed.url = atts.getValue(ATOM_ATTR_HREF); } break; case PAYMENT: if (safePeek(Tag.ATOM_ENTRY) || safePeek(Tag.RSS_ITEM)) { String url = atts.getValue(ATOM_ATTR_HREF); try { if (new URL(url).getHost().equals("flattr.com")) { feedItem.flattrUrl = url; } } catch (MalformedURLException e) { // ignore if url is malformed } } break; default: break; } break; default: break; } } private void onStartTagRss(Tag tag, Attributes atts) { switch (tag) { case RSS_ITEM: feedItem = new FeedItem(); feedItem.feed = feed; currentRssItemHasHtml = false; currentItemHasITunesSummaryAlternative = false; break; case RSS_ENCLOSURE: if (safePeek(Tag.RSS_ITEM)) { enclosure = new Enclosure(); enclosure.feedItem = feedItem; enclosure.url = atts.getValue(RSS_ATTR_URL); enclosure.mime = atts.getValue(RSS_ATTR_TYPE); String length = atts.getValue(RSS_ATTR_LENGTH); enclosure.size = safeParseLong(length); onEnclosure(); } break; default: break; } } private void onStartTagXHtml(String name, Attributes atts) { buffer.append("<"); buffer.append(name); for (int i = 0; i < atts.getLength(); i++) { buffer.append(" "); buffer.append(atts.getLocalName(i)); buffer.append("=\""); // escape double quotes (hope this works) buffer.append(atts.getValue(i).replaceAll("\"", "\\\"")); buffer.append("\""); } buffer.append(">"); } private void onStartTagITunes(Tag tag, Attributes atts) { if (tag == Tag.ITUNES_IMAGE && (safePeek(Tag.RSS_CHANNEL) || safePeek(Tag.ATOM_FEED))) { feed.image = atts.getValue("href"); hasITunesImage = true; } } private void onEndTagAtom(Tag tag) { switch (tag) { case ATOM_TITLE: if (safePeek(Tag.ATOM_FEED)) { // feed title feed.title = Utils.trimmedString(buffer); } else if (safePeek(Tag.ATOM_ENTRY)) { // entry title feedItem.title = Utils.trimmedString(buffer); } break; case ATOM_CONTENT: if (xhtmlMode) { xhtmlMode = false; } if (safePeek(Tag.ATOM_ENTRY)) { feedItem.description = Utils.trimmedString(buffer); currentItemHasITunesSummaryAlternative = true; } break; case ATOM_PUBLISHED: if (safePeek(Tag.ATOM_ENTRY)) { try { feedItem.date = parseAtomDate(buffer.toString()); currentAtomItemHasPublished = true; } catch (IndexOutOfBoundsException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; case ATOM_UPDATED: if (safePeek(Tag.ATOM_ENTRY) && !currentAtomItemHasPublished) { try { feedItem.date = parseAtomDate(buffer.toString()); } catch (IndexOutOfBoundsException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; case ATOM_SUBTITLE: feed.description = Utils.trimmedString(buffer); break; case ATOM_ENTRY: onFeedItem(); break; case ATOM_ID: if (safePeek(Tag.ATOM_ENTRY)) { feedItem.itemId = Utils.trimmedString(buffer); } break; case ATOM_ICON: if (safePeek(Tag.ATOM_FEED) && !hasITunesImage) { feed.image = Utils.trimmedString(buffer); } break; case ATOM_FEED: onFeed(); break; default: break; } } private void onEndTagRss(Tag tag) { switch (tag) { case RSS_TITLE: if (safePeek(Tag.RSS_CHANNEL)) { feed.title = Utils.trimmedString(buffer); } else if (safePeek(Tag.RSS_ITEM)) { feedItem.title = Utils.trimmedString(buffer); } break; case RSS_PUB_DATE: if (safePeek(Tag.RSS_ITEM)) { try { feedItem.date = parseRssDate(buffer.toString()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; case RSS_LINK: if (safePeek(Tag.RSS_ITEM)) { feedItem.url = Utils.trimmedString(buffer); } else if (safePeek(Tag.RSS_CHANNEL)) { feed.website = Utils.trimmedString(buffer); } break; case RSS_DESCRIPTION: if (!currentRssItemHasHtml) { if (safePeek(Tag.RSS_ITEM)) { feedItem.description = Utils.trimmedString(buffer); currentItemHasITunesSummaryAlternative = true; } else if (safePeek(Tag.RSS_CHANNEL)) { feed.description = Utils.trimmedString(buffer); } } break; case RSS_CONTENT_ENCODED: currentRssItemHasHtml = true; if (safePeek(Tag.RSS_ITEM)) { feedItem.description = Utils.trimmedString(buffer); currentItemHasITunesSummaryAlternative = true; } else if (safePeek(Tag.RSS_CHANNEL)) { feed.description = Utils.trimmedString(buffer); } break; case RSS_ITEM: onFeedItem(); currentRssItemHasHtml = false; break; case RSS_GUID: if (safePeek(Tag.RSS_ITEM)) { feedItem.itemId = Utils.trimmedString(buffer); } break; case RSS_URL: if (safePeek(Tag.RSS_IMAGE) && !hasITunesImage) { Tag copy; try { copy = parents.pop(); } catch (EmptyStackException e) { return; } if (safePeek(Tag.RSS_CHANNEL)) { feed.image = Utils.trimmedString(buffer); } parents.push(copy); } case RSS_CHANNEL: onFeed(); break; default: break; } } private void onEndTagXHtml(String name) { buffer.append("</"); buffer.append(name); buffer.append(">"); } private void onEndTagITunes(Tag tag) { if (tag == Tag.ITUNES_SUMMARY && (safePeek(Tag.ATOM_ENTRY) || safePeek(Tag.RSS_ITEM)) && !currentItemHasITunesSummaryAlternative) { feedItem.description = Utils.trimmedString(buffer); } } private Date parseAtomDate(String datestring) throws java.text.ParseException, IndexOutOfBoundsException { datestring = datestring.trim().toUpperCase(Locale.getDefault()); // dirty version - write a new one TODO // Modified version of http://cokere.com/RFC3339Date.txt /* * I was working on an Atom (http://www.w3.org/2005/Atom) parser and * discovered that I could not parse dates in the format defined by * RFC 3339 using the SimpleDateFormat class. The reason was the ':' * in the time zone. This code strips out the colon if it's there * and tries four different formats on the resulting string * depending on if it has a time zone, or if it has a fractional * second part. There is a probably a better way to do this, and a * more proper way. But this is a really small addition to a * codebase (You don't need a jar, just throw this function in some * static Utility class if you have one). * * Feel free to use this in your code, but I'd appreciate it if you * keep this note in the code if you distribute it. Thanks! * * For people who might be googling: The date format parsed by this * goes by: atomDateConstruct, xsd:dateTime, RFC3339 and is * compatable with: ISO.8601.1988, W3C.NOTE-datetime-19980827 and * W3C.REC-xmlschema-2-20041028 (that I know of) * * * Copyright 2007, Chad Okere (ceothrow1 at gmail dotcom) OMG NO * WARRENTY EXPRESSED OR IMPLIED!!!1 */ // if there is no time zone, we don't need to do any special // parsing. if (datestring.charAt(datestring.length() - 1) == 'Z') { try { // spec for RFC3339 return formats[4].parse(datestring); } catch (java.text.ParseException pe) { // try again with optional decimals // spec for RFC3339 (with fractional seconds) return formats[5].parse(datestring); } } // step one, split off the timezone. String firstpart = datestring.substring(0, datestring.lastIndexOf('-')); String secondpart = datestring.substring(datestring .lastIndexOf('-')); // step two, remove the colon from the timezone offset secondpart = secondpart.substring(0, secondpart.indexOf(':')) + secondpart.substring(secondpart.indexOf(':') + 1); datestring = firstpart + secondpart; try { return formats[6].parse(datestring);// spec for RFC3339 } catch (java.text.ParseException pe) { // try again with optional decimals // spec for RFC3339 (with fractional seconds) return formats[7].parse(datestring); } } private static final SimpleDateFormat formats[] = new SimpleDateFormat[] { new SimpleDateFormat("d MMM yy HH:mm z", Locale.US), new SimpleDateFormat("d MMM yy HH:mm:ss z", Locale.US), new SimpleDateFormat("d MMM yyyy HH:mm z", Locale.US), new SimpleDateFormat("d MMM yyyy HH:mm:ss z", Locale.US), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", Locale.US), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ", Locale.US) }; static { formats[5].setLenient(true); formats[7].setLenient(true); } private Date parseRssDate(String datestring) throws ParseException { // dirty version - write a new one TODO SimpleDateFormat format; int commaPos = datestring.indexOf(','); if (commaPos > -1) { // remove weekday if present datestring = datestring.substring(commaPos + 1); } datestring = datestring.trim(); if (datestring.length() > 8 && datestring.charAt(8) == ' ') { if (datestring.length() > 16 && datestring.charAt(14) == ' ') { format = formats[0]; } else { format = formats[1]; } } else { if (datestring.length() > 16 && datestring.charAt(16) == ' ') { format = formats[2]; } else { format = formats[3]; } } return format.parse(datestring); } private static Namespace getNamespace(String nsString) { return StringLookup.lookupNamespace(nsString); } private static Tag getTag(Namespace ns, String tagString) { switch (ns) { case ATOM: return StringLookup.lookupAtomTag(tagString); case RSS: case NONE: return StringLookup.lookupRssTag(tagString); case RSS_CONTENT: if (tagString.equals("encoded")) { return Tag.RSS_CONTENT_ENCODED; } else { return Tag.UNKNOWN; } case ITUNES: return StringLookup.lookupITunesTag(tagString); default: return Tag.UNKNOWN; } } private static AtomRel getAtomRel(String relString) { return StringLookup.lookupAtomRel(relString); } private static Mime getMime(String mimeString) { return StringLookup.lookupMime(mimeString); } private void onEnclosure() { listener.onEnclosure(enclosure); } private void onFeedItem() { if (feedItem.itemId == null) { if (feedItem.url != null) { feedItem.itemId = feedItem.url; } else if (feedItem.title != null) { feedItem.itemId = feedItem.title; } else { return; } } if (feedItem.date == null) { return; } listener.onFeedItem(feedItem); } private void onFeed() { listener.onFeed(feed); } private long safeParseLong(String number) { if (number != null) { try { return Long.parseLong(number.trim()); } catch (NumberFormatException e) { return 0; } } return 0; } private boolean safePeek(Tag tag) { try { Tag parent = parents.peek(); if (tag == parent) { return true; } else { return false; } } catch (EmptyStackException e) { return false; } } } }
true
true
private void onStartTagAtom(Tag tag, Attributes atts) { switch (tag) { case ATOM_ENTRY: feedItem = new FeedItem(); feedItem.feed = feed; currentItemHasITunesSummaryAlternative = false; currentAtomItemHasPublished = false; break; case ATOM_CONTENT: if (atts.getValue(ATOM_ATTR_TYPE).equals("xhtml")) { xhtmlMode = true; } case ATOM_LINK: String relString = atts.getValue(ATOM_ATTR_REL); AtomRel rel = AtomRel.UNKNOWN; if (relString != null) { rel = getAtomRel(relString); relString = null; } switch (rel) { case ENCLOSURE: if (safePeek(Tag.ATOM_ENTRY)) { enclosure = new Enclosure(); enclosure.feedItem = feedItem; enclosure.url = atts.getValue(ATOM_ATTR_HREF); enclosure.mime = atts.getValue(ATOM_ATTR_TYPE); enclosure.title = atts.getValue(ATOM_ATTR_TITLE); String length = atts.getValue(ATOM_ATTR_LENGTH); enclosure.size = safeParseLong(length); onEnclosure(); } break; case ALTERNATE: String mimeString = atts.getValue(ATOM_ATTR_TYPE); Mime type = Mime.UNKNOWN; if (mimeString != null) { type = getMime(mimeString); mimeString = null; } if (safePeek(Tag.ATOM_ENTRY)) { if (type == Mime.UNKNOWN || type == Mime.HTML || type == Mime.XHTML) { // actually there can be multiple // "alternate links" // this uses the LAST alternate link as the // URL for // the FeedItem feedItem.url = atts.getValue(ATOM_ATTR_HREF); } } else if (safePeek(Tag.ATOM_FEED)) { if (type == Mime.UNKNOWN || type == Mime.HTML || type == Mime.XHTML) { // same issue as above with multiple // alternate links feed.website = atts.getValue(ATOM_ATTR_HREF); } } break; case SELF: if (safePeek(Tag.ATOM_FEED)) { feed.url = atts.getValue(ATOM_ATTR_HREF); } break; case PAYMENT: if (safePeek(Tag.ATOM_ENTRY) || safePeek(Tag.RSS_ITEM)) { String url = atts.getValue(ATOM_ATTR_HREF); try { if (new URL(url).getHost().equals("flattr.com")) { feedItem.flattrUrl = url; } } catch (MalformedURLException e) { // ignore if url is malformed } } break; default: break; } break; default: break; } }
private void onStartTagAtom(Tag tag, Attributes atts) { switch (tag) { case ATOM_ENTRY: feedItem = new FeedItem(); feedItem.feed = feed; currentItemHasITunesSummaryAlternative = false; currentAtomItemHasPublished = false; break; case ATOM_CONTENT: if (atts.getValue(ATOM_ATTR_TYPE).equals("xhtml")) { xhtmlMode = true; } case ATOM_LINK: String relString = atts.getValue(ATOM_ATTR_REL); AtomRel rel = AtomRel.UNKNOWN; if (relString != null) { rel = getAtomRel(relString); relString = null; } switch (rel) { case ENCLOSURE: if (safePeek(Tag.ATOM_ENTRY)) { enclosure = new Enclosure(); enclosure.feedItem = feedItem; enclosure.url = atts.getValue(ATOM_ATTR_HREF); enclosure.mime = atts.getValue(ATOM_ATTR_TYPE); enclosure.title = atts.getValue(ATOM_ATTR_TITLE); String length = atts.getValue(ATOM_ATTR_LENGTH); enclosure.size = safeParseLong(length); onEnclosure(); } break; case ALTERNATE: String mimeString = atts.getValue(ATOM_ATTR_TYPE); Mime type = Mime.UNKNOWN; if (mimeString != null) { type = getMime(mimeString); mimeString = null; } if (safePeek(Tag.ATOM_ENTRY)) { if (type == Mime.UNKNOWN || type == Mime.HTML || type == Mime.XHTML) { // actually there can be multiple // "alternate links" // this uses the LAST alternate link as the // URL for // the FeedItem feedItem.url = atts.getValue(ATOM_ATTR_HREF); } } else if (safePeek(Tag.ATOM_FEED)) { if (type == Mime.UNKNOWN || type == Mime.HTML || type == Mime.XHTML) { // same issue as above with multiple // alternate links feed.website = atts.getValue(ATOM_ATTR_HREF); } } break; case SELF: // I changed the tag below from Tag.ATOM_FEED to // Tag.RSS_CHANNEL. // I think this fixes an upstream bug: // http://volksempfaenger.0x4a42.net/dev/ticket/216 if (safePeek(Tag.RSS_CHANNEL)) { feed.url = atts.getValue(ATOM_ATTR_HREF); } break; case PAYMENT: if (safePeek(Tag.ATOM_ENTRY) || safePeek(Tag.RSS_ITEM)) { String url = atts.getValue(ATOM_ATTR_HREF); try { if (new URL(url).getHost().equals("flattr.com")) { feedItem.flattrUrl = url; } } catch (MalformedURLException e) { // ignore if url is malformed } } break; default: break; } break; default: break; } }
diff --git a/src/gui/MakeOfferListener.java b/src/gui/MakeOfferListener.java index f6bbc61..cf92356 100644 --- a/src/gui/MakeOfferListener.java +++ b/src/gui/MakeOfferListener.java @@ -1,49 +1,52 @@ package gui; import java.awt.Container; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JOptionPane; import app.Command; public class MakeOfferListener extends MouseAdapter { private Command comm; private int row, index; private Container parent; public MakeOfferListener(Command comm, int row, int index, Container parent) { super(); this.comm = comm; this.row = row; this.index = index; } private void errorDialog() { JOptionPane.showMessageDialog(parent, "Incorrect price! Aborting.", "Make offer error", JOptionPane.PLAIN_MESSAGE); } public void mousePressed(MouseEvent e) { String price = JOptionPane.showInputDialog(parent,"Enter the price:", -1); if (price == null) return; if (!price.equals("")) { try { int offerredPrice = Integer.parseInt(price); - comm.execute(row, offerredPrice, index); + if (offerredPrice < 0) + errorDialog(); + else + comm.execute(row, offerredPrice, index); } catch(java.lang.NumberFormatException exc) { exc.printStackTrace(); errorDialog(); } } else errorDialog(); } }
true
true
public void mousePressed(MouseEvent e) { String price = JOptionPane.showInputDialog(parent,"Enter the price:", -1); if (price == null) return; if (!price.equals("")) { try { int offerredPrice = Integer.parseInt(price); comm.execute(row, offerredPrice, index); } catch(java.lang.NumberFormatException exc) { exc.printStackTrace(); errorDialog(); } } else errorDialog(); }
public void mousePressed(MouseEvent e) { String price = JOptionPane.showInputDialog(parent,"Enter the price:", -1); if (price == null) return; if (!price.equals("")) { try { int offerredPrice = Integer.parseInt(price); if (offerredPrice < 0) errorDialog(); else comm.execute(row, offerredPrice, index); } catch(java.lang.NumberFormatException exc) { exc.printStackTrace(); errorDialog(); } } else errorDialog(); }
diff --git a/sample/hello/flash/src/playn/sample/hello/flash/HelloGameFlash.java b/sample/hello/flash/src/playn/sample/hello/flash/HelloGameFlash.java index b3d5ee5d..682a5452 100644 --- a/sample/hello/flash/src/playn/sample/hello/flash/HelloGameFlash.java +++ b/sample/hello/flash/src/playn/sample/hello/flash/HelloGameFlash.java @@ -1,32 +1,32 @@ /** * Copyright 2010 The PlayN 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 playn.sample.hello.flash; import playn.core.PlayN; import playn.flash.FlashAssetManager; import playn.flash.FlashGame; import playn.flash.FlashPlatform; import playn.sample.hello.core.HelloGame; public class HelloGameFlash extends FlashGame { @Override public void start() { FlashAssetManager assets = FlashPlatform.register().assetManager(); - assets.setPathPrefix("hellogame/"); + assets.setPathPrefix("hellogameflash/"); PlayN.run(new HelloGame()); } }
true
true
public void start() { FlashAssetManager assets = FlashPlatform.register().assetManager(); assets.setPathPrefix("hellogame/"); PlayN.run(new HelloGame()); }
public void start() { FlashAssetManager assets = FlashPlatform.register().assetManager(); assets.setPathPrefix("hellogameflash/"); PlayN.run(new HelloGame()); }
diff --git a/wasync/src/main/java/org/atmosphere/wasync/impl/DefaultFuture.java b/wasync/src/main/java/org/atmosphere/wasync/impl/DefaultFuture.java index e103fe3..28256fc 100644 --- a/wasync/src/main/java/org/atmosphere/wasync/impl/DefaultFuture.java +++ b/wasync/src/main/java/org/atmosphere/wasync/impl/DefaultFuture.java @@ -1,119 +1,119 @@ /* * Copyright 2013 Jeanfrancois Arcand * * 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.atmosphere.wasync.impl; import org.atmosphere.wasync.Future; import org.atmosphere.wasync.Socket; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; public class DefaultFuture implements Future { private final DefaultSocket socket; private CountDownLatch latch = new CountDownLatch(1); private final AtomicBoolean done = new AtomicBoolean(false); protected long time = -1; protected TimeUnit tu; protected TimeoutException te = null; public DefaultFuture(DefaultSocket socket) { this.socket = socket; } /** * {@inheritDoc} */ @Override public boolean cancel(boolean mayInterruptIfRunning) { latch.countDown(); return true; } /** * {@inheritDoc} */ @Override public boolean isCancelled() { return latch.getCount() == 0; } /** * {@inheritDoc} */ @Override public boolean isDone() { return done.get(); } // TODO: Not public /** * {@inheritDoc} */ @Override public Future done(){ done.set(true); latch.countDown(); return this; } protected void reset(){ done.set(false); latch = new CountDownLatch(1); } /** * {@inheritDoc} */ @Override public Socket get() throws InterruptedException, ExecutionException { latch.await(); return socket; } /** * {@inheritDoc} */ @Override public Socket get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { time = timeout; tu = unit; if (!latch.await(timeout, unit) || te != null) { - throw te; + throw te == null ? new TimeoutException() : te; } return socket; } protected Socket socket() { return socket; } /** * {@inheritDoc} */ @Override public Future fire(Object data) throws IOException { reset(); socket.internalSocket().write(socket.request(), data); return this; } }
true
true
public Socket get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { time = timeout; tu = unit; if (!latch.await(timeout, unit) || te != null) { throw te; } return socket; }
public Socket get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { time = timeout; tu = unit; if (!latch.await(timeout, unit) || te != null) { throw te == null ? new TimeoutException() : te; } return socket; }
diff --git a/sql12/app/src/net/sourceforge/squirrel_sql/client/plugin/PluginSummaryDialog.java b/sql12/app/src/net/sourceforge/squirrel_sql/client/plugin/PluginSummaryDialog.java index 0dc86b94c..2e4370c7b 100755 --- a/sql12/app/src/net/sourceforge/squirrel_sql/client/plugin/PluginSummaryDialog.java +++ b/sql12/app/src/net/sourceforge/squirrel_sql/client/plugin/PluginSummaryDialog.java @@ -1,170 +1,172 @@ package net.sourceforge.squirrel_sql.client.plugin; /* * Copyright (C) 2001-2004 Colin Bell * [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.awt.BorderLayout; import java.awt.Container; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.event.TableModelEvent; import net.sourceforge.squirrel_sql.client.IApplication; import net.sourceforge.squirrel_sql.client.util.ApplicationFiles; import net.sourceforge.squirrel_sql.fw.datasetviewer.DataSetException; import net.sourceforge.squirrel_sql.fw.gui.GUIUtils; import net.sourceforge.squirrel_sql.fw.util.StringManager; import net.sourceforge.squirrel_sql.fw.util.StringManagerFactory; /** * This dialog displays a summary of all plugins. * * @author <A HREF="mailto:[email protected]">Colin Bell</A> */ public class PluginSummaryDialog extends JDialog { /** Internationalized strings for this class. */ private static final StringManager s_stringMgr = StringManagerFactory.getStringManager(PluginSummaryDialog.class); private final IApplication _app; private PluginSummaryTable _pluginPnl; static interface i18n { //i18n[PluginSummaryDialog.unload=Unload] String UNLOAD_LABEL = s_stringMgr.getString("PluginSummaryDialog.unload"); } public PluginSummaryDialog(IApplication app, Frame owner) throws DataSetException { super(owner, s_stringMgr.getString("PluginSummaryDialog.title")); _app = app; createGUI(); } private void saveSettings() { _app.getPluginManager().setPluginStatuses(_pluginPnl.getPluginStatus()); } private void createGUI() throws DataSetException { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // final SquirrelResources rsrc = _app.getResources(); // final ImageIcon icon = rsrc.getIcon(SquirrelResources.IImageNames.PLUGINS); // if (icon != null) // { // setIconImage(icon.getImage()); // } final Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); // Label containing the location of the plugins at top of dialog. final JLabel pluginLoc = new JLabel(s_stringMgr.getString("PluginSummaryDialog.pluginloc", new ApplicationFiles().getPluginsDirectory().getAbsolutePath())); pluginLoc.setBorder(BorderFactory.createEmptyBorder(1, 4, 1, 4)); contentPane.add(pluginLoc, BorderLayout.NORTH); // Table of loaded plugins in centre of dialog. final PluginManager pmgr = _app.getPluginManager(); final PluginInfo[] pluginInfo = pmgr.getPluginInformation(); final PluginStatus[] pluginStatus = pmgr.getPluginStatuses(); _pluginPnl = new PluginSummaryTable(_app, pluginInfo, pluginStatus); contentPane.add(new JScrollPane(_pluginPnl), BorderLayout.CENTER); final JPanel btnsPnl = new JPanel(); final JButton okBtn = new JButton(s_stringMgr.getString("PluginSummaryDialog.ok")); okBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveSettings(); dispose(); } }); btnsPnl.add(okBtn); final JButton unloadButton = new JButton(i18n.UNLOAD_LABEL); unloadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - int row = _pluginPnl.getSelectedRow(); - if (row == -1) { + int[] rows = _pluginPnl.getSelectedRows(); + if (rows.length == 0) { // no rows selected. return; } - // column 1 is internal name - String internalName = - (String)_pluginPnl.getModel().getValueAt(row, 1); - _app.getPluginManager().unloadPlugin(internalName); - // column 3 is loaded status - _pluginPnl.setValueAt("false", row, 3); + for (int row : rows) { + // column 1 is internal name + String internalName = + (String)_pluginPnl.getModel().getValueAt(row, 1); + _app.getPluginManager().unloadPlugin(internalName); + // column 3 is loaded status + _pluginPnl.setValueAt("false", row, 3); + } _pluginPnl.repaint(); } }); btnsPnl.add(unloadButton); final JButton closeBtn = new JButton(s_stringMgr.getString("PluginSummaryDialog.close")); closeBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { dispose(); } }); btnsPnl.add(closeBtn); contentPane.add(btnsPnl, BorderLayout.SOUTH); AbstractAction closeAction = new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { setVisible(false); dispose(); } }; KeyStroke escapeStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(escapeStroke, "CloseAction"); getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeStroke, "CloseAction"); getRootPane().getInputMap(JComponent.WHEN_FOCUSED).put(escapeStroke, "CloseAction"); getRootPane().getActionMap().put("CloseAction", closeAction); pack(); setSize(655, 500); GUIUtils.centerWithinParent(this); setResizable(true); } }
false
true
private void createGUI() throws DataSetException { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // final SquirrelResources rsrc = _app.getResources(); // final ImageIcon icon = rsrc.getIcon(SquirrelResources.IImageNames.PLUGINS); // if (icon != null) // { // setIconImage(icon.getImage()); // } final Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); // Label containing the location of the plugins at top of dialog. final JLabel pluginLoc = new JLabel(s_stringMgr.getString("PluginSummaryDialog.pluginloc", new ApplicationFiles().getPluginsDirectory().getAbsolutePath())); pluginLoc.setBorder(BorderFactory.createEmptyBorder(1, 4, 1, 4)); contentPane.add(pluginLoc, BorderLayout.NORTH); // Table of loaded plugins in centre of dialog. final PluginManager pmgr = _app.getPluginManager(); final PluginInfo[] pluginInfo = pmgr.getPluginInformation(); final PluginStatus[] pluginStatus = pmgr.getPluginStatuses(); _pluginPnl = new PluginSummaryTable(_app, pluginInfo, pluginStatus); contentPane.add(new JScrollPane(_pluginPnl), BorderLayout.CENTER); final JPanel btnsPnl = new JPanel(); final JButton okBtn = new JButton(s_stringMgr.getString("PluginSummaryDialog.ok")); okBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveSettings(); dispose(); } }); btnsPnl.add(okBtn); final JButton unloadButton = new JButton(i18n.UNLOAD_LABEL); unloadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { int row = _pluginPnl.getSelectedRow(); if (row == -1) { // no rows selected. return; } // column 1 is internal name String internalName = (String)_pluginPnl.getModel().getValueAt(row, 1); _app.getPluginManager().unloadPlugin(internalName); // column 3 is loaded status _pluginPnl.setValueAt("false", row, 3); _pluginPnl.repaint(); } }); btnsPnl.add(unloadButton); final JButton closeBtn = new JButton(s_stringMgr.getString("PluginSummaryDialog.close")); closeBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { dispose(); } }); btnsPnl.add(closeBtn); contentPane.add(btnsPnl, BorderLayout.SOUTH); AbstractAction closeAction = new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { setVisible(false); dispose(); } }; KeyStroke escapeStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(escapeStroke, "CloseAction"); getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeStroke, "CloseAction"); getRootPane().getInputMap(JComponent.WHEN_FOCUSED).put(escapeStroke, "CloseAction"); getRootPane().getActionMap().put("CloseAction", closeAction); pack(); setSize(655, 500); GUIUtils.centerWithinParent(this); setResizable(true); }
private void createGUI() throws DataSetException { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // final SquirrelResources rsrc = _app.getResources(); // final ImageIcon icon = rsrc.getIcon(SquirrelResources.IImageNames.PLUGINS); // if (icon != null) // { // setIconImage(icon.getImage()); // } final Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); // Label containing the location of the plugins at top of dialog. final JLabel pluginLoc = new JLabel(s_stringMgr.getString("PluginSummaryDialog.pluginloc", new ApplicationFiles().getPluginsDirectory().getAbsolutePath())); pluginLoc.setBorder(BorderFactory.createEmptyBorder(1, 4, 1, 4)); contentPane.add(pluginLoc, BorderLayout.NORTH); // Table of loaded plugins in centre of dialog. final PluginManager pmgr = _app.getPluginManager(); final PluginInfo[] pluginInfo = pmgr.getPluginInformation(); final PluginStatus[] pluginStatus = pmgr.getPluginStatuses(); _pluginPnl = new PluginSummaryTable(_app, pluginInfo, pluginStatus); contentPane.add(new JScrollPane(_pluginPnl), BorderLayout.CENTER); final JPanel btnsPnl = new JPanel(); final JButton okBtn = new JButton(s_stringMgr.getString("PluginSummaryDialog.ok")); okBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveSettings(); dispose(); } }); btnsPnl.add(okBtn); final JButton unloadButton = new JButton(i18n.UNLOAD_LABEL); unloadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { int[] rows = _pluginPnl.getSelectedRows(); if (rows.length == 0) { // no rows selected. return; } for (int row : rows) { // column 1 is internal name String internalName = (String)_pluginPnl.getModel().getValueAt(row, 1); _app.getPluginManager().unloadPlugin(internalName); // column 3 is loaded status _pluginPnl.setValueAt("false", row, 3); } _pluginPnl.repaint(); } }); btnsPnl.add(unloadButton); final JButton closeBtn = new JButton(s_stringMgr.getString("PluginSummaryDialog.close")); closeBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { dispose(); } }); btnsPnl.add(closeBtn); contentPane.add(btnsPnl, BorderLayout.SOUTH); AbstractAction closeAction = new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { setVisible(false); dispose(); } }; KeyStroke escapeStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(escapeStroke, "CloseAction"); getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeStroke, "CloseAction"); getRootPane().getInputMap(JComponent.WHEN_FOCUSED).put(escapeStroke, "CloseAction"); getRootPane().getActionMap().put("CloseAction", closeAction); pack(); setSize(655, 500); GUIUtils.centerWithinParent(this); setResizable(true); }
diff --git a/core/test/src/com/google/zxing/common/reedsolomon/ReedSolomonEncoderQRCodeTestCase.java b/core/test/src/com/google/zxing/common/reedsolomon/ReedSolomonEncoderQRCodeTestCase.java index 17f6d37a..2ed1856d 100644 --- a/core/test/src/com/google/zxing/common/reedsolomon/ReedSolomonEncoderQRCodeTestCase.java +++ b/core/test/src/com/google/zxing/common/reedsolomon/ReedSolomonEncoderQRCodeTestCase.java @@ -1,66 +1,67 @@ /* * Copyright 2008 ZXing 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 com.google.zxing.common.reedsolomon; import org.junit.Test; import java.util.Random; /** * @author Sean Owen */ public final class ReedSolomonEncoderQRCodeTestCase extends AbstractReedSolomonTestCase { /** * Tests example given in ISO 18004, Annex I */ @Test public void testISO18004Example() { int[] dataBytes = { 0x10, 0x20, 0x0C, 0x56, 0x61, 0x80, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11 }; int[] expectedECBytes = { 0xA5, 0x24, 0xD4, 0xC1, 0xED, 0x36, 0xC7, 0x87, 0x2C, 0x55 }; doTestQRCodeEncoding(dataBytes, expectedECBytes); } @Test public void testQRCodeVersusDecoder() throws Exception { Random random = getRandom(); ReedSolomonEncoder encoder = new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256); ReedSolomonDecoder decoder = new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256); for (int i = 0; i < 100; i++) { - int size = 1 + random.nextInt(1000); + int size = 2 + random.nextInt(254); int[] toEncode = new int[size]; int ecBytes = 1 + random.nextInt(2 * (1 + size / 8)); ecBytes = Math.min(ecBytes, size - 1); int dataBytes = size - ecBytes; for (int j = 0; j < dataBytes; j++) { toEncode[j] = random.nextInt(256); } int[] original = new int[dataBytes]; System.arraycopy(toEncode, 0, original, 0, dataBytes); encoder.encode(toEncode, ecBytes); + corrupt(toEncode, ecBytes / 2, random); decoder.decode(toEncode, ecBytes); assertArraysEqual(original, 0, toEncode, 0, dataBytes); } } // Need more tests I am sure }
false
true
public void testQRCodeVersusDecoder() throws Exception { Random random = getRandom(); ReedSolomonEncoder encoder = new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256); ReedSolomonDecoder decoder = new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256); for (int i = 0; i < 100; i++) { int size = 1 + random.nextInt(1000); int[] toEncode = new int[size]; int ecBytes = 1 + random.nextInt(2 * (1 + size / 8)); ecBytes = Math.min(ecBytes, size - 1); int dataBytes = size - ecBytes; for (int j = 0; j < dataBytes; j++) { toEncode[j] = random.nextInt(256); } int[] original = new int[dataBytes]; System.arraycopy(toEncode, 0, original, 0, dataBytes); encoder.encode(toEncode, ecBytes); decoder.decode(toEncode, ecBytes); assertArraysEqual(original, 0, toEncode, 0, dataBytes); } }
public void testQRCodeVersusDecoder() throws Exception { Random random = getRandom(); ReedSolomonEncoder encoder = new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256); ReedSolomonDecoder decoder = new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256); for (int i = 0; i < 100; i++) { int size = 2 + random.nextInt(254); int[] toEncode = new int[size]; int ecBytes = 1 + random.nextInt(2 * (1 + size / 8)); ecBytes = Math.min(ecBytes, size - 1); int dataBytes = size - ecBytes; for (int j = 0; j < dataBytes; j++) { toEncode[j] = random.nextInt(256); } int[] original = new int[dataBytes]; System.arraycopy(toEncode, 0, original, 0, dataBytes); encoder.encode(toEncode, ecBytes); corrupt(toEncode, ecBytes / 2, random); decoder.decode(toEncode, ecBytes); assertArraysEqual(original, 0, toEncode, 0, dataBytes); } }
diff --git a/scheduler-component-shared/src/java/org/sakaiproject/component/app/scheduler/jobs/SakaiEventArchiveJob.java b/scheduler-component-shared/src/java/org/sakaiproject/component/app/scheduler/jobs/SakaiEventArchiveJob.java index 4acca0a..ce8afc5 100644 --- a/scheduler-component-shared/src/java/org/sakaiproject/component/app/scheduler/jobs/SakaiEventArchiveJob.java +++ b/scheduler-component-shared/src/java/org/sakaiproject/component/app/scheduler/jobs/SakaiEventArchiveJob.java @@ -1,98 +1,102 @@ package org.sakaiproject.component.app.scheduler.jobs; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.Calendar; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.db.cover.SqlService; public class SakaiEventArchiveJob implements Job { private static final Log LOG = LogFactory.getLog(SakaiEventArchiveJob.class); // default is to move any events older than 24 hours private static final boolean ARCHIVE_ENABLED = true; private static final String DEFAULT_ARCHIVE_LENGTH = "86400000"; public void execute(JobExecutionContext arg0) throws JobExecutionException { boolean archiveEnabled = ServerConfigurationService.getBoolean("scheduler.event.archive.enabled", ARCHIVE_ENABLED); long archiveLength = Long.parseLong( ServerConfigurationService.getString("scheduler.event.archive.length", DEFAULT_ARCHIVE_LENGTH)); Connection sakaiConnection = null; PreparedStatement sakaiStatement = null; String sql; Timestamp archiveDate = new Timestamp(System.currentTimeMillis()- archiveLength); LOG.info("archiveDate="+archiveDate.toString()); // TODO: checkToSeeIfArchiveTablesExist(); // Make separate statements for HSQL, MySQL, Oracle try { sakaiConnection = SqlService.borrowConnection(); sakaiConnection.setAutoCommit(false); // move session entries older than <date> to archive table sql = "INSERT INTO SAKAI_SESSION_ARCHIVE (SELECT * FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?)"; LOG.info("sql="+sql); sakaiStatement = sakaiConnection.prepareStatement(sql); sakaiStatement.setTimestamp(1, archiveDate); sakaiStatement.execute(sql); sql = "DELETE FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?"; LOG.info("sql="+sql); //sakaiStatement = sakaiConnection.prepareStatement(sql); //sakaiStatement.setTimestamp(1, archiveDate); //sakaiStatement.execute(sql); sakaiConnection.commit(); // move events older than <date> to archive table sql = "INSERT INTO SAKAI_EVENT_ARCHIVE (SELECT * FROM SAKAI_EVENT WHERE EVENT_DATE < ?)"; LOG.info("sql="+sql); sakaiStatement = sakaiConnection.prepareStatement(sql); sakaiStatement.setTimestamp(1, archiveDate); sakaiStatement.execute(sql); sql = "DELETE FROM SAKAI_EVENT WHERE EVENT_DATE < ?"; LOG.info("sql="+sql); //sakaiStatement = sakaiConnection.prepareStatement(sql); //sakaiStatement.setTimestamp(1, archiveDate); //sakaiStatement.execute(sql); sakaiConnection.commit(); } catch (SQLException e) { LOG.error("SQLException: " +e); } finally { + try { + if(sakaiStatement != null) sakaiStatement.close(); + } catch (SQLException e) { + LOG.error("SQLException in finally block: " +e); + } try { - if(sakaiStatement != null) sakaiStatement.close(); if(sakaiConnection != null) SqlService.returnConnection(sakaiConnection); } catch (SQLException e) { LOG.error("SQLException in finally block: " +e); } } } }
false
true
public void execute(JobExecutionContext arg0) throws JobExecutionException { boolean archiveEnabled = ServerConfigurationService.getBoolean("scheduler.event.archive.enabled", ARCHIVE_ENABLED); long archiveLength = Long.parseLong( ServerConfigurationService.getString("scheduler.event.archive.length", DEFAULT_ARCHIVE_LENGTH)); Connection sakaiConnection = null; PreparedStatement sakaiStatement = null; String sql; Timestamp archiveDate = new Timestamp(System.currentTimeMillis()- archiveLength); LOG.info("archiveDate="+archiveDate.toString()); // TODO: checkToSeeIfArchiveTablesExist(); // Make separate statements for HSQL, MySQL, Oracle try { sakaiConnection = SqlService.borrowConnection(); sakaiConnection.setAutoCommit(false); // move session entries older than <date> to archive table sql = "INSERT INTO SAKAI_SESSION_ARCHIVE (SELECT * FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?)"; LOG.info("sql="+sql); sakaiStatement = sakaiConnection.prepareStatement(sql); sakaiStatement.setTimestamp(1, archiveDate); sakaiStatement.execute(sql); sql = "DELETE FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?"; LOG.info("sql="+sql); //sakaiStatement = sakaiConnection.prepareStatement(sql); //sakaiStatement.setTimestamp(1, archiveDate); //sakaiStatement.execute(sql); sakaiConnection.commit(); // move events older than <date> to archive table sql = "INSERT INTO SAKAI_EVENT_ARCHIVE (SELECT * FROM SAKAI_EVENT WHERE EVENT_DATE < ?)"; LOG.info("sql="+sql); sakaiStatement = sakaiConnection.prepareStatement(sql); sakaiStatement.setTimestamp(1, archiveDate); sakaiStatement.execute(sql); sql = "DELETE FROM SAKAI_EVENT WHERE EVENT_DATE < ?"; LOG.info("sql="+sql); //sakaiStatement = sakaiConnection.prepareStatement(sql); //sakaiStatement.setTimestamp(1, archiveDate); //sakaiStatement.execute(sql); sakaiConnection.commit(); } catch (SQLException e) { LOG.error("SQLException: " +e); } finally { try { if(sakaiStatement != null) sakaiStatement.close(); if(sakaiConnection != null) SqlService.returnConnection(sakaiConnection); } catch (SQLException e) { LOG.error("SQLException in finally block: " +e); } } }
public void execute(JobExecutionContext arg0) throws JobExecutionException { boolean archiveEnabled = ServerConfigurationService.getBoolean("scheduler.event.archive.enabled", ARCHIVE_ENABLED); long archiveLength = Long.parseLong( ServerConfigurationService.getString("scheduler.event.archive.length", DEFAULT_ARCHIVE_LENGTH)); Connection sakaiConnection = null; PreparedStatement sakaiStatement = null; String sql; Timestamp archiveDate = new Timestamp(System.currentTimeMillis()- archiveLength); LOG.info("archiveDate="+archiveDate.toString()); // TODO: checkToSeeIfArchiveTablesExist(); // Make separate statements for HSQL, MySQL, Oracle try { sakaiConnection = SqlService.borrowConnection(); sakaiConnection.setAutoCommit(false); // move session entries older than <date> to archive table sql = "INSERT INTO SAKAI_SESSION_ARCHIVE (SELECT * FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?)"; LOG.info("sql="+sql); sakaiStatement = sakaiConnection.prepareStatement(sql); sakaiStatement.setTimestamp(1, archiveDate); sakaiStatement.execute(sql); sql = "DELETE FROM SAKAI_SESSION WHERE SESSION_END IS NOT NULL AND SESSION_END < ?"; LOG.info("sql="+sql); //sakaiStatement = sakaiConnection.prepareStatement(sql); //sakaiStatement.setTimestamp(1, archiveDate); //sakaiStatement.execute(sql); sakaiConnection.commit(); // move events older than <date> to archive table sql = "INSERT INTO SAKAI_EVENT_ARCHIVE (SELECT * FROM SAKAI_EVENT WHERE EVENT_DATE < ?)"; LOG.info("sql="+sql); sakaiStatement = sakaiConnection.prepareStatement(sql); sakaiStatement.setTimestamp(1, archiveDate); sakaiStatement.execute(sql); sql = "DELETE FROM SAKAI_EVENT WHERE EVENT_DATE < ?"; LOG.info("sql="+sql); //sakaiStatement = sakaiConnection.prepareStatement(sql); //sakaiStatement.setTimestamp(1, archiveDate); //sakaiStatement.execute(sql); sakaiConnection.commit(); } catch (SQLException e) { LOG.error("SQLException: " +e); } finally { try { if(sakaiStatement != null) sakaiStatement.close(); } catch (SQLException e) { LOG.error("SQLException in finally block: " +e); } try { if(sakaiConnection != null) SqlService.returnConnection(sakaiConnection); } catch (SQLException e) { LOG.error("SQLException in finally block: " +e); } } }
diff --git a/src/me/shock/avatarpvp/EarthListener.java b/src/me/shock/avatarpvp/EarthListener.java index 8b40427..b392eb7 100644 --- a/src/me/shock/avatarpvp/EarthListener.java +++ b/src/me/shock/avatarpvp/EarthListener.java @@ -1,330 +1,332 @@ package me.shock.avatarpvp; import java.util.HashMap; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityTargetLivingEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class EarthListener implements Listener { public HashMap<String, Long> fortify = new HashMap<String, Long>(); public HashMap<String, Long> golem = new HashMap<String, Long>(); public Main plugin; public EarthListener(Main instance) { this.plugin = instance; } String apvp = ChatColor.BLUE + "[" + ChatColor.WHITE + "AvatarPvP" + ChatColor.BLUE + "]" + ChatColor.WHITE + ": "; /** * Listen to earth abilities. * Fortify - 5 seconds sphere protection. * Golem - summon a rock golem to protect you. */ @EventHandler public void earthInteract(PlayerInteractEvent event) { /** * Stuff we need for everything. * Set up cooldowns in seconds. */ long golemcool = 60; long fortifycool = 60; Player player = event.getPlayer(); Action action = event.getAction(); if(action == Action.LEFT_CLICK_BLOCK) { ItemStack itemStack = player.getItemInHand(); ItemMeta meta = itemStack.getItemMeta(); List<String> lore = meta.getLore(); if(lore.isEmpty()) { return; } /** * Check for lore of earth abilities added via commands. */ else { if(lore.contains(ChatColor.GREEN + "Fortify")) { // TODO: stuff for fortify here. } if(lore.contains(ChatColor.GREEN + "Golem")) { if(player.hasPermission("avatarpvp.earth.golem")) { // Check if the player has used the ability already. if(golem.containsKey(player.getName())) { long diff = (System.currentTimeMillis() - golem.get(player.getName())) / 1000; // Used it too recently. if(golemcool > diff) { player.sendMessage(apvp + "You must wait " + ChatColor.RED + (golemcool - diff) + ChatColor.WHITE + " before using this again."); } // Can use it again. else { Block clickedBlock = event.getClickedBlock(); Location loc = clickedBlock.getLocation(); loc.getWorld().spawnEntity(loc, EntityType.IRON_GOLEM); golem.remove(player.getName()); golem.put(player.getName(), System.currentTimeMillis()); player.sendMessage(apvp + "Spawned an iron golem to protect you."); } } // Player hasn't already used it. else { Block clickedBlock = event.getClickedBlock(); Location loc = clickedBlock.getLocation(); loc.getWorld().spawnEntity(loc, EntityType.IRON_GOLEM); golem.put(player.getName(), System.currentTimeMillis()); } } else { player.sendMessage(apvp + "You don't have permission to use this ability."); } } } } if(action == Action.LEFT_CLICK_AIR) { /** * Need to handle left click air so that way we get the location * of the player and not the clicked block so they don't spawn * the box on themselves. */ ItemStack itemStack = player.getItemInHand(); ItemMeta meta = itemStack.getItemMeta(); List<String> lore = meta.getLore(); if(lore.isEmpty()) { return; } if(lore.contains(ChatColor.GREEN + "Fortify")) { if(player.hasPermission("avatarpvp.earth.fortify")) { if(fortify.containsKey(player.getName())) { long diff = (System.currentTimeMillis() - golem.get(player.getName())) / 1000; // Used it too recently. if(fortifycool > diff) { player.sendMessage(apvp + "You must wait " + ChatColor.RED + (fortifycool - diff) + ChatColor.WHITE + " before using this again."); } // Can use the ability again. else { Location loc = player.getLocation(); Location loc1 = loc.add(2, -1, -2); Location loc2 = loc.add(2, -1, -1); Location loc3 = loc.add(2, -1, 0); Location loc4 = loc.add(2, -1, 1); Location loc5 = loc.add(2, -1, 1); Location loc6 = loc.add(-1, -1, 2); Location loc7 = loc.add(0, -1, 2); Location loc8 = loc.add(1, -1, 2); Location loc9 = loc.add(-2, -1, -2); Location loc10 = loc.add(-2, -1, -1); Location loc11 = loc.add(-2, -1, 0); Location loc12 = loc.add(-2, -1, 1); Location loc13 = loc.add(-2, -1, 2); Location loc14 = loc.add(-1, -1, -2); Location loc15 = loc.add(0, -1, -2); Location loc16 = loc.add(1, -1, -2); /** * Lets spawn some obsidian around the player. * Spawn it like this four blocks high: * 12345 * 6 6 * 5 P 7 * 4 8 * 32109 */ int count = 1; // Spawn the blocks for(count = 1; count < 4; count++) { Location locx1 = loc1.add(0, count, 0); Location locx2 = loc2.add(0, count, 0); Location locx3 = loc3.add(0, count, 0); Location locx4 = loc4.add(0, count, 0); Location locx5 = loc5.add(0, count, 0); Location locx6 = loc6.add(0, count, 0); Location locx7 = loc7.add(0, count, 0); Location locx8 = loc8.add(0, count, 0); Location locx9 = loc9.add(0, count, 0); Location locx10 = loc10.add(0, count, 0); Location locx11 = loc11.add(0, count, 0); Location locx12 = loc12.add(0, count, 0); Location locx13 = loc13.add(0, count, 0); Location locx14 = loc14.add(0, count, 0); Location locx15 = loc15.add(0, count, 0); Location locx16 = loc16.add(0, count, 0); loc.getWorld().spawnFallingBlock(locx1, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx2, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx3, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx4, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx5, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx6, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx7, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx8, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx9, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx10, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx11, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx12, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx13, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx14, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx15, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx16, Material.OBSIDIAN, (byte) 0); } player.sendMessage(apvp + "Obsidian fortification is protecting you."); + fortify.remove(player.getName()); + fortify.put(player.getName(), System.currentTimeMillis()); } } else { -Location loc = player.getLocation(); + Location loc = player.getLocation(); Location loc1 = loc.add(2, -1, -2); Location loc2 = loc.add(2, -1, -1); Location loc3 = loc.add(2, -1, 0); Location loc4 = loc.add(2, -1, 1); Location loc5 = loc.add(2, -1, 1); Location loc6 = loc.add(-1, -1, 2); Location loc7 = loc.add(0, -1, 2); Location loc8 = loc.add(1, -1, 2); Location loc9 = loc.add(-2, -1, -2); Location loc10 = loc.add(-2, -1, -1); Location loc11 = loc.add(-2, -1, 0); Location loc12 = loc.add(-2, -1, 1); Location loc13 = loc.add(-2, -1, 2); Location loc14 = loc.add(-1, -1, -2); Location loc15 = loc.add(0, -1, -2); Location loc16 = loc.add(1, -1, -2); /** * Lets spawn some obsidian around the player. * Spawn it like this four blocks high: * 12345 * 6 6 * 5 P 7 * 4 8 * 32109 */ int count = 1; // Spawn the blocks for(count = 1; count < 4; count++) { Location locx1 = loc1.add(0, count, 0); Location locx2 = loc2.add(0, count, 0); Location locx3 = loc3.add(0, count, 0); Location locx4 = loc4.add(0, count, 0); Location locx5 = loc5.add(0, count, 0); Location locx6 = loc6.add(0, count, 0); Location locx7 = loc7.add(0, count, 0); Location locx8 = loc8.add(0, count, 0); Location locx9 = loc9.add(0, count, 0); Location locx10 = loc10.add(0, count, 0); Location locx11 = loc11.add(0, count, 0); Location locx12 = loc12.add(0, count, 0); Location locx13 = loc13.add(0, count, 0); Location locx14 = loc14.add(0, count, 0); Location locx15 = loc15.add(0, count, 0); Location locx16 = loc16.add(0, count, 0); loc.getWorld().spawnFallingBlock(locx1, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx2, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx3, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx4, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx5, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx6, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx7, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx8, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx9, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx10, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx11, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx12, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx13, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx14, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx15, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx16, Material.OBSIDIAN, (byte) 0); } player.sendMessage(apvp + "Obsidian fortification is protecting you."); } } else { player.sendMessage(apvp + "You don't have permission to use this ability."); } } } // Everything must be above this. } /** * Get the iron golem spawned then * make it so it doesn't attack anyone else. */ @EventHandler public void onGolemTarget(EntityTargetLivingEntityEvent event) { EntityType type = event.getEntityType(); if(type == EntityType.IRON_GOLEM) { LivingEntity entityTarget = event.getTarget(); if(entityTarget instanceof Player) { Player player = (Player) entityTarget; if(player.hasPermission("avatarpvp.earth")) { event.setCancelled(true); } } return; } return; } }
false
true
public void earthInteract(PlayerInteractEvent event) { /** * Stuff we need for everything. * Set up cooldowns in seconds. */ long golemcool = 60; long fortifycool = 60; Player player = event.getPlayer(); Action action = event.getAction(); if(action == Action.LEFT_CLICK_BLOCK) { ItemStack itemStack = player.getItemInHand(); ItemMeta meta = itemStack.getItemMeta(); List<String> lore = meta.getLore(); if(lore.isEmpty()) { return; } /** * Check for lore of earth abilities added via commands. */ else { if(lore.contains(ChatColor.GREEN + "Fortify")) { // TODO: stuff for fortify here. } if(lore.contains(ChatColor.GREEN + "Golem")) { if(player.hasPermission("avatarpvp.earth.golem")) { // Check if the player has used the ability already. if(golem.containsKey(player.getName())) { long diff = (System.currentTimeMillis() - golem.get(player.getName())) / 1000; // Used it too recently. if(golemcool > diff) { player.sendMessage(apvp + "You must wait " + ChatColor.RED + (golemcool - diff) + ChatColor.WHITE + " before using this again."); } // Can use it again. else { Block clickedBlock = event.getClickedBlock(); Location loc = clickedBlock.getLocation(); loc.getWorld().spawnEntity(loc, EntityType.IRON_GOLEM); golem.remove(player.getName()); golem.put(player.getName(), System.currentTimeMillis()); player.sendMessage(apvp + "Spawned an iron golem to protect you."); } } // Player hasn't already used it. else { Block clickedBlock = event.getClickedBlock(); Location loc = clickedBlock.getLocation(); loc.getWorld().spawnEntity(loc, EntityType.IRON_GOLEM); golem.put(player.getName(), System.currentTimeMillis()); } } else { player.sendMessage(apvp + "You don't have permission to use this ability."); } } } } if(action == Action.LEFT_CLICK_AIR) { /** * Need to handle left click air so that way we get the location * of the player and not the clicked block so they don't spawn * the box on themselves. */ ItemStack itemStack = player.getItemInHand(); ItemMeta meta = itemStack.getItemMeta(); List<String> lore = meta.getLore(); if(lore.isEmpty()) { return; } if(lore.contains(ChatColor.GREEN + "Fortify")) { if(player.hasPermission("avatarpvp.earth.fortify")) { if(fortify.containsKey(player.getName())) { long diff = (System.currentTimeMillis() - golem.get(player.getName())) / 1000; // Used it too recently. if(fortifycool > diff) { player.sendMessage(apvp + "You must wait " + ChatColor.RED + (fortifycool - diff) + ChatColor.WHITE + " before using this again."); } // Can use the ability again. else { Location loc = player.getLocation(); Location loc1 = loc.add(2, -1, -2); Location loc2 = loc.add(2, -1, -1); Location loc3 = loc.add(2, -1, 0); Location loc4 = loc.add(2, -1, 1); Location loc5 = loc.add(2, -1, 1); Location loc6 = loc.add(-1, -1, 2); Location loc7 = loc.add(0, -1, 2); Location loc8 = loc.add(1, -1, 2); Location loc9 = loc.add(-2, -1, -2); Location loc10 = loc.add(-2, -1, -1); Location loc11 = loc.add(-2, -1, 0); Location loc12 = loc.add(-2, -1, 1); Location loc13 = loc.add(-2, -1, 2); Location loc14 = loc.add(-1, -1, -2); Location loc15 = loc.add(0, -1, -2); Location loc16 = loc.add(1, -1, -2); /** * Lets spawn some obsidian around the player. * Spawn it like this four blocks high: * 12345 * 6 6 * 5 P 7 * 4 8 * 32109 */ int count = 1; // Spawn the blocks for(count = 1; count < 4; count++) { Location locx1 = loc1.add(0, count, 0); Location locx2 = loc2.add(0, count, 0); Location locx3 = loc3.add(0, count, 0); Location locx4 = loc4.add(0, count, 0); Location locx5 = loc5.add(0, count, 0); Location locx6 = loc6.add(0, count, 0); Location locx7 = loc7.add(0, count, 0); Location locx8 = loc8.add(0, count, 0); Location locx9 = loc9.add(0, count, 0); Location locx10 = loc10.add(0, count, 0); Location locx11 = loc11.add(0, count, 0); Location locx12 = loc12.add(0, count, 0); Location locx13 = loc13.add(0, count, 0); Location locx14 = loc14.add(0, count, 0); Location locx15 = loc15.add(0, count, 0); Location locx16 = loc16.add(0, count, 0); loc.getWorld().spawnFallingBlock(locx1, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx2, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx3, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx4, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx5, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx6, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx7, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx8, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx9, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx10, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx11, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx12, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx13, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx14, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx15, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx16, Material.OBSIDIAN, (byte) 0); } player.sendMessage(apvp + "Obsidian fortification is protecting you."); } } else { Location loc = player.getLocation(); Location loc1 = loc.add(2, -1, -2); Location loc2 = loc.add(2, -1, -1); Location loc3 = loc.add(2, -1, 0); Location loc4 = loc.add(2, -1, 1); Location loc5 = loc.add(2, -1, 1); Location loc6 = loc.add(-1, -1, 2); Location loc7 = loc.add(0, -1, 2); Location loc8 = loc.add(1, -1, 2); Location loc9 = loc.add(-2, -1, -2); Location loc10 = loc.add(-2, -1, -1); Location loc11 = loc.add(-2, -1, 0); Location loc12 = loc.add(-2, -1, 1); Location loc13 = loc.add(-2, -1, 2); Location loc14 = loc.add(-1, -1, -2); Location loc15 = loc.add(0, -1, -2); Location loc16 = loc.add(1, -1, -2); /** * Lets spawn some obsidian around the player. * Spawn it like this four blocks high: * 12345 * 6 6 * 5 P 7 * 4 8 * 32109 */ int count = 1; // Spawn the blocks for(count = 1; count < 4; count++) { Location locx1 = loc1.add(0, count, 0); Location locx2 = loc2.add(0, count, 0); Location locx3 = loc3.add(0, count, 0); Location locx4 = loc4.add(0, count, 0); Location locx5 = loc5.add(0, count, 0); Location locx6 = loc6.add(0, count, 0); Location locx7 = loc7.add(0, count, 0); Location locx8 = loc8.add(0, count, 0); Location locx9 = loc9.add(0, count, 0); Location locx10 = loc10.add(0, count, 0); Location locx11 = loc11.add(0, count, 0); Location locx12 = loc12.add(0, count, 0); Location locx13 = loc13.add(0, count, 0); Location locx14 = loc14.add(0, count, 0); Location locx15 = loc15.add(0, count, 0); Location locx16 = loc16.add(0, count, 0); loc.getWorld().spawnFallingBlock(locx1, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx2, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx3, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx4, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx5, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx6, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx7, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx8, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx9, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx10, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx11, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx12, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx13, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx14, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx15, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx16, Material.OBSIDIAN, (byte) 0); } player.sendMessage(apvp + "Obsidian fortification is protecting you."); } } else { player.sendMessage(apvp + "You don't have permission to use this ability."); } } } // Everything must be above this. }
public void earthInteract(PlayerInteractEvent event) { /** * Stuff we need for everything. * Set up cooldowns in seconds. */ long golemcool = 60; long fortifycool = 60; Player player = event.getPlayer(); Action action = event.getAction(); if(action == Action.LEFT_CLICK_BLOCK) { ItemStack itemStack = player.getItemInHand(); ItemMeta meta = itemStack.getItemMeta(); List<String> lore = meta.getLore(); if(lore.isEmpty()) { return; } /** * Check for lore of earth abilities added via commands. */ else { if(lore.contains(ChatColor.GREEN + "Fortify")) { // TODO: stuff for fortify here. } if(lore.contains(ChatColor.GREEN + "Golem")) { if(player.hasPermission("avatarpvp.earth.golem")) { // Check if the player has used the ability already. if(golem.containsKey(player.getName())) { long diff = (System.currentTimeMillis() - golem.get(player.getName())) / 1000; // Used it too recently. if(golemcool > diff) { player.sendMessage(apvp + "You must wait " + ChatColor.RED + (golemcool - diff) + ChatColor.WHITE + " before using this again."); } // Can use it again. else { Block clickedBlock = event.getClickedBlock(); Location loc = clickedBlock.getLocation(); loc.getWorld().spawnEntity(loc, EntityType.IRON_GOLEM); golem.remove(player.getName()); golem.put(player.getName(), System.currentTimeMillis()); player.sendMessage(apvp + "Spawned an iron golem to protect you."); } } // Player hasn't already used it. else { Block clickedBlock = event.getClickedBlock(); Location loc = clickedBlock.getLocation(); loc.getWorld().spawnEntity(loc, EntityType.IRON_GOLEM); golem.put(player.getName(), System.currentTimeMillis()); } } else { player.sendMessage(apvp + "You don't have permission to use this ability."); } } } } if(action == Action.LEFT_CLICK_AIR) { /** * Need to handle left click air so that way we get the location * of the player and not the clicked block so they don't spawn * the box on themselves. */ ItemStack itemStack = player.getItemInHand(); ItemMeta meta = itemStack.getItemMeta(); List<String> lore = meta.getLore(); if(lore.isEmpty()) { return; } if(lore.contains(ChatColor.GREEN + "Fortify")) { if(player.hasPermission("avatarpvp.earth.fortify")) { if(fortify.containsKey(player.getName())) { long diff = (System.currentTimeMillis() - golem.get(player.getName())) / 1000; // Used it too recently. if(fortifycool > diff) { player.sendMessage(apvp + "You must wait " + ChatColor.RED + (fortifycool - diff) + ChatColor.WHITE + " before using this again."); } // Can use the ability again. else { Location loc = player.getLocation(); Location loc1 = loc.add(2, -1, -2); Location loc2 = loc.add(2, -1, -1); Location loc3 = loc.add(2, -1, 0); Location loc4 = loc.add(2, -1, 1); Location loc5 = loc.add(2, -1, 1); Location loc6 = loc.add(-1, -1, 2); Location loc7 = loc.add(0, -1, 2); Location loc8 = loc.add(1, -1, 2); Location loc9 = loc.add(-2, -1, -2); Location loc10 = loc.add(-2, -1, -1); Location loc11 = loc.add(-2, -1, 0); Location loc12 = loc.add(-2, -1, 1); Location loc13 = loc.add(-2, -1, 2); Location loc14 = loc.add(-1, -1, -2); Location loc15 = loc.add(0, -1, -2); Location loc16 = loc.add(1, -1, -2); /** * Lets spawn some obsidian around the player. * Spawn it like this four blocks high: * 12345 * 6 6 * 5 P 7 * 4 8 * 32109 */ int count = 1; // Spawn the blocks for(count = 1; count < 4; count++) { Location locx1 = loc1.add(0, count, 0); Location locx2 = loc2.add(0, count, 0); Location locx3 = loc3.add(0, count, 0); Location locx4 = loc4.add(0, count, 0); Location locx5 = loc5.add(0, count, 0); Location locx6 = loc6.add(0, count, 0); Location locx7 = loc7.add(0, count, 0); Location locx8 = loc8.add(0, count, 0); Location locx9 = loc9.add(0, count, 0); Location locx10 = loc10.add(0, count, 0); Location locx11 = loc11.add(0, count, 0); Location locx12 = loc12.add(0, count, 0); Location locx13 = loc13.add(0, count, 0); Location locx14 = loc14.add(0, count, 0); Location locx15 = loc15.add(0, count, 0); Location locx16 = loc16.add(0, count, 0); loc.getWorld().spawnFallingBlock(locx1, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx2, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx3, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx4, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx5, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx6, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx7, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx8, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx9, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx10, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx11, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx12, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx13, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx14, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx15, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx16, Material.OBSIDIAN, (byte) 0); } player.sendMessage(apvp + "Obsidian fortification is protecting you."); fortify.remove(player.getName()); fortify.put(player.getName(), System.currentTimeMillis()); } } else { Location loc = player.getLocation(); Location loc1 = loc.add(2, -1, -2); Location loc2 = loc.add(2, -1, -1); Location loc3 = loc.add(2, -1, 0); Location loc4 = loc.add(2, -1, 1); Location loc5 = loc.add(2, -1, 1); Location loc6 = loc.add(-1, -1, 2); Location loc7 = loc.add(0, -1, 2); Location loc8 = loc.add(1, -1, 2); Location loc9 = loc.add(-2, -1, -2); Location loc10 = loc.add(-2, -1, -1); Location loc11 = loc.add(-2, -1, 0); Location loc12 = loc.add(-2, -1, 1); Location loc13 = loc.add(-2, -1, 2); Location loc14 = loc.add(-1, -1, -2); Location loc15 = loc.add(0, -1, -2); Location loc16 = loc.add(1, -1, -2); /** * Lets spawn some obsidian around the player. * Spawn it like this four blocks high: * 12345 * 6 6 * 5 P 7 * 4 8 * 32109 */ int count = 1; // Spawn the blocks for(count = 1; count < 4; count++) { Location locx1 = loc1.add(0, count, 0); Location locx2 = loc2.add(0, count, 0); Location locx3 = loc3.add(0, count, 0); Location locx4 = loc4.add(0, count, 0); Location locx5 = loc5.add(0, count, 0); Location locx6 = loc6.add(0, count, 0); Location locx7 = loc7.add(0, count, 0); Location locx8 = loc8.add(0, count, 0); Location locx9 = loc9.add(0, count, 0); Location locx10 = loc10.add(0, count, 0); Location locx11 = loc11.add(0, count, 0); Location locx12 = loc12.add(0, count, 0); Location locx13 = loc13.add(0, count, 0); Location locx14 = loc14.add(0, count, 0); Location locx15 = loc15.add(0, count, 0); Location locx16 = loc16.add(0, count, 0); loc.getWorld().spawnFallingBlock(locx1, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx2, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx3, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx4, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx5, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx6, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx7, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx8, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx9, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx10, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx11, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx12, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx13, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx14, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx15, Material.OBSIDIAN, (byte) 0); loc.getWorld().spawnFallingBlock(locx16, Material.OBSIDIAN, (byte) 0); } player.sendMessage(apvp + "Obsidian fortification is protecting you."); } } else { player.sendMessage(apvp + "You don't have permission to use this ability."); } } } // Everything must be above this. }
diff --git a/examples/embedded/src/main/java/org/mortbay/jetty/example/LikeJettyXml.java b/examples/embedded/src/main/java/org/mortbay/jetty/example/LikeJettyXml.java index ec5ec3801..992b57afa 100644 --- a/examples/embedded/src/main/java/org/mortbay/jetty/example/LikeJettyXml.java +++ b/examples/embedded/src/main/java/org/mortbay/jetty/example/LikeJettyXml.java @@ -1,90 +1,90 @@ //======================================================================== //Copyright 2006 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //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.mortbay.jetty.example; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Handler; import org.mortbay.jetty.NCSARequestLog; import org.mortbay.jetty.Server; import org.mortbay.jetty.deployer.ContextDeployer; import org.mortbay.jetty.deployer.WebAppDeployer; import org.mortbay.jetty.handler.ContextHandlerCollection; import org.mortbay.jetty.handler.DefaultHandler; import org.mortbay.jetty.handler.HandlerCollection; import org.mortbay.jetty.handler.RequestLogHandler; import org.mortbay.jetty.nio.SelectChannelConnector; import org.mortbay.jetty.security.HashUserRealm; import org.mortbay.jetty.security.UserRealm; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.thread.BoundedThreadPool; import org.mortbay.thread.QueuedThreadPool; public class LikeJettyXml { public static void main(String[] args) throws Exception { String jetty_default=new java.io.File("./start.jar").exists()?".":"../..";; String jetty_home = System.getProperty("jetty.home",jetty_default); Server server = new Server(); QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setMaxThreads(100); server.setThreadPool(threadPool); Connector connector=new SelectChannelConnector(); connector.setPort(8080); connector.setMaxIdleTime(30000); server.setConnectors(new Connector[]{connector}); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[]{contexts,new DefaultHandler(),requestLogHandler}); server.setHandler(handlers); ContextDeployer deployer0 = new ContextDeployer(); deployer0.setContexts(contexts); deployer0.setConfigurationDir(jetty_home+"/contexts"); deployer0.setScanInterval(1); server.addLifeCycle(deployer0); WebAppDeployer deployer1 = new WebAppDeployer(); deployer1.setContexts(contexts); deployer1.setWebAppDir(jetty_home+"/webapps"); deployer1.setParentLoaderPriority(false); deployer1.setExtract(true); deployer1.setAllowDuplicates(false); deployer1.setDefaultsDescriptor(jetty_home+"/etc/webdefault.xml"); server.addLifeCycle(deployer1); HashUserRealm userRealm = new HashUserRealm(); userRealm.setName("Test Realm"); userRealm.setConfig(jetty_home+"/etc/realm.properties"); server.setUserRealms(new UserRealm[]{userRealm}); - NCSARequestLog requestLog = new NCSARequestLog(jetty_home+"/logs/jetty-yyyy-mm-dd.log"); + NCSARequestLog requestLog = new NCSARequestLog(jetty_home+"/logs/jetty-yyyy_mm_dd.log"); requestLog.setExtended(false); requestLogHandler.setRequestLog(requestLog); server.setStopAtShutdown(true); server.setSendServerVersion(true); server.start(); server.join(); } }
true
true
public static void main(String[] args) throws Exception { String jetty_default=new java.io.File("./start.jar").exists()?".":"../..";; String jetty_home = System.getProperty("jetty.home",jetty_default); Server server = new Server(); QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setMaxThreads(100); server.setThreadPool(threadPool); Connector connector=new SelectChannelConnector(); connector.setPort(8080); connector.setMaxIdleTime(30000); server.setConnectors(new Connector[]{connector}); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[]{contexts,new DefaultHandler(),requestLogHandler}); server.setHandler(handlers); ContextDeployer deployer0 = new ContextDeployer(); deployer0.setContexts(contexts); deployer0.setConfigurationDir(jetty_home+"/contexts"); deployer0.setScanInterval(1); server.addLifeCycle(deployer0); WebAppDeployer deployer1 = new WebAppDeployer(); deployer1.setContexts(contexts); deployer1.setWebAppDir(jetty_home+"/webapps"); deployer1.setParentLoaderPriority(false); deployer1.setExtract(true); deployer1.setAllowDuplicates(false); deployer1.setDefaultsDescriptor(jetty_home+"/etc/webdefault.xml"); server.addLifeCycle(deployer1); HashUserRealm userRealm = new HashUserRealm(); userRealm.setName("Test Realm"); userRealm.setConfig(jetty_home+"/etc/realm.properties"); server.setUserRealms(new UserRealm[]{userRealm}); NCSARequestLog requestLog = new NCSARequestLog(jetty_home+"/logs/jetty-yyyy-mm-dd.log"); requestLog.setExtended(false); requestLogHandler.setRequestLog(requestLog); server.setStopAtShutdown(true); server.setSendServerVersion(true); server.start(); server.join(); }
public static void main(String[] args) throws Exception { String jetty_default=new java.io.File("./start.jar").exists()?".":"../..";; String jetty_home = System.getProperty("jetty.home",jetty_default); Server server = new Server(); QueuedThreadPool threadPool = new QueuedThreadPool(); threadPool.setMaxThreads(100); server.setThreadPool(threadPool); Connector connector=new SelectChannelConnector(); connector.setPort(8080); connector.setMaxIdleTime(30000); server.setConnectors(new Connector[]{connector}); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[]{contexts,new DefaultHandler(),requestLogHandler}); server.setHandler(handlers); ContextDeployer deployer0 = new ContextDeployer(); deployer0.setContexts(contexts); deployer0.setConfigurationDir(jetty_home+"/contexts"); deployer0.setScanInterval(1); server.addLifeCycle(deployer0); WebAppDeployer deployer1 = new WebAppDeployer(); deployer1.setContexts(contexts); deployer1.setWebAppDir(jetty_home+"/webapps"); deployer1.setParentLoaderPriority(false); deployer1.setExtract(true); deployer1.setAllowDuplicates(false); deployer1.setDefaultsDescriptor(jetty_home+"/etc/webdefault.xml"); server.addLifeCycle(deployer1); HashUserRealm userRealm = new HashUserRealm(); userRealm.setName("Test Realm"); userRealm.setConfig(jetty_home+"/etc/realm.properties"); server.setUserRealms(new UserRealm[]{userRealm}); NCSARequestLog requestLog = new NCSARequestLog(jetty_home+"/logs/jetty-yyyy_mm_dd.log"); requestLog.setExtended(false); requestLogHandler.setRequestLog(requestLog); server.setStopAtShutdown(true); server.setSendServerVersion(true); server.start(); server.join(); }
diff --git a/src/edu/jas/application/PolyUtilAppTest.java b/src/edu/jas/application/PolyUtilAppTest.java index 4f7427d4..5258fb2b 100644 --- a/src/edu/jas/application/PolyUtilAppTest.java +++ b/src/edu/jas/application/PolyUtilAppTest.java @@ -1,241 +1,241 @@ /* * $Id$ */ package edu.jas.application; import java.util.List; import java.util.ArrayList; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import edu.jas.arith.BigInteger; import edu.jas.arith.ModInteger; import edu.jas.arith.ModIntegerRing; import edu.jas.arith.BigRational; import edu.jas.arith.BigComplex; import edu.jas.poly.TermOrder; import edu.jas.poly.GenPolynomial; import edu.jas.poly.GenPolynomialRing; import edu.jas.poly.AlgebraicNumber; import edu.jas.poly.AlgebraicNumberRing; import edu.jas.structure.Product; import edu.jas.structure.ProductRing; import edu.jas.structure.RingElem; import edu.jas.application.PolyUtilApp; /** * PolyUtilApp tests with JUnit. * @author Heinz Kredel. */ public class PolyUtilAppTest extends TestCase { /** * main. */ public static void main (String[] args) { junit.textui.TestRunner.run( suite() ); } /** * Constructs a <CODE>PolyUtilAppTest</CODE> object. * @param name String. */ public PolyUtilAppTest(String name) { super(name); } /** */ public static Test suite() { TestSuite suite= new TestSuite(PolyUtilAppTest.class); return suite; } //private final static int bitlen = 100; TermOrder to = new TermOrder( TermOrder.INVLEX ); GenPolynomialRing<BigRational> dfac; GenPolynomialRing<BigRational> cfac; GenPolynomialRing<GenPolynomial<BigRational>> rfac; BigRational ai; BigRational bi; BigRational ci; BigRational di; BigRational ei; GenPolynomial<BigRational> a; GenPolynomial<BigRational> b; GenPolynomial<BigRational> c; GenPolynomial<BigRational> d; GenPolynomial<BigRational> e; GenPolynomial<GenPolynomial<BigRational>> ar; GenPolynomial<GenPolynomial<BigRational>> br; GenPolynomial<GenPolynomial<BigRational>> cr; GenPolynomial<GenPolynomial<BigRational>> dr; GenPolynomial<GenPolynomial<BigRational>> er; int rl = 5; int kl = 5; int ll = 5; int el = 5; float q = 0.6f; protected void setUp() { a = b = c = d = e = null; ai = bi = ci = di = ei = null; ar = br = cr = dr = er = null; dfac = new GenPolynomialRing<BigRational>(new BigRational(1),rl,to); cfac = new GenPolynomialRing<BigRational>(new BigRational(1),rl-1,to); rfac = new GenPolynomialRing<GenPolynomial<BigRational>>(cfac,1,to); } protected void tearDown() { a = b = c = d = e = null; ai = bi = ci = di = ei = null; ar = br = cr = dr = er = null; dfac = null; cfac = null; rfac = null; } /** * Test Product represenation conversion, rational numbers. * */ public void xtestProductConversionRN() { GenPolynomialRing<BigRational> ufac; ufac = new GenPolynomialRing<BigRational>(new BigRational(1),1); ProductRing<GenPolynomial<BigRational>> pfac; pfac = new ProductRing<GenPolynomial<BigRational>>( ufac, rl ); Product<GenPolynomial<BigRational>> cp; c = dfac.getONE(); //System.out.println("c = " + c); cp = PolyUtilApp.toProduct(pfac,c); //System.out.println("cp = " + cp); assertTrue("isZERO( cp )", cp.isZERO() ); c = dfac.random(kl,ll,el,q); //System.out.println("c = " + c); cp = PolyUtilApp.toProduct(pfac,c); //System.out.println("cp = " + cp); assertTrue("!isONE( cp )", !cp.isONE() ); } /** * Test Product represenation conversion, algebraic numbers. * */ public void xtestProductConversionAN() { GenPolynomialRing<BigRational> ufac; ufac = new GenPolynomialRing<BigRational>(new BigRational(1),1); GenPolynomial<BigRational> m; m = ufac.univariate(0,2); m = m.subtract( ufac.univariate(0,1) ); //System.out.println("m = " + m); AlgebraicNumberRing<BigRational> afac; afac = new AlgebraicNumberRing<BigRational>(m); //System.out.println("afac = " + afac); ProductRing<AlgebraicNumber<BigRational>> pfac; pfac = new ProductRing<AlgebraicNumber<BigRational>>( afac, rl ); Product<AlgebraicNumber<BigRational>> cp; c = dfac.getONE(); //System.out.println("c = " + c); cp = PolyUtilApp.toANProduct(pfac,c); //System.out.println("cp = " + cp); assertTrue("isZERO( cp )", cp.isZERO() ); c = dfac.random(kl,ll,el,q); //System.out.println("c = " + c); cp = PolyUtilApp.toANProduct(pfac,c); //System.out.println("cp = " + cp); assertTrue("!isONE( cp )", !cp.isONE() ); } /** * Test Product represenation conversion, algebraic numbers, coefficients. * */ public void testProductConversionANCoeff() { GenPolynomialRing<BigRational> ufac; ufac = new GenPolynomialRing<BigRational>(new BigRational(1),1); GenPolynomial<BigRational> m; m = ufac.univariate(0,2); m = m.subtract( ufac.univariate(0,1) ); //System.out.println("m = " + m); AlgebraicNumberRing<BigRational> afac; afac = new AlgebraicNumberRing<BigRational>(m); //System.out.println("afac = " + afac); ProductRing<AlgebraicNumber<BigRational>> pfac; pfac = new ProductRing<AlgebraicNumber<BigRational>>( afac, rl ); //System.out.println("pfac = " + pfac); GenPolynomialRing<Product<AlgebraicNumber<BigRational>>> fac = new GenPolynomialRing<Product<AlgebraicNumber<BigRational>>>(pfac,4); //System.out.println("fac = " + fac); rfac = new GenPolynomialRing<GenPolynomial<BigRational>>(dfac,4); GenPolynomial<Product<AlgebraicNumber<BigRational>>> cp; // Product<AlgebraicNumber<BigRational>> cp; cr = rfac.getONE(); //System.out.println("cr = " + cr); cp = PolyUtilApp.toANProductCoeff(fac,cr); //System.out.println("cp = " + cp); - assertTrue("isZERO( cp )", cp.isZERO() ); + assertTrue("isONE( cp )", cp.isONE() ); cr = rfac.random(kl,ll,el,q); //System.out.println("cr = " + cr); cp = PolyUtilApp.toANProductCoeff(fac,cr); //System.out.println("cp = " + cp); assertTrue("!isONE( cp )", !cp.isONE() ); br = rfac.random(kl,ll,el,q); //System.out.println("br = " + br); List<GenPolynomial<GenPolynomial<BigRational>>> list = new ArrayList<GenPolynomial<GenPolynomial<BigRational>>>(); list.add(cr); list.add(br); List<GenPolynomial<Product<AlgebraicNumber<BigRational>>>> res = new ArrayList<GenPolynomial<Product<AlgebraicNumber<BigRational>>>>(); //System.out.println("list = " + list); res = PolyUtilApp.toANProductCoeff(fac,list); //System.out.println("res = " + res); } }
true
true
public void testProductConversionANCoeff() { GenPolynomialRing<BigRational> ufac; ufac = new GenPolynomialRing<BigRational>(new BigRational(1),1); GenPolynomial<BigRational> m; m = ufac.univariate(0,2); m = m.subtract( ufac.univariate(0,1) ); //System.out.println("m = " + m); AlgebraicNumberRing<BigRational> afac; afac = new AlgebraicNumberRing<BigRational>(m); //System.out.println("afac = " + afac); ProductRing<AlgebraicNumber<BigRational>> pfac; pfac = new ProductRing<AlgebraicNumber<BigRational>>( afac, rl ); //System.out.println("pfac = " + pfac); GenPolynomialRing<Product<AlgebraicNumber<BigRational>>> fac = new GenPolynomialRing<Product<AlgebraicNumber<BigRational>>>(pfac,4); //System.out.println("fac = " + fac); rfac = new GenPolynomialRing<GenPolynomial<BigRational>>(dfac,4); GenPolynomial<Product<AlgebraicNumber<BigRational>>> cp; // Product<AlgebraicNumber<BigRational>> cp; cr = rfac.getONE(); //System.out.println("cr = " + cr); cp = PolyUtilApp.toANProductCoeff(fac,cr); //System.out.println("cp = " + cp); assertTrue("isZERO( cp )", cp.isZERO() ); cr = rfac.random(kl,ll,el,q); //System.out.println("cr = " + cr); cp = PolyUtilApp.toANProductCoeff(fac,cr); //System.out.println("cp = " + cp); assertTrue("!isONE( cp )", !cp.isONE() ); br = rfac.random(kl,ll,el,q); //System.out.println("br = " + br); List<GenPolynomial<GenPolynomial<BigRational>>> list = new ArrayList<GenPolynomial<GenPolynomial<BigRational>>>(); list.add(cr); list.add(br); List<GenPolynomial<Product<AlgebraicNumber<BigRational>>>> res = new ArrayList<GenPolynomial<Product<AlgebraicNumber<BigRational>>>>(); //System.out.println("list = " + list); res = PolyUtilApp.toANProductCoeff(fac,list); //System.out.println("res = " + res); }
public void testProductConversionANCoeff() { GenPolynomialRing<BigRational> ufac; ufac = new GenPolynomialRing<BigRational>(new BigRational(1),1); GenPolynomial<BigRational> m; m = ufac.univariate(0,2); m = m.subtract( ufac.univariate(0,1) ); //System.out.println("m = " + m); AlgebraicNumberRing<BigRational> afac; afac = new AlgebraicNumberRing<BigRational>(m); //System.out.println("afac = " + afac); ProductRing<AlgebraicNumber<BigRational>> pfac; pfac = new ProductRing<AlgebraicNumber<BigRational>>( afac, rl ); //System.out.println("pfac = " + pfac); GenPolynomialRing<Product<AlgebraicNumber<BigRational>>> fac = new GenPolynomialRing<Product<AlgebraicNumber<BigRational>>>(pfac,4); //System.out.println("fac = " + fac); rfac = new GenPolynomialRing<GenPolynomial<BigRational>>(dfac,4); GenPolynomial<Product<AlgebraicNumber<BigRational>>> cp; // Product<AlgebraicNumber<BigRational>> cp; cr = rfac.getONE(); //System.out.println("cr = " + cr); cp = PolyUtilApp.toANProductCoeff(fac,cr); //System.out.println("cp = " + cp); assertTrue("isONE( cp )", cp.isONE() ); cr = rfac.random(kl,ll,el,q); //System.out.println("cr = " + cr); cp = PolyUtilApp.toANProductCoeff(fac,cr); //System.out.println("cp = " + cp); assertTrue("!isONE( cp )", !cp.isONE() ); br = rfac.random(kl,ll,el,q); //System.out.println("br = " + br); List<GenPolynomial<GenPolynomial<BigRational>>> list = new ArrayList<GenPolynomial<GenPolynomial<BigRational>>>(); list.add(cr); list.add(br); List<GenPolynomial<Product<AlgebraicNumber<BigRational>>>> res = new ArrayList<GenPolynomial<Product<AlgebraicNumber<BigRational>>>>(); //System.out.println("list = " + list); res = PolyUtilApp.toANProductCoeff(fac,list); //System.out.println("res = " + res); }
diff --git a/src/minecraft/org/spoutcraft/client/gui/settings/DifficultyButton.java b/src/minecraft/org/spoutcraft/client/gui/settings/DifficultyButton.java index 6af921e0..b91595c7 100644 --- a/src/minecraft/org/spoutcraft/client/gui/settings/DifficultyButton.java +++ b/src/minecraft/org/spoutcraft/client/gui/settings/DifficultyButton.java @@ -1,80 +1,80 @@ /* * This file is part of Spoutcraft (http://www.spout.org/). * * Spoutcraft is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Spoutcraft is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.spoutcraft.client.gui.settings; import net.minecraft.client.Minecraft; import org.spoutcraft.spoutcraftapi.event.screen.ButtonClickEvent; import org.spoutcraft.spoutcraftapi.gui.GenericButton; public class DifficultyButton extends GenericButton{ public DifficultyButton() { super("Difficulty"); setTooltip("Difficulty\nControls the difficulty of the game."); } @Override public String getText() { if (Minecraft.theMinecraft.theWorld != null && Minecraft.theMinecraft.theWorld.getWorldInfo().isHardcoreModeEnabled()) { return "Difficulty: Hardcore"; } String difficulty; switch(Minecraft.theMinecraft.gameSettings.difficulty) { case 0: difficulty = "Peaceful"; break; case 1: difficulty = "Easy"; break; case 2: difficulty = "Normal"; break; - case 3: difficulty = "Hard;"; break; + case 3: difficulty = "Hard"; break; default: difficulty = "Unknown"; break; } return "Difficulty: " + difficulty; } @Override public String getTooltip() { if (Minecraft.theMinecraft.theWorld == null) { return "Can not change difficulty outside of the game"; } if (Minecraft.theMinecraft.isMultiplayerWorld()) { return "Can not change difficulty in multiplayer"; } if (Minecraft.theMinecraft.theWorld.getWorldInfo().isHardcoreModeEnabled()) { return "Can not change difficulty in hardcore mode"; } return super.getTooltip(); } @Override public boolean isEnabled() { if (Minecraft.theMinecraft.theWorld == null) { return false; } if (Minecraft.theMinecraft.isMultiplayerWorld()) { return false; } if (Minecraft.theMinecraft.theWorld.getWorldInfo().isHardcoreModeEnabled()) { return false; } return true; } @Override public void onButtonClick(ButtonClickEvent event) { Minecraft.theMinecraft.gameSettings.difficulty++; if (Minecraft.theMinecraft.gameSettings.difficulty > 3) Minecraft.theMinecraft.gameSettings.difficulty = 0; Minecraft.theMinecraft.gameSettings.saveOptions(); } }
true
true
public String getText() { if (Minecraft.theMinecraft.theWorld != null && Minecraft.theMinecraft.theWorld.getWorldInfo().isHardcoreModeEnabled()) { return "Difficulty: Hardcore"; } String difficulty; switch(Minecraft.theMinecraft.gameSettings.difficulty) { case 0: difficulty = "Peaceful"; break; case 1: difficulty = "Easy"; break; case 2: difficulty = "Normal"; break; case 3: difficulty = "Hard;"; break; default: difficulty = "Unknown"; break; } return "Difficulty: " + difficulty; }
public String getText() { if (Minecraft.theMinecraft.theWorld != null && Minecraft.theMinecraft.theWorld.getWorldInfo().isHardcoreModeEnabled()) { return "Difficulty: Hardcore"; } String difficulty; switch(Minecraft.theMinecraft.gameSettings.difficulty) { case 0: difficulty = "Peaceful"; break; case 1: difficulty = "Easy"; break; case 2: difficulty = "Normal"; break; case 3: difficulty = "Hard"; break; default: difficulty = "Unknown"; break; } return "Difficulty: " + difficulty; }
diff --git a/mpicbg/trakem2/align/ElasticMontage.java b/mpicbg/trakem2/align/ElasticMontage.java index bc210090..be3c6fa3 100644 --- a/mpicbg/trakem2/align/ElasticMontage.java +++ b/mpicbg/trakem2/align/ElasticMontage.java @@ -1,613 +1,613 @@ /** * License: GPL * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package mpicbg.trakem2.align; import ij.IJ; import ij.gui.GenericDialog; import ij.process.ByteProcessor; import ij.process.FloatProcessor; import ini.trakem2.Project; import ini.trakem2.display.Display; import ini.trakem2.display.Patch; import ini.trakem2.display.Patch.PatchImage; import ini.trakem2.utils.Utils; import java.awt.Rectangle; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import mpicbg.ij.SIFT; import mpicbg.ij.blockmatching.BlockMatching; import mpicbg.imagefeatures.Feature; import mpicbg.imagefeatures.FloatArray2DSIFT; import mpicbg.models.AbstractAffineModel2D; import mpicbg.models.AffineModel2D; import mpicbg.models.ErrorStatistic; import mpicbg.models.InvertibleCoordinateTransform; import mpicbg.models.NotEnoughDataPointsException; import mpicbg.models.Point; import mpicbg.models.PointMatch; import mpicbg.models.RigidModel2D; import mpicbg.models.SimilarityModel2D; import mpicbg.models.Spring; import mpicbg.models.SpringMesh; import mpicbg.models.TranslationModel2D; import mpicbg.models.Vertex; import mpicbg.trakem2.align.Align.ParamOptimize; import mpicbg.trakem2.transform.MovingLeastSquaresTransform; import mpicbg.trakem2.transform.MovingLeastSquaresTransform2; import mpicbg.util.Util; /** * @author Stephan Saalfeld <[email protected]> * @version 0.1a */ public class ElasticMontage extends AbstractElasticAlignment { final static protected class Param implements Serializable { /** * */ private static final long serialVersionUID = 685811752558724564L; public ParamOptimize po = new ParamOptimize(); { po.maxEpsilon = 25.0f; po.minInlierRatio = 0.0f; po.minNumInliers = 12; po.expectedModelIndex = 0; po.desiredModelIndex = 0; po.rejectIdentity = true; po.identityTolerance = 5.0f; } public boolean tilesAreInPlace = true; /** * Block matching */ public float bmScale = 0.33f; public float bmMinR = 0.8f; public float bmMaxCurvatureR = 3f; public float bmRodR = 0.8f; /** * Spring mesh */ public float springLengthSpringMesh = 100; public float stiffnessSpringMesh = 0.1f; public float dampSpringMesh = 0.6f; public float maxStretchSpringMesh = 2000.0f; public int maxIterationsSpringMesh = 1000; public int maxPlateauwidthSpringMesh = 200; /** * Visualize spring mesh optimization */ public boolean visualize = false; /** * Change this in case you want to limit the number of parallel threads to a specific number. */ public int maxNumThreads = Runtime.getRuntime().availableProcessors(); public boolean setup() { final GenericDialog gdSIFT = new GenericDialog( "Elastic montage: SIFT based pre-montage" ); po.addFields( gdSIFT ); gdSIFT.addMessage( "Miscellaneous:" ); gdSIFT.addCheckbox( "tiles are roughly in place", tilesAreInPlace ); gdSIFT.showDialog(); if ( gdSIFT.wasCanceled() ) return false; po.readFields( gdSIFT ); tilesAreInPlace = gdSIFT.getNextBoolean(); /* Block Matching */ final GenericDialog gdBlockMatching = new GenericDialog( "Elastic montage: Block Matching and Spring Meshes" ); gdBlockMatching.addMessage( "Block Matching:" ); gdBlockMatching.addNumericField( "patch_scale :", bmScale, 2 ); gdBlockMatching.addNumericField( "minimal_PMCC_r :", bmMinR, 2 ); gdBlockMatching.addNumericField( "maximal_curvature_ratio :", bmMaxCurvatureR, 2 ); gdBlockMatching.addNumericField( "maximal_second_best_r/best_r :", bmRodR, 2 ); /* TODO suggest a resolution that matches maxEpsilon */ gdBlockMatching.addMessage( "Spring Mesh:" ); gdBlockMatching.addNumericField( "spring_length :", springLengthSpringMesh, 2, 6, "px" ); gdBlockMatching.addNumericField( "stiffness :", stiffnessSpringMesh, 2 ); gdBlockMatching.addNumericField( "maximal_stretch :", maxStretchSpringMesh, 2, 6, "px" ); gdBlockMatching.addNumericField( "maximal_iterations :", maxIterationsSpringMesh, 0 ); gdBlockMatching.addNumericField( "maximal_plateauwidth :", maxPlateauwidthSpringMesh, 0 ); gdBlockMatching.showDialog(); if ( gdBlockMatching.wasCanceled() ) return false; bmScale = ( float )gdBlockMatching.getNextNumber(); bmMinR = ( float )gdBlockMatching.getNextNumber(); bmMaxCurvatureR = ( float )gdBlockMatching.getNextNumber(); bmRodR = ( float )gdBlockMatching.getNextNumber(); springLengthSpringMesh = ( float )gdBlockMatching.getNextNumber(); stiffnessSpringMesh = ( float )gdBlockMatching.getNextNumber(); maxStretchSpringMesh = ( float )gdBlockMatching.getNextNumber(); maxIterationsSpringMesh = ( int )gdBlockMatching.getNextNumber(); maxPlateauwidthSpringMesh = ( int )gdBlockMatching.getNextNumber(); return true; } @Override public Param clone() { final Param p = new Param(); p.po = po.clone(); p.tilesAreInPlace = tilesAreInPlace; p.bmScale = bmScale; p.bmMinR = bmMinR; p.bmMaxCurvatureR = bmMaxCurvatureR; p.bmRodR = bmRodR; p.springLengthSpringMesh = springLengthSpringMesh; p.stiffnessSpringMesh = stiffnessSpringMesh; p.dampSpringMesh = dampSpringMesh; p.maxStretchSpringMesh = maxStretchSpringMesh; p.maxIterationsSpringMesh = maxIterationsSpringMesh; p.maxPlateauwidthSpringMesh = maxPlateauwidthSpringMesh; p.visualize = visualize; p.maxNumThreads = maxNumThreads; return p; } } final static Param p = new Param(); final static public Param setup() { return p.setup() ? p.clone() : null; } final static private String patchName( final Patch patch ) { return new StringBuffer( "patch `" ) .append( patch.getTitle() ) .append( "'" ) .toString(); } /** * Extract SIFT features and save them into the project folder. * * @param layerSet the layerSet that contains all layers * @param layerRange the list of layers to be aligned * @param box a rectangular region of interest that will be used for alignment * @param scale scale factor <= 1.0 * @param filter a name based filter for Patches (can be null) * @param p SIFT extraction parameters * @throws Exception */ final static protected void extractAndSaveFeatures( final List< AbstractAffineTile2D< ? > > tiles, final FloatArray2DSIFT.Param siftParam, final boolean clearCache ) throws Exception { final ExecutorService exec = Executors.newFixedThreadPool( p.maxNumThreads ); /* extract features for all slices and store them to disk */ final AtomicInteger counter = new AtomicInteger( 0 ); final ArrayList< Future< ArrayList< Feature > > > siftTasks = new ArrayList< Future< ArrayList< Feature > > >(); for ( int i = 0; i < tiles.size(); ++i ) { final int tileIndex = i; siftTasks.add( exec.submit( new Callable< ArrayList< Feature > >() { public ArrayList< Feature > call() { final AbstractAffineTile2D< ? > tile = tiles.get( tileIndex ); final String patchName = patchName( tile.getPatch() ); IJ.showProgress( counter.getAndIncrement(), tiles.size() - 1 ); ArrayList< Feature > fs = null; if ( !clearCache ) fs = mpicbg.trakem2.align.Util.deserializeFeatures( tile.getPatch().getProject(), siftParam, null, tile.getPatch().getId() ); if ( null == fs ) { final FloatArray2DSIFT sift = new FloatArray2DSIFT( siftParam ); final SIFT ijSIFT = new SIFT( sift ); fs = new ArrayList< Feature >(); final ByteProcessor ip = tile.createMaskedByteImage(); ijSIFT.extractFeatures( ip, fs ); Utils.log( fs.size() + " features extracted for " + patchName ); if ( !mpicbg.trakem2.align.Util.serializeFeatures( tile.getPatch().getProject(), siftParam, null, tile.getPatch().getId(), fs ) ) Utils.log( "FAILED to store serialized features for " + patchName ); } else Utils.log( fs.size() + " features loaded for " + patchName ); return fs; } } ) ); } /* join */ for ( Future< ArrayList< Feature > > fu : siftTasks ) fu.get(); siftTasks.clear(); exec.shutdown(); } final static protected FloatProcessor scaleByte( final ByteProcessor bp ) { final FloatProcessor fp = new FloatProcessor( bp.getWidth(), bp.getHeight() ); final byte[] bytes = ( byte[] )bp.getPixels(); final float[] floats = ( float[] )fp.getPixels(); for ( int i = 0; i < bytes.length; ++i ) floats[ i ] = ( bytes[ i ] & 0xff ) / 255.0f; return fp; } final public void exec( final List< Patch > patches, final List< Patch > fixedPatches ) throws Exception { /* make sure that passed patches are ok */ if ( patches.size() < 2 ) { Utils.log( "Elastic montage requires at least 2 patches to be montaged. You passed me " + patches.size() ); return; } final Project project = patches.get( 0 ).getProject(); for ( final Patch patch : patches ) { if ( patch.getProject() != project ) { Utils.log( "Elastic montage requires all patches to be member of a single project. You passed me patches from several projects." ); return; } } for ( final Patch patch : fixedPatches ) { if ( patch.getProject() != project ) { Utils.log( "Elastic montage requires all fixed patches to be member of a single project. You passed me fixed patches from several projects." ); return; } } final Param p = setup(); if ( p == null ) return; else exec( p, patches, fixedPatches ); } final public void exec( final Param p, final List< Patch > patches, final List< Patch > fixedPatches ) throws Exception { /* free memory */ patches.get( 0 ).getProject().getLoader().releaseAll(); /* create tiles and models for all patches */ final List< AbstractAffineTile2D< ? > > tiles = new ArrayList< AbstractAffineTile2D< ? > >(); final List< AbstractAffineTile2D< ? > > fixedTiles = new ArrayList< AbstractAffineTile2D< ? > > (); Align.tilesFromPatches( p.po, patches, fixedPatches, tiles, fixedTiles ); Align.alignTiles( p.po, tiles, fixedTiles, p.tilesAreInPlace, p.maxNumThreads ); /* Apply the estimated affine transform to patches */ for ( final AbstractAffineTile2D< ? > t : tiles ) t.getPatch().setAffineTransform( t.createAffine() ); Display.update(); /* generate tile pairs for all by now overlapping tiles */ final ArrayList< AbstractAffineTile2D< ? >[] > tilePairs = new ArrayList< AbstractAffineTile2D<?>[] >(); AbstractAffineTile2D.pairOverlappingTiles( tiles, tilePairs ); /* check if there was any pair */ if ( tilePairs.size() == 0 ) { Utils.log( "Elastic montage could not find any overlapping patches after pre-montaging." ); return; } Utils.log( tilePairs.size() + " pairs of patches will be block-matched..." ); /* make pairwise global models local */ final ArrayList< Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform > > pairs = new ArrayList< Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform > >(); /* * The following casting madness is necessary to get this code compiled * with Sun/Oracle Java 6 which otherwise generates an inconvertible * type exception. * * TODO Remove as soon as this bug is fixed in Sun/Oracle javac. */ for ( final AbstractAffineTile2D< ? >[] pair : tilePairs ) { final AbstractAffineModel2D< ? > m; switch ( p.po.desiredModelIndex ) { case 0: final TranslationModel2D t = ( TranslationModel2D )( Object )pair[ 1 ].getModel().createInverse(); t.concatenate( ( TranslationModel2D )( Object )pair[ 0 ].getModel() ); m = t; break; case 1: final RigidModel2D r = ( RigidModel2D )( Object )pair[ 1 ].getModel().createInverse(); r.concatenate( ( RigidModel2D )( Object )pair[ 0 ].getModel() ); m = r; break; case 2: final SimilarityModel2D s = ( SimilarityModel2D )( Object )pair[ 1 ].getModel().createInverse(); s.concatenate( ( SimilarityModel2D )( Object )pair[ 0 ].getModel() ); m = s; break; case 3: final AffineModel2D a = ( AffineModel2D )( Object )pair[ 1 ].getModel().createInverse(); a.concatenate( ( AffineModel2D )( Object )pair[ 0 ].getModel() ); m = a; break; default: m = null; } pairs.add( new Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform >( pair[ 0 ], pair[ 1 ], m ) ); } /* Elastic alignment */ /* Initialization */ final float springTriangleHeightTwice = 2 * ( float )Math.sqrt( 0.75f * p.springLengthSpringMesh * p.springLengthSpringMesh ); final ArrayList< SpringMesh > meshes = new ArrayList< SpringMesh >( tiles.size() ); final HashMap< AbstractAffineTile2D< ? >, SpringMesh > tileMeshMap = new HashMap< AbstractAffineTile2D< ? >, SpringMesh >(); for ( final AbstractAffineTile2D< ? > tile : tiles ) { final double w = tile.getWidth(); final double h = tile.getWidth(); final int numX = Math.max( 2, ( int )Math.ceil( w / p.springLengthSpringMesh ) + 1 ); final int numY = Math.max( 2, ( int )Math.ceil( h / springTriangleHeightTwice ) + 1 ); final float wMesh = ( numX - 1 ) * p.springLengthSpringMesh; final float hMesh = ( numY - 1 ) * springTriangleHeightTwice; final SpringMesh mesh = new SpringMesh( numX, numY, wMesh, hMesh, p.stiffnessSpringMesh, p.maxStretchSpringMesh * p.bmScale, p.dampSpringMesh ); meshes.add( mesh ); tileMeshMap.put( tile, mesh ); } final int blockRadius = Math.max( 32, Util.roundPos( p.springLengthSpringMesh / 2 ) ); /** TODO set this something more than the largest error by the approximate model */ final int searchRadius = ( int )Math.round( p.po.maxEpsilon ); for ( final Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform > pair : pairs ) { final AbstractAffineTile2D< ? > t1 = pair.a; final AbstractAffineTile2D< ? > t2 = pair.b; final SpringMesh m1 = tileMeshMap.get( t1 ); final SpringMesh m2 = tileMeshMap.get( t2 ); ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >(); ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >(); final Collection< Vertex > v1 = m1.getVertices(); final Collection< Vertex > v2 = m2.getVertices(); final String patchName1 = patchName( t1.getPatch() ); final String patchName2 = patchName( t2.getPatch() ); PatchImage pi1 = t1.getPatch().createTransformedImage(); if ( pi1 == null ) { Utils.log( "Patch `" + patchName1 + "' failed generating a transformed image. Skipping..." ); continue; } PatchImage pi2 = t2.getPatch().createTransformedImage(); if ( pi2 == null ) { Utils.log( "Patch `" + patchName2 + "' failed generating a transformed image. Skipping..." ); continue; } FloatProcessor fp1 = ( FloatProcessor )pi1.target.convertToFloat(); ByteProcessor mask1 = pi1.getMask(); FloatProcessor fpMask1 = mask1 == null ? null : scaleByte( mask1 ); FloatProcessor fp2 = ( FloatProcessor )pi2.target.convertToFloat(); - ByteProcessor mask2 = pi1.getMask(); + ByteProcessor mask2 = pi2.getMask(); FloatProcessor fpMask2 = mask2 == null ? null : scaleByte( mask2 ); BlockMatching.matchByMaximalPMCC( fp1, fp2, fpMask1, fpMask2, p.bmScale, pair.c, blockRadius, blockRadius, searchRadius, searchRadius, p.bmMinR, p.bmRodR, p.bmMaxCurvatureR, v1, pm12, new ErrorStatistic( 1 ) ); IJ.log( "`" + patchName1 + "' > `" + patchName2 + "': found " + pm12.size() + " correspondences." ); // /* <visualisation> */ // // final List< Point > s1 = new ArrayList< Point >(); // // PointMatch.sourcePoints( pm12, s1 ); // // final ImagePlus imp1 = new ImagePlus( i + " >", ip1 ); // // imp1.show(); // // imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null ); // // imp1.setRoi( Util.pointsToPointRoi( s1 ) ); // // imp1.updateAndDraw(); // /* </visualisation> */ BlockMatching.matchByMaximalPMCC( fp2, fp1, fpMask2, fpMask1, p.bmScale, pair.c.createInverse(), blockRadius, blockRadius, searchRadius, searchRadius, p.bmMinR, p.bmRodR, p.bmMaxCurvatureR, v2, pm21, new ErrorStatistic( 1 ) ); IJ.log( "`" + patchName1 + "' > `" + patchName2 + "': found " + pm12.size() + " correspondences." ); /* <visualisation> */ // final List< Point > s2 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm21, s2 ); // final ImagePlus imp2 = new ImagePlus( i + " <", ip2 ); // imp2.show(); // imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null ); // imp2.setRoi( Util.pointsToPointRoi( s2 ) ); // imp2.updateAndDraw(); /* </visualisation> */ for ( final PointMatch pm : pm12 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, 1.0f ) ); m2.addPassiveVertex( p2 ); } for ( final PointMatch pm : pm21 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, 1.0f ) ); m1.addPassiveVertex( p2 ); } } /* initialize */ for ( Map.Entry< AbstractAffineTile2D< ? >, SpringMesh > entry : tileMeshMap.entrySet() ) entry.getValue().init( entry.getKey().getModel() ); /* optimize the meshes */ try { long t0 = System.currentTimeMillis(); IJ.log( "Optimizing spring meshes..." ); SpringMesh.optimizeMeshes( meshes, p.po.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh, p.visualize ); IJ.log( "Done optimizing spring meshes. Took " + ( System.currentTimeMillis() - t0 ) + " ms" ); } catch ( NotEnoughDataPointsException e ) { Utils.log( "There were not enough data points to get the spring mesh optimizing." ); e.printStackTrace(); return; } /* apply */ for ( Map.Entry< AbstractAffineTile2D< ? >, SpringMesh > entry : tileMeshMap.entrySet() ) { final AbstractAffineTile2D< ? > tile = entry.getKey(); final Patch patch = tile.getPatch(); final SpringMesh mesh = entry.getValue(); final Set< PointMatch > matches = mesh.getVA().keySet(); Rectangle box = patch.getCoordinateTransformBoundingBox(); /* compensate for existing coordinate transform bounding box */ for ( final PointMatch pm : matches ) { final Point p1 = pm.getP1(); final float[] l = p1.getL(); l[ 0 ] += box.x; l[ 1 ] += box.y; } final MovingLeastSquaresTransform2 mlt = new MovingLeastSquaresTransform2(); mlt.setModel( AffineModel2D.class ); mlt.setAlpha( 2.0f ); mlt.setMatches( matches ); patch.appendCoordinateTransform( mlt ); box = patch.getCoordinateTransformBoundingBox(); patch.getAffineTransform().setToTranslation( box.x, box.y ); patch.updateInDatabase( "transform" ); patch.updateBucket(); patch.updateMipMaps(); } Utils.log( "Done." ); } }
true
true
final public void exec( final Param p, final List< Patch > patches, final List< Patch > fixedPatches ) throws Exception { /* free memory */ patches.get( 0 ).getProject().getLoader().releaseAll(); /* create tiles and models for all patches */ final List< AbstractAffineTile2D< ? > > tiles = new ArrayList< AbstractAffineTile2D< ? > >(); final List< AbstractAffineTile2D< ? > > fixedTiles = new ArrayList< AbstractAffineTile2D< ? > > (); Align.tilesFromPatches( p.po, patches, fixedPatches, tiles, fixedTiles ); Align.alignTiles( p.po, tiles, fixedTiles, p.tilesAreInPlace, p.maxNumThreads ); /* Apply the estimated affine transform to patches */ for ( final AbstractAffineTile2D< ? > t : tiles ) t.getPatch().setAffineTransform( t.createAffine() ); Display.update(); /* generate tile pairs for all by now overlapping tiles */ final ArrayList< AbstractAffineTile2D< ? >[] > tilePairs = new ArrayList< AbstractAffineTile2D<?>[] >(); AbstractAffineTile2D.pairOverlappingTiles( tiles, tilePairs ); /* check if there was any pair */ if ( tilePairs.size() == 0 ) { Utils.log( "Elastic montage could not find any overlapping patches after pre-montaging." ); return; } Utils.log( tilePairs.size() + " pairs of patches will be block-matched..." ); /* make pairwise global models local */ final ArrayList< Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform > > pairs = new ArrayList< Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform > >(); /* * The following casting madness is necessary to get this code compiled * with Sun/Oracle Java 6 which otherwise generates an inconvertible * type exception. * * TODO Remove as soon as this bug is fixed in Sun/Oracle javac. */ for ( final AbstractAffineTile2D< ? >[] pair : tilePairs ) { final AbstractAffineModel2D< ? > m; switch ( p.po.desiredModelIndex ) { case 0: final TranslationModel2D t = ( TranslationModel2D )( Object )pair[ 1 ].getModel().createInverse(); t.concatenate( ( TranslationModel2D )( Object )pair[ 0 ].getModel() ); m = t; break; case 1: final RigidModel2D r = ( RigidModel2D )( Object )pair[ 1 ].getModel().createInverse(); r.concatenate( ( RigidModel2D )( Object )pair[ 0 ].getModel() ); m = r; break; case 2: final SimilarityModel2D s = ( SimilarityModel2D )( Object )pair[ 1 ].getModel().createInverse(); s.concatenate( ( SimilarityModel2D )( Object )pair[ 0 ].getModel() ); m = s; break; case 3: final AffineModel2D a = ( AffineModel2D )( Object )pair[ 1 ].getModel().createInverse(); a.concatenate( ( AffineModel2D )( Object )pair[ 0 ].getModel() ); m = a; break; default: m = null; } pairs.add( new Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform >( pair[ 0 ], pair[ 1 ], m ) ); } /* Elastic alignment */ /* Initialization */ final float springTriangleHeightTwice = 2 * ( float )Math.sqrt( 0.75f * p.springLengthSpringMesh * p.springLengthSpringMesh ); final ArrayList< SpringMesh > meshes = new ArrayList< SpringMesh >( tiles.size() ); final HashMap< AbstractAffineTile2D< ? >, SpringMesh > tileMeshMap = new HashMap< AbstractAffineTile2D< ? >, SpringMesh >(); for ( final AbstractAffineTile2D< ? > tile : tiles ) { final double w = tile.getWidth(); final double h = tile.getWidth(); final int numX = Math.max( 2, ( int )Math.ceil( w / p.springLengthSpringMesh ) + 1 ); final int numY = Math.max( 2, ( int )Math.ceil( h / springTriangleHeightTwice ) + 1 ); final float wMesh = ( numX - 1 ) * p.springLengthSpringMesh; final float hMesh = ( numY - 1 ) * springTriangleHeightTwice; final SpringMesh mesh = new SpringMesh( numX, numY, wMesh, hMesh, p.stiffnessSpringMesh, p.maxStretchSpringMesh * p.bmScale, p.dampSpringMesh ); meshes.add( mesh ); tileMeshMap.put( tile, mesh ); } final int blockRadius = Math.max( 32, Util.roundPos( p.springLengthSpringMesh / 2 ) ); /** TODO set this something more than the largest error by the approximate model */ final int searchRadius = ( int )Math.round( p.po.maxEpsilon ); for ( final Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform > pair : pairs ) { final AbstractAffineTile2D< ? > t1 = pair.a; final AbstractAffineTile2D< ? > t2 = pair.b; final SpringMesh m1 = tileMeshMap.get( t1 ); final SpringMesh m2 = tileMeshMap.get( t2 ); ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >(); ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >(); final Collection< Vertex > v1 = m1.getVertices(); final Collection< Vertex > v2 = m2.getVertices(); final String patchName1 = patchName( t1.getPatch() ); final String patchName2 = patchName( t2.getPatch() ); PatchImage pi1 = t1.getPatch().createTransformedImage(); if ( pi1 == null ) { Utils.log( "Patch `" + patchName1 + "' failed generating a transformed image. Skipping..." ); continue; } PatchImage pi2 = t2.getPatch().createTransformedImage(); if ( pi2 == null ) { Utils.log( "Patch `" + patchName2 + "' failed generating a transformed image. Skipping..." ); continue; } FloatProcessor fp1 = ( FloatProcessor )pi1.target.convertToFloat(); ByteProcessor mask1 = pi1.getMask(); FloatProcessor fpMask1 = mask1 == null ? null : scaleByte( mask1 ); FloatProcessor fp2 = ( FloatProcessor )pi2.target.convertToFloat(); ByteProcessor mask2 = pi1.getMask(); FloatProcessor fpMask2 = mask2 == null ? null : scaleByte( mask2 ); BlockMatching.matchByMaximalPMCC( fp1, fp2, fpMask1, fpMask2, p.bmScale, pair.c, blockRadius, blockRadius, searchRadius, searchRadius, p.bmMinR, p.bmRodR, p.bmMaxCurvatureR, v1, pm12, new ErrorStatistic( 1 ) ); IJ.log( "`" + patchName1 + "' > `" + patchName2 + "': found " + pm12.size() + " correspondences." ); // /* <visualisation> */ // // final List< Point > s1 = new ArrayList< Point >(); // // PointMatch.sourcePoints( pm12, s1 ); // // final ImagePlus imp1 = new ImagePlus( i + " >", ip1 ); // // imp1.show(); // // imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null ); // // imp1.setRoi( Util.pointsToPointRoi( s1 ) ); // // imp1.updateAndDraw(); // /* </visualisation> */ BlockMatching.matchByMaximalPMCC( fp2, fp1, fpMask2, fpMask1, p.bmScale, pair.c.createInverse(), blockRadius, blockRadius, searchRadius, searchRadius, p.bmMinR, p.bmRodR, p.bmMaxCurvatureR, v2, pm21, new ErrorStatistic( 1 ) ); IJ.log( "`" + patchName1 + "' > `" + patchName2 + "': found " + pm12.size() + " correspondences." ); /* <visualisation> */ // final List< Point > s2 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm21, s2 ); // final ImagePlus imp2 = new ImagePlus( i + " <", ip2 ); // imp2.show(); // imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null ); // imp2.setRoi( Util.pointsToPointRoi( s2 ) ); // imp2.updateAndDraw(); /* </visualisation> */ for ( final PointMatch pm : pm12 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, 1.0f ) ); m2.addPassiveVertex( p2 ); } for ( final PointMatch pm : pm21 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, 1.0f ) ); m1.addPassiveVertex( p2 ); } } /* initialize */ for ( Map.Entry< AbstractAffineTile2D< ? >, SpringMesh > entry : tileMeshMap.entrySet() ) entry.getValue().init( entry.getKey().getModel() ); /* optimize the meshes */ try { long t0 = System.currentTimeMillis(); IJ.log( "Optimizing spring meshes..." ); SpringMesh.optimizeMeshes( meshes, p.po.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh, p.visualize ); IJ.log( "Done optimizing spring meshes. Took " + ( System.currentTimeMillis() - t0 ) + " ms" ); } catch ( NotEnoughDataPointsException e ) { Utils.log( "There were not enough data points to get the spring mesh optimizing." ); e.printStackTrace(); return; } /* apply */ for ( Map.Entry< AbstractAffineTile2D< ? >, SpringMesh > entry : tileMeshMap.entrySet() ) { final AbstractAffineTile2D< ? > tile = entry.getKey(); final Patch patch = tile.getPatch(); final SpringMesh mesh = entry.getValue(); final Set< PointMatch > matches = mesh.getVA().keySet(); Rectangle box = patch.getCoordinateTransformBoundingBox(); /* compensate for existing coordinate transform bounding box */ for ( final PointMatch pm : matches ) { final Point p1 = pm.getP1(); final float[] l = p1.getL(); l[ 0 ] += box.x; l[ 1 ] += box.y; } final MovingLeastSquaresTransform2 mlt = new MovingLeastSquaresTransform2(); mlt.setModel( AffineModel2D.class ); mlt.setAlpha( 2.0f ); mlt.setMatches( matches ); patch.appendCoordinateTransform( mlt ); box = patch.getCoordinateTransformBoundingBox(); patch.getAffineTransform().setToTranslation( box.x, box.y ); patch.updateInDatabase( "transform" ); patch.updateBucket(); patch.updateMipMaps(); } Utils.log( "Done." ); }
final public void exec( final Param p, final List< Patch > patches, final List< Patch > fixedPatches ) throws Exception { /* free memory */ patches.get( 0 ).getProject().getLoader().releaseAll(); /* create tiles and models for all patches */ final List< AbstractAffineTile2D< ? > > tiles = new ArrayList< AbstractAffineTile2D< ? > >(); final List< AbstractAffineTile2D< ? > > fixedTiles = new ArrayList< AbstractAffineTile2D< ? > > (); Align.tilesFromPatches( p.po, patches, fixedPatches, tiles, fixedTiles ); Align.alignTiles( p.po, tiles, fixedTiles, p.tilesAreInPlace, p.maxNumThreads ); /* Apply the estimated affine transform to patches */ for ( final AbstractAffineTile2D< ? > t : tiles ) t.getPatch().setAffineTransform( t.createAffine() ); Display.update(); /* generate tile pairs for all by now overlapping tiles */ final ArrayList< AbstractAffineTile2D< ? >[] > tilePairs = new ArrayList< AbstractAffineTile2D<?>[] >(); AbstractAffineTile2D.pairOverlappingTiles( tiles, tilePairs ); /* check if there was any pair */ if ( tilePairs.size() == 0 ) { Utils.log( "Elastic montage could not find any overlapping patches after pre-montaging." ); return; } Utils.log( tilePairs.size() + " pairs of patches will be block-matched..." ); /* make pairwise global models local */ final ArrayList< Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform > > pairs = new ArrayList< Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform > >(); /* * The following casting madness is necessary to get this code compiled * with Sun/Oracle Java 6 which otherwise generates an inconvertible * type exception. * * TODO Remove as soon as this bug is fixed in Sun/Oracle javac. */ for ( final AbstractAffineTile2D< ? >[] pair : tilePairs ) { final AbstractAffineModel2D< ? > m; switch ( p.po.desiredModelIndex ) { case 0: final TranslationModel2D t = ( TranslationModel2D )( Object )pair[ 1 ].getModel().createInverse(); t.concatenate( ( TranslationModel2D )( Object )pair[ 0 ].getModel() ); m = t; break; case 1: final RigidModel2D r = ( RigidModel2D )( Object )pair[ 1 ].getModel().createInverse(); r.concatenate( ( RigidModel2D )( Object )pair[ 0 ].getModel() ); m = r; break; case 2: final SimilarityModel2D s = ( SimilarityModel2D )( Object )pair[ 1 ].getModel().createInverse(); s.concatenate( ( SimilarityModel2D )( Object )pair[ 0 ].getModel() ); m = s; break; case 3: final AffineModel2D a = ( AffineModel2D )( Object )pair[ 1 ].getModel().createInverse(); a.concatenate( ( AffineModel2D )( Object )pair[ 0 ].getModel() ); m = a; break; default: m = null; } pairs.add( new Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform >( pair[ 0 ], pair[ 1 ], m ) ); } /* Elastic alignment */ /* Initialization */ final float springTriangleHeightTwice = 2 * ( float )Math.sqrt( 0.75f * p.springLengthSpringMesh * p.springLengthSpringMesh ); final ArrayList< SpringMesh > meshes = new ArrayList< SpringMesh >( tiles.size() ); final HashMap< AbstractAffineTile2D< ? >, SpringMesh > tileMeshMap = new HashMap< AbstractAffineTile2D< ? >, SpringMesh >(); for ( final AbstractAffineTile2D< ? > tile : tiles ) { final double w = tile.getWidth(); final double h = tile.getWidth(); final int numX = Math.max( 2, ( int )Math.ceil( w / p.springLengthSpringMesh ) + 1 ); final int numY = Math.max( 2, ( int )Math.ceil( h / springTriangleHeightTwice ) + 1 ); final float wMesh = ( numX - 1 ) * p.springLengthSpringMesh; final float hMesh = ( numY - 1 ) * springTriangleHeightTwice; final SpringMesh mesh = new SpringMesh( numX, numY, wMesh, hMesh, p.stiffnessSpringMesh, p.maxStretchSpringMesh * p.bmScale, p.dampSpringMesh ); meshes.add( mesh ); tileMeshMap.put( tile, mesh ); } final int blockRadius = Math.max( 32, Util.roundPos( p.springLengthSpringMesh / 2 ) ); /** TODO set this something more than the largest error by the approximate model */ final int searchRadius = ( int )Math.round( p.po.maxEpsilon ); for ( final Triple< AbstractAffineTile2D< ? >, AbstractAffineTile2D< ? >, InvertibleCoordinateTransform > pair : pairs ) { final AbstractAffineTile2D< ? > t1 = pair.a; final AbstractAffineTile2D< ? > t2 = pair.b; final SpringMesh m1 = tileMeshMap.get( t1 ); final SpringMesh m2 = tileMeshMap.get( t2 ); ArrayList< PointMatch > pm12 = new ArrayList< PointMatch >(); ArrayList< PointMatch > pm21 = new ArrayList< PointMatch >(); final Collection< Vertex > v1 = m1.getVertices(); final Collection< Vertex > v2 = m2.getVertices(); final String patchName1 = patchName( t1.getPatch() ); final String patchName2 = patchName( t2.getPatch() ); PatchImage pi1 = t1.getPatch().createTransformedImage(); if ( pi1 == null ) { Utils.log( "Patch `" + patchName1 + "' failed generating a transformed image. Skipping..." ); continue; } PatchImage pi2 = t2.getPatch().createTransformedImage(); if ( pi2 == null ) { Utils.log( "Patch `" + patchName2 + "' failed generating a transformed image. Skipping..." ); continue; } FloatProcessor fp1 = ( FloatProcessor )pi1.target.convertToFloat(); ByteProcessor mask1 = pi1.getMask(); FloatProcessor fpMask1 = mask1 == null ? null : scaleByte( mask1 ); FloatProcessor fp2 = ( FloatProcessor )pi2.target.convertToFloat(); ByteProcessor mask2 = pi2.getMask(); FloatProcessor fpMask2 = mask2 == null ? null : scaleByte( mask2 ); BlockMatching.matchByMaximalPMCC( fp1, fp2, fpMask1, fpMask2, p.bmScale, pair.c, blockRadius, blockRadius, searchRadius, searchRadius, p.bmMinR, p.bmRodR, p.bmMaxCurvatureR, v1, pm12, new ErrorStatistic( 1 ) ); IJ.log( "`" + patchName1 + "' > `" + patchName2 + "': found " + pm12.size() + " correspondences." ); // /* <visualisation> */ // // final List< Point > s1 = new ArrayList< Point >(); // // PointMatch.sourcePoints( pm12, s1 ); // // final ImagePlus imp1 = new ImagePlus( i + " >", ip1 ); // // imp1.show(); // // imp1.setOverlay( BlockMatching.illustrateMatches( pm12 ), Color.yellow, null ); // // imp1.setRoi( Util.pointsToPointRoi( s1 ) ); // // imp1.updateAndDraw(); // /* </visualisation> */ BlockMatching.matchByMaximalPMCC( fp2, fp1, fpMask2, fpMask1, p.bmScale, pair.c.createInverse(), blockRadius, blockRadius, searchRadius, searchRadius, p.bmMinR, p.bmRodR, p.bmMaxCurvatureR, v2, pm21, new ErrorStatistic( 1 ) ); IJ.log( "`" + patchName1 + "' > `" + patchName2 + "': found " + pm12.size() + " correspondences." ); /* <visualisation> */ // final List< Point > s2 = new ArrayList< Point >(); // PointMatch.sourcePoints( pm21, s2 ); // final ImagePlus imp2 = new ImagePlus( i + " <", ip2 ); // imp2.show(); // imp2.setOverlay( BlockMatching.illustrateMatches( pm21 ), Color.yellow, null ); // imp2.setRoi( Util.pointsToPointRoi( s2 ) ); // imp2.updateAndDraw(); /* </visualisation> */ for ( final PointMatch pm : pm12 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, 1.0f ) ); m2.addPassiveVertex( p2 ); } for ( final PointMatch pm : pm21 ) { final Vertex p1 = ( Vertex )pm.getP1(); final Vertex p2 = new Vertex( pm.getP2() ); p1.addSpring( p2, new Spring( 0, 1.0f ) ); m1.addPassiveVertex( p2 ); } } /* initialize */ for ( Map.Entry< AbstractAffineTile2D< ? >, SpringMesh > entry : tileMeshMap.entrySet() ) entry.getValue().init( entry.getKey().getModel() ); /* optimize the meshes */ try { long t0 = System.currentTimeMillis(); IJ.log( "Optimizing spring meshes..." ); SpringMesh.optimizeMeshes( meshes, p.po.maxEpsilon, p.maxIterationsSpringMesh, p.maxPlateauwidthSpringMesh, p.visualize ); IJ.log( "Done optimizing spring meshes. Took " + ( System.currentTimeMillis() - t0 ) + " ms" ); } catch ( NotEnoughDataPointsException e ) { Utils.log( "There were not enough data points to get the spring mesh optimizing." ); e.printStackTrace(); return; } /* apply */ for ( Map.Entry< AbstractAffineTile2D< ? >, SpringMesh > entry : tileMeshMap.entrySet() ) { final AbstractAffineTile2D< ? > tile = entry.getKey(); final Patch patch = tile.getPatch(); final SpringMesh mesh = entry.getValue(); final Set< PointMatch > matches = mesh.getVA().keySet(); Rectangle box = patch.getCoordinateTransformBoundingBox(); /* compensate for existing coordinate transform bounding box */ for ( final PointMatch pm : matches ) { final Point p1 = pm.getP1(); final float[] l = p1.getL(); l[ 0 ] += box.x; l[ 1 ] += box.y; } final MovingLeastSquaresTransform2 mlt = new MovingLeastSquaresTransform2(); mlt.setModel( AffineModel2D.class ); mlt.setAlpha( 2.0f ); mlt.setMatches( matches ); patch.appendCoordinateTransform( mlt ); box = patch.getCoordinateTransformBoundingBox(); patch.getAffineTransform().setToTranslation( box.x, box.y ); patch.updateInDatabase( "transform" ); patch.updateBucket(); patch.updateMipMaps(); } Utils.log( "Done." ); }
diff --git a/CheMet/Resource/src/main/java/uk/ac/ebi/resource/Preference.java b/CheMet/Resource/src/main/java/uk/ac/ebi/resource/Preference.java index c1a0c2c2..aa4ab20c 100644 --- a/CheMet/Resource/src/main/java/uk/ac/ebi/resource/Preference.java +++ b/CheMet/Resource/src/main/java/uk/ac/ebi/resource/Preference.java @@ -1,172 +1,173 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.ac.ebi.resource; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.List; import java.util.prefs.Preferences; /** * Enumeration organises user and system preferences * * @author johnmay */ public enum Preference { /* * TEST */ LIST_TEST(Type.TEST, Access.USER, new ArrayList<String>()), /* * IO */ BUFFER_SIZE(Type.IO, Access.USER, 2048), RECENT_FILES(Type.IO, Access.USER, ""), /* * Resource */ CHEMICAL_IDENTIFIER_FORMAT(Type.IDENTIFIER, Access.USER, "M/%05d"), PROTEIN_IDENTIFIER_FORMAT(Type.IDENTIFIER, Access.USER, "P/%05d"), GENE_IDENTIFIER_FORMAT(Type.IDENTIFIER, Access.USER, "G/%05d"), REACTION_IDENTIFIER_FORMAT(Type.IDENTIFIER, Access.USER, "R/%d"), /* * Tool */ CPLEX_PATH(Type.TOOL, Access.USER, ""), BLASTP_PATH(Type.TOOL, Access.USER, ""), BLASTP_VERSION(Type.TOOL, Access.USER, ""); public static final String LIST_SEPARATOR_SPLIT = "(?<!\\\\);"; public static final String LIST_SEPARATOR = ";"; public static final String LIST_SEPARATOR_ESCAPED = "\\\\;"; private String key; private Type type; private Access access; private Object defaultValue; private Preference(Type type, Access access, Object defaultValue) { this.type = type; this.access = access; this.defaultValue = defaultValue; this.key = type + "." + name(); } /** * Access the string value of the preference * * @return */ public String get() { return access.getPreferences().get(key, defaultValue.toString()); } /** * Access a list of string for the preference * * @return */ public List<String> getList() { String rawValue = get(); List<String> values = new ArrayList<String>(); for (String value : rawValue.split(LIST_SEPARATOR_SPLIT)) { values.add(value.replaceAll(LIST_SEPARATOR_ESCAPED, LIST_SEPARATOR)); } return values; } /** * Access a integer value from the preference * * @return */ public int getInteger() { if (!(defaultValue instanceof Integer)) { throw new InvalidParameterException("Preference " + key + " default value must be an integer"); } return access.getPreferences().getInt(key, (Integer) defaultValue); } /** * Access a double value from the preference * * @return */ public double getDouble() { if (!(defaultValue instanceof Double)) { throw new InvalidParameterException("Preference " + key + " default value must be an double"); } return access.getPreferences().getDouble(key, (Double) defaultValue); } public void put(String value) { access.getPreferences().put(key, value); } /** * Puts a list into preferences * * @param values */ public void putList(List<String> values) { StringBuilder sb = new StringBuilder(values.size() * 14); for (String value : values) { sb.append(value.replaceAll(LIST_SEPARATOR, LIST_SEPARATOR_ESCAPED)); - if (value.equals(values.get(values.size() - 1))) { + if (!value.equals(values.get(values.size() - 1))) { sb.append(LIST_SEPARATOR); } } put(sb.toString()); + System.out.println("putting list:" + sb.toString()); } public void putInteger(int value) { access.getPreferences().putInt(key, value); } public void putDouble(int value) { access.getPreferences().putDouble(key, value); } private enum Access { USER(Preferences.userNodeForPackage(Preference.class)), SYSTEM(Preferences.systemNodeForPackage(Preference.class)); private final Preferences preferences; private Access(Preferences preferences) { this.preferences = preferences; } public Preferences getPreferences() { return preferences; } }; private enum Type { IO, IDENTIFIER, TOOL, TEST; }; }
false
true
public void putList(List<String> values) { StringBuilder sb = new StringBuilder(values.size() * 14); for (String value : values) { sb.append(value.replaceAll(LIST_SEPARATOR, LIST_SEPARATOR_ESCAPED)); if (value.equals(values.get(values.size() - 1))) { sb.append(LIST_SEPARATOR); } } put(sb.toString()); }
public void putList(List<String> values) { StringBuilder sb = new StringBuilder(values.size() * 14); for (String value : values) { sb.append(value.replaceAll(LIST_SEPARATOR, LIST_SEPARATOR_ESCAPED)); if (!value.equals(values.get(values.size() - 1))) { sb.append(LIST_SEPARATOR); } } put(sb.toString()); System.out.println("putting list:" + sb.toString()); }
diff --git a/eclihand/webapp/src/main/java/com/pedrero/eclihand/ui/panel/TeamsScreen.java b/eclihand/webapp/src/main/java/com/pedrero/eclihand/ui/panel/TeamsScreen.java index f1fccab..62f2bd2 100644 --- a/eclihand/webapp/src/main/java/com/pedrero/eclihand/ui/panel/TeamsScreen.java +++ b/eclihand/webapp/src/main/java/com/pedrero/eclihand/ui/panel/TeamsScreen.java @@ -1,104 +1,105 @@ package com.pedrero.eclihand.ui.panel; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; import com.pedrero.eclihand.controller.panel.TeamsPanelController; import com.pedrero.eclihand.model.dto.TeamDto; import com.pedrero.eclihand.navigation.EclihandPlace; import com.pedrero.eclihand.navigation.EclihandViewImpl; import com.pedrero.eclihand.navigation.places.TeamsPlace; import com.pedrero.eclihand.ui.table.GenericTable; import com.pedrero.eclihand.utils.text.MessageResolver; import com.pedrero.eclihand.utils.ui.EclihandLayoutFactory; import com.pedrero.eclihand.utils.ui.EclihandUiFactory; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Layout; @Component(value = "teamsScreen") @Scope(value = BeanDefinition.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS) public class TeamsScreen extends EclihandViewImpl { private static final Logger LOGGER = LoggerFactory .getLogger(TeamsScreen.class); @Resource private MessageResolver messageResolver; @Resource private TeamsPanelController teamsPanelController; @Resource(name = "teamTableForTeamsPanel") private GenericTable<TeamDto> teamTable; @Resource private EclihandLayoutFactory eclihandLayoutFactory; @Resource private EclihandUiFactory eclihandUiFactory; @Resource private TeamsPlace teamsPlace; private Button createNewTeamButton; /** * */ private static final long serialVersionUID = 5954828103989095039L; @PostConstruct protected void postConstruct() { LOGGER.info("initializing TeamsPanel"); this.setCaption(messageResolver.getMessage("teams.panel.title")); Layout layout = eclihandLayoutFactory.createCommonVerticalLayout(); this.setContent(layout); this.createNewTeamButton = eclihandUiFactory.createButton(); this.createNewTeamButton.setCaption(messageResolver .getMessage("players.create.new")); this.createNewTeamButton.addClickListener(new ClickListener() { /** * */ private static final long serialVersionUID = -7117656998497854385L; @Override public void buttonClick(ClickEvent event) { teamsPanelController.openNewTeamForm(); } }); - layout.addComponent(teamTable); + // FIXME : Ajout de la table des �quipes + // layout.addComponent(teamTable); layout.addComponent(createNewTeamButton); teamTable.feed(teamsPanelController.searchTeamsToDisplay()); } public GenericTable<TeamDto> getTeamsTable() { return teamTable; } public void refreshTeams(List<TeamDto> teams) { teamTable.removeAllDataObjects(); } @Override public EclihandPlace retrieveAssociatedPlace() { return teamsPlace; } }
true
true
protected void postConstruct() { LOGGER.info("initializing TeamsPanel"); this.setCaption(messageResolver.getMessage("teams.panel.title")); Layout layout = eclihandLayoutFactory.createCommonVerticalLayout(); this.setContent(layout); this.createNewTeamButton = eclihandUiFactory.createButton(); this.createNewTeamButton.setCaption(messageResolver .getMessage("players.create.new")); this.createNewTeamButton.addClickListener(new ClickListener() { /** * */ private static final long serialVersionUID = -7117656998497854385L; @Override public void buttonClick(ClickEvent event) { teamsPanelController.openNewTeamForm(); } }); layout.addComponent(teamTable); layout.addComponent(createNewTeamButton); teamTable.feed(teamsPanelController.searchTeamsToDisplay()); }
protected void postConstruct() { LOGGER.info("initializing TeamsPanel"); this.setCaption(messageResolver.getMessage("teams.panel.title")); Layout layout = eclihandLayoutFactory.createCommonVerticalLayout(); this.setContent(layout); this.createNewTeamButton = eclihandUiFactory.createButton(); this.createNewTeamButton.setCaption(messageResolver .getMessage("players.create.new")); this.createNewTeamButton.addClickListener(new ClickListener() { /** * */ private static final long serialVersionUID = -7117656998497854385L; @Override public void buttonClick(ClickEvent event) { teamsPanelController.openNewTeamForm(); } }); // FIXME : Ajout de la table des �quipes // layout.addComponent(teamTable); layout.addComponent(createNewTeamButton); teamTable.feed(teamsPanelController.searchTeamsToDisplay()); }
diff --git a/org.spoofax.jsglr/src/org/spoofax/jsglr/ParserHistory.java b/org.spoofax.jsglr/src/org/spoofax/jsglr/ParserHistory.java index 51f6a057..b02343ed 100644 --- a/org.spoofax.jsglr/src/org/spoofax/jsglr/ParserHistory.java +++ b/org.spoofax.jsglr/src/org/spoofax/jsglr/ParserHistory.java @@ -1,247 +1,247 @@ package org.spoofax.jsglr; import java.io.IOException; import java.util.ArrayList; public class ParserHistory { private final static int MAX_SIZE_NEW_LINE_POINTS = 150; private final static int MIN_SIZE_NEW_LINE_POINTS = 50; private IndentationHandler indentHandler; private IndentationHandler recoveryIndentHandler; private ArrayList<IndentInfo> newLinePoints; public char[] recoverTokenStream; private int recoverTokenCount; private int tokenIndex; public int getTokenIndex() { return tokenIndex; } public int getIndexLastToken() { return recoverTokenCount-1; } public void setTokenIndex(int tokenIndex) { this.tokenIndex = tokenIndex; } public ParserHistory(){ newLinePoints=new ArrayList<IndentInfo>(); reset(); } private void reset(){ newLinePoints.clear(); recoverTokenStream = new char[5000]; recoverTokenCount = 0; tokenIndex=0; indentHandler = new IndentationHandler(); recoveryIndentHandler=new IndentationHandler(); } public void resetRecoveryIndentHandler(int indentValue){ recoveryIndentHandler=new IndentationHandler(); recoveryIndentHandler.setInLeftMargin(true); recoveryIndentHandler.setIndentValue(indentValue); } /* * Set current token of parser based on recover tokens or read from new tokens */ public void readRecoverToken(SGLR myParser, boolean keepRecoveredLines) throws IOException{ if (hasFinishedRecoverTokens()) { if(myParser.currentToken!=SGLR.EOF){ - if(getIndexLastToken()>0 && recoverTokenStream[getIndexLastToken()]!=SGLR.EOF){ + if(getIndexLastToken()>=0 && recoverTokenStream[getIndexLastToken()]!=SGLR.EOF){ myParser.readNextToken(); indentHandler.updateIndentation(myParser.currentToken); keepToken((char)myParser.currentToken); if(indentHandler.lineMarginEnded() || myParser.currentToken==SGLR.EOF) keepNewLinePoint(myParser, myParser.tokensSeen-1, true, indentHandler); } } } else if(tokenIndex<0 || tokenIndex>recoverTokenCount){ myParser.currentToken =SGLR.EOF; System.err.println("Unexpected token index"+tokenIndex); } else{ myParser.currentToken = recoverTokenStream[tokenIndex]; if(keepRecoveredLines){ recoveryIndentHandler.updateIndentation(myParser.currentToken); if(recoveryIndentHandler.lineMarginEnded() || myParser.currentToken==SGLR.EOF) keepNewLinePoint(myParser, tokenIndex, false, recoveryIndentHandler); } } tokenIndex++; } public boolean hasFinishedRecoverTokens() { return tokenIndex >= recoverTokenCount; } public int getTokensSeenStartLine(int tokPosition){ int tokIndexLine=tokPosition; while (recoverTokenStream[tokIndexLine] != '\n' && tokIndexLine>0) { tokIndexLine-=1; } return tokIndexLine; } public void keepTokenAndState(SGLR myParser) { indentHandler.updateIndentation(myParser.currentToken); keepToken((char)myParser.currentToken); tokenIndex++; if(indentHandler.lineMarginEnded() || myParser.currentToken==SGLR.EOF) keepNewLinePoint(myParser, myParser.tokensSeen-1, false, indentHandler); } public void keepInitialState(SGLR myParser) { IndentInfo newLinePoint= new IndentInfo(0, 0, 0); newLinePoint.fillStackNodes(myParser.activeStacks); newLinePoints.add(newLinePoint); } private void keepToken(char currentToken) { if(getIndexLastToken()>0 && recoverTokenStream[getIndexLastToken()]==SGLR.EOF) return; recoverTokenStream[recoverTokenCount++] = currentToken; if (recoverTokenCount == recoverTokenStream.length) { char[] copy = recoverTokenStream; recoverTokenStream = new char[recoverTokenStream.length * 2]; System.arraycopy(copy, 0, recoverTokenStream, 0, copy.length); } } private void keepNewLinePoint(SGLR myParser, int tokSeen ,boolean inRecoverMode, IndentationHandler anIndentHandler) { int indent = anIndentHandler.getIndentValue(); IndentInfo newLinePoint= new IndentInfo(myParser.lineNumber, tokSeen, indent); newLinePoints.add(newLinePoint); //System.out.println(newLinePoints.size()-1+" NEWLINE ("+newLinePoint.getIndentValue()+")"+newLinePoint.getTokensSeen()); if(!inRecoverMode){ newLinePoint.fillStackNodes(myParser.activeStacks); if(newLinePoints.size()> MAX_SIZE_NEW_LINE_POINTS) removeOldPoints(); } } private void removeOldPoints() { int firstPointIndex = nrOfLines()-MIN_SIZE_NEW_LINE_POINTS; ArrayList<IndentInfo> shrinkedList = new ArrayList<IndentInfo>(); shrinkedList.ensureCapacity(newLinePoints.size()); shrinkedList.addAll(newLinePoints.subList(firstPointIndex, newLinePoints.size()-1)); newLinePoints = shrinkedList; } public String getFragment(int startTok, int endTok) { String fragment=""; for (int i = startTok; i <= endTok; i++) { if(i >= recoverTokenCount) break; fragment+= recoverTokenStream[i]; } return fragment; } public String getFragment(StructureSkipSuggestion skip) { if(skip.getEndSkip().getTokensSeen() < skip.getStartSkip().getTokensSeen()){ System.err.println("Startskip > endskip"); //System.err.println(getFragment(skip.getEndSkip().getTokensSeen(), skip.getEndSkip().getTokensSeen())); return "--Wrong Fragment --"; } String fragment=""; for (int i = skip.getStartSkip().getTokensSeen(); i <= skip.getEndSkip().getTokensSeen()-1; i++) { if(i >= recoverTokenCount) break; fragment+= recoverTokenStream[i]; } String correctedFragment=fragment.substring(skip.getAdditionalTokens().length); return correctedFragment; } public String readLine(int StartTok) { String fragment=""; int pos=StartTok; char currentTok=' '; while(currentTok!='\n' && currentTok!=SGLR.EOF && pos<recoverTokenCount) { currentTok=recoverTokenStream[pos]; fragment+= currentTok; pos++; } return fragment; } private int nrOfLines(){ return newLinePoints.size(); } public IndentInfo getLine(int index){ if(index < 0 || index > getIndexLastLine()) return null; return newLinePoints.get(index); } public IndentInfo getLastLine(){ return newLinePoints.get(newLinePoints.size()-1); } public int getIndexLastLine(){ return newLinePoints.size()-1; } public ArrayList<IndentInfo> getLinesFromTo(int startIndex, int endLocation) { int indexLine = startIndex; ArrayList<IndentInfo> result=new ArrayList<IndentInfo>(); IndentInfo firstLine = newLinePoints.get(indexLine); while(indexLine < newLinePoints.size()){ firstLine = newLinePoints.get(indexLine); if(firstLine.getTokensSeen() < endLocation){ result.add(firstLine); indexLine++; } else{ indexLine=newLinePoints.size(); } } return result; } public void deleteLinesFrom(int startIndexErrorFragment) { if(startIndexErrorFragment>=0 && startIndexErrorFragment<newLinePoints.size()-1){ ArrayList<IndentInfo> shrinkedList=new ArrayList<IndentInfo>(); shrinkedList.addAll(newLinePoints.subList(0, startIndexErrorFragment)); newLinePoints=shrinkedList; } else if (startIndexErrorFragment > newLinePoints.size()-1){ System.err.println("StartIndex Error Fragment: "+startIndexErrorFragment); System.err.println("Numeber Of Lines in History: : "+newLinePoints.size()); System.err.println("Unexpected index of history new-line-points"); } } public void logHistory(){ for (int i = 0; i < newLinePoints.size()-1; i++) { IndentInfo currLine=newLinePoints.get(i); IndentInfo nextLine=newLinePoints.get(i+1); String stackDescription=""; for (Frame node : currLine.getStackNodes()) { stackDescription+=node.state.stateNumber+";"; } System.out.print("("+i+")"+"["+currLine.getIndentValue()+"]"+"{"+stackDescription+"}"+getFragment(currLine.getTokensSeen(), nextLine.getTokensSeen()-1)); } IndentInfo currLine=newLinePoints.get(newLinePoints.size()-1); System.out.print("("+(newLinePoints.size()-1)+")"+"["+currLine.getIndentValue()+"]"+getFragment(currLine.getTokensSeen(), getIndexLastToken()-1)); } public int getLineOfTokenPosition(int tokPos) { for (int i = 1; i < newLinePoints.size(); i++) { IndentInfo line=newLinePoints.get(i); if(line.getTokensSeen()>tokPos) return i-1; } return newLinePoints.size()-1; } }
true
true
public void readRecoverToken(SGLR myParser, boolean keepRecoveredLines) throws IOException{ if (hasFinishedRecoverTokens()) { if(myParser.currentToken!=SGLR.EOF){ if(getIndexLastToken()>0 && recoverTokenStream[getIndexLastToken()]!=SGLR.EOF){ myParser.readNextToken(); indentHandler.updateIndentation(myParser.currentToken); keepToken((char)myParser.currentToken); if(indentHandler.lineMarginEnded() || myParser.currentToken==SGLR.EOF) keepNewLinePoint(myParser, myParser.tokensSeen-1, true, indentHandler); } } } else if(tokenIndex<0 || tokenIndex>recoverTokenCount){ myParser.currentToken =SGLR.EOF; System.err.println("Unexpected token index"+tokenIndex); } else{ myParser.currentToken = recoverTokenStream[tokenIndex]; if(keepRecoveredLines){ recoveryIndentHandler.updateIndentation(myParser.currentToken); if(recoveryIndentHandler.lineMarginEnded() || myParser.currentToken==SGLR.EOF) keepNewLinePoint(myParser, tokenIndex, false, recoveryIndentHandler); } } tokenIndex++; }
public void readRecoverToken(SGLR myParser, boolean keepRecoveredLines) throws IOException{ if (hasFinishedRecoverTokens()) { if(myParser.currentToken!=SGLR.EOF){ if(getIndexLastToken()>=0 && recoverTokenStream[getIndexLastToken()]!=SGLR.EOF){ myParser.readNextToken(); indentHandler.updateIndentation(myParser.currentToken); keepToken((char)myParser.currentToken); if(indentHandler.lineMarginEnded() || myParser.currentToken==SGLR.EOF) keepNewLinePoint(myParser, myParser.tokensSeen-1, true, indentHandler); } } } else if(tokenIndex<0 || tokenIndex>recoverTokenCount){ myParser.currentToken =SGLR.EOF; System.err.println("Unexpected token index"+tokenIndex); } else{ myParser.currentToken = recoverTokenStream[tokenIndex]; if(keepRecoveredLines){ recoveryIndentHandler.updateIndentation(myParser.currentToken); if(recoveryIndentHandler.lineMarginEnded() || myParser.currentToken==SGLR.EOF) keepNewLinePoint(myParser, tokenIndex, false, recoveryIndentHandler); } } tokenIndex++; }
diff --git a/src/com/example/hushcal/SyncCal.java b/src/com/example/hushcal/SyncCal.java index bcae4ca..2d404e6 100644 --- a/src/com/example/hushcal/SyncCal.java +++ b/src/com/example/hushcal/SyncCal.java @@ -1,272 +1,272 @@ package com.example.hushcal; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class SyncCal extends Activity { private static HashMap<String, Long> cal_map; private static EventTableHandler handler; private static HashMap<String, Event> events_list; //list of events constructed from data taken from android calendar private static HashMap<String, String> event_status_map; //list of event names and statuses taken from hushcal database static Context app_context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.synccal); app_context = getApplicationContext(); handler = new EventTableHandler(this); /** * generate spinner dropdown menu and populate with calendars from phone */ final Spinner calendar_list = (Spinner)findViewById(R.id.calendar_list); calendar_list.setOnItemSelectedListener(spinner_listener); cal_map = getCalendars(); ArrayList<String> selector_array = new ArrayList<String>(); selector_array.addAll(cal_map.keySet()); List<Event> events_list = handler.getAllEvents(); //turn this into event_status_map event_status_map = new HashMap<String, String>(); for (Event event : events_list) { String title = event.getName(); String status = event.getStatus(); event_status_map.put(title, status); } ArrayAdapter<String> spinner_array = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, selector_array); spinner_array.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); calendar_list.setAdapter(spinner_array); } // The indices for the projection array above. private static final int CALENDAR_ID_INDEX = 0; private static final int CALENDAR_DISPLAY_NAME_INDEX = 1; //returns a hashmap of all available calendars and their ids private HashMap<String, Long> getCalendars() { HashMap<String, Long> results_list = new HashMap<String, Long>(); if (android.os.Build.VERSION.SDK_INT >= 4.0) { // Run query Cursor cur = null; ContentResolver cr = getContentResolver(); Uri uri = Calendars.CONTENT_URI; // Submit the query and get a Cursor object back. cur = cr.query(uri, null, null, null, null); //get list of calendars from cursor object while(cur.moveToNext()) { long cal_id = cur.getLong(CALENDAR_ID_INDEX); String cal_display_name = cur.getString(CALENDAR_DISPLAY_NAME_INDEX); results_list.put(cal_display_name, cal_id); } return results_list; } else { //TODO: get calendars from google calendar api - for previous android versions // (higher priority now, should start working on this right after release) return results_list; } } // Projection array. Creating indices for this array instead of doing // dynamic lookups improves performance. public static final String[] EVENT_PROJECTION = new String[] { Events._ID, // 0 Events.TITLE, // 1 Events.DTSTART, // 2 Events.DTEND // 3 }; // The indices for the projection array above. private static final int EVENT_ID_INDEX = 0; private static final int EVENT_TITLE_INDEX = 1; private static final int EVENT_START_INDEX = 2; private static final int EVENT_END_INDEX = 3; //returns an arraylist of events constructed from data queried from the android calendar private HashMap<String, Event> getCalendarEvents(String calendar_name) { HashMap<String, Event> events = new HashMap<String, Event>(); String calendarID = cal_map.get(calendar_name).toString(); if (android.os.Build.VERSION.SDK_INT >= 4.0) { Cursor cur = null; ContentResolver cr = getContentResolver(); Uri uri = Events.CONTENT_URI; String selection = "((" + Events.CALENDAR_ID + " = ?) AND (" + Events.DTSTART + " >= ?))"; String [] selectionArgs = new String[] {calendarID, Calendar.getInstance().getTimeInMillis() + ""}; String sortOrder = Events.DTSTART + " ASC"; cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, sortOrder); while(cur.moveToNext()) { String event_id = cur.getString(EVENT_ID_INDEX); String event_title = cur.getString(EVENT_TITLE_INDEX); Calendar event_start = Calendar.getInstance(); event_start.setTimeInMillis(cur.getLong(EVENT_START_INDEX)); Calendar event_end = Calendar.getInstance(); event_end.setTimeInMillis(cur.getLong(EVENT_END_INDEX)); Event event = new Event(Integer.parseInt(event_id), event_title, event_start, event_end, null); if (event != null) { events.put(event_title, event); } } } else { //TODO: get events from google calendar api - for previous android versions // (higher priority, should start working on this right after release) } return events; } OnCheckedChangeListener event_status_listener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton checkedRadioButton = (RadioButton) findViewById(checkedId); if (checkedRadioButton != null) { String status = ""; switch(checkedRadioButton.getId()) { case R.id.event_sound: status = "sound"; break; case R.id.event_silence: status = "silence"; break; case R.id.event_vibrate: status = "vibrate"; break; } RelativeLayout parent = (RelativeLayout) group.getParent(); String event_name = ((TextView) parent.getChildAt(0)).getText().toString(); //If the event is already in hushcal database, then update its status if (event_status_map.keySet().contains(event_name)) { //get the id from the Event with name event_name //int event_id = events_list.get(event_name).getId(); Event updated_event = events_list.get(event_name); //new Event(event_id, event_name, null, null, status); updated_event.setStatus(status); //TODO: unschedule old event (might not have to do this because of PendingIntent.FLAG_UPDATE_CURRENT, need to test) int updated = handler.updateEvent(updated_event); EventScheduler.schedule(app_context, updated_event); } //otherwise (if you change an event taken from the android calendar but is not in //hushcal database yet) add event to hushcal database with new status else { Event updated_event = events_list.get(event_name); updated_event.setStatus(status); handler.addEvent(updated_event); EventScheduler.schedule(app_context, updated_event); } } } }; OnItemSelectedListener spinner_listener = new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { List<Event> tmp_events_list = handler.getAllEvents(); //turn this into event_status_map event_status_map = new HashMap<String, String>(); for (Event event : tmp_events_list) { String title = event.getName(); String status = event.getStatus(); event_status_map.put(title, status); } String selected = parent.getItemAtPosition(pos).toString(); events_list = getCalendarEvents(selected); TableLayout events_table = (TableLayout)findViewById(R.id.event_table); events_table.removeAllViews(); for (String event : events_list.keySet()) { //make row in table including event name and silence/vibrate radio button //and maybe a pop up that shows more info about event, such as start and //end time. TableRow tr_container = (TableRow)getLayoutInflater().inflate(R.layout.event_row_layout, null); RelativeLayout tr = (RelativeLayout)tr_container.getChildAt(0); TextView text = (TextView) tr.getChildAt(0); text.setText(event); - events_table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, + events_table.addView(tr_container, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); RadioGroup status_group = (RadioGroup) tr.getChildAt(1); //when you generate the table, populate it's radio buttons based on their //status in database String status; try { if (event_status_map.get(event).equalsIgnoreCase("vibrate")) { events_list.get(event).setStatus("vibrate"); ((RadioButton) status_group.getChildAt(2)).setChecked(true); status = "vibrate"; } else if (event_status_map.get(event).equalsIgnoreCase("silence")) { events_list.get(event).setStatus("silence"); ((RadioButton) status_group.getChildAt(1)).setChecked(true); status = "silence"; } else { events_list.get(event).setStatus("sound"); ((RadioButton) status_group.getChildAt(0)).setChecked(true); status = "sound"; } } catch (Exception e) { e.printStackTrace(); } // query Events database each time a radio button is pressed to // update its silence/vibrate status status_group.setOnCheckedChangeListener(event_status_listener); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } }; }
true
true
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { List<Event> tmp_events_list = handler.getAllEvents(); //turn this into event_status_map event_status_map = new HashMap<String, String>(); for (Event event : tmp_events_list) { String title = event.getName(); String status = event.getStatus(); event_status_map.put(title, status); } String selected = parent.getItemAtPosition(pos).toString(); events_list = getCalendarEvents(selected); TableLayout events_table = (TableLayout)findViewById(R.id.event_table); events_table.removeAllViews(); for (String event : events_list.keySet()) { //make row in table including event name and silence/vibrate radio button //and maybe a pop up that shows more info about event, such as start and //end time. TableRow tr_container = (TableRow)getLayoutInflater().inflate(R.layout.event_row_layout, null); RelativeLayout tr = (RelativeLayout)tr_container.getChildAt(0); TextView text = (TextView) tr.getChildAt(0); text.setText(event); events_table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); RadioGroup status_group = (RadioGroup) tr.getChildAt(1); //when you generate the table, populate it's radio buttons based on their //status in database String status; try { if (event_status_map.get(event).equalsIgnoreCase("vibrate")) { events_list.get(event).setStatus("vibrate"); ((RadioButton) status_group.getChildAt(2)).setChecked(true); status = "vibrate"; } else if (event_status_map.get(event).equalsIgnoreCase("silence")) { events_list.get(event).setStatus("silence"); ((RadioButton) status_group.getChildAt(1)).setChecked(true); status = "silence"; } else { events_list.get(event).setStatus("sound"); ((RadioButton) status_group.getChildAt(0)).setChecked(true); status = "sound"; } } catch (Exception e) { e.printStackTrace(); } // query Events database each time a radio button is pressed to // update its silence/vibrate status status_group.setOnCheckedChangeListener(event_status_listener); } }
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { List<Event> tmp_events_list = handler.getAllEvents(); //turn this into event_status_map event_status_map = new HashMap<String, String>(); for (Event event : tmp_events_list) { String title = event.getName(); String status = event.getStatus(); event_status_map.put(title, status); } String selected = parent.getItemAtPosition(pos).toString(); events_list = getCalendarEvents(selected); TableLayout events_table = (TableLayout)findViewById(R.id.event_table); events_table.removeAllViews(); for (String event : events_list.keySet()) { //make row in table including event name and silence/vibrate radio button //and maybe a pop up that shows more info about event, such as start and //end time. TableRow tr_container = (TableRow)getLayoutInflater().inflate(R.layout.event_row_layout, null); RelativeLayout tr = (RelativeLayout)tr_container.getChildAt(0); TextView text = (TextView) tr.getChildAt(0); text.setText(event); events_table.addView(tr_container, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); RadioGroup status_group = (RadioGroup) tr.getChildAt(1); //when you generate the table, populate it's radio buttons based on their //status in database String status; try { if (event_status_map.get(event).equalsIgnoreCase("vibrate")) { events_list.get(event).setStatus("vibrate"); ((RadioButton) status_group.getChildAt(2)).setChecked(true); status = "vibrate"; } else if (event_status_map.get(event).equalsIgnoreCase("silence")) { events_list.get(event).setStatus("silence"); ((RadioButton) status_group.getChildAt(1)).setChecked(true); status = "silence"; } else { events_list.get(event).setStatus("sound"); ((RadioButton) status_group.getChildAt(0)).setChecked(true); status = "sound"; } } catch (Exception e) { e.printStackTrace(); } // query Events database each time a radio button is pressed to // update its silence/vibrate status status_group.setOnCheckedChangeListener(event_status_listener); } }
diff --git a/bundleplugin/src/test/java/org/apache/felix/bundleplugin/BundleAllPluginTest.java b/bundleplugin/src/test/java/org/apache/felix/bundleplugin/BundleAllPluginTest.java index bd76d247c..9eaeb63e7 100644 --- a/bundleplugin/src/test/java/org/apache/felix/bundleplugin/BundleAllPluginTest.java +++ b/bundleplugin/src/test/java/org/apache/felix/bundleplugin/BundleAllPluginTest.java @@ -1,147 +1,147 @@ package org.apache.felix.bundleplugin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.felix.bundleplugin.BundleAllPlugin; import java.io.File; import java.util.Collections; import java.util.Map; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.testing.stubs.ArtifactStub; import org.apache.maven.plugin.testing.stubs.MavenProjectStub; import org.apache.maven.project.MavenProject; import org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter; /** * Test for {@link BundleAllPlugin} * * @author <a href="mailto:[email protected]">Carlos Sanchez</a> * @version $Id$ */ public class BundleAllPluginTest extends AbstractBundlePluginTest { private BundleAllPlugin plugin; protected void setUp() throws Exception { super.setUp(); init(); } private void init() { plugin = new BundleAllPlugin(); File basedir = new File( getBasedir() ); plugin.setBasedir( basedir ); File buildDirectory = new File( basedir, "target" ); plugin.setBuildDirectory( buildDirectory.getPath() ); File outputDirectory = new File( buildDirectory, "classes" ); plugin.setOutputDirectory( outputDirectory ); plugin.setMaven2OsgiConverter( new DefaultMaven2OsgiConverter() ); } public void testSnapshotMatch() { ArtifactStub artifact = getArtifactStub(); String bundleName; artifact.setVersion( "2.1-SNAPSHOT" ); bundleName = "group.artifact_2.1.0.20070207_193904_2.jar"; assertTrue( plugin.snapshotMatch( artifact, bundleName ) ); artifact.setVersion( "2-SNAPSHOT" ); assertFalse( plugin.snapshotMatch( artifact, bundleName ) ); artifact.setArtifactId( "artifactx" ); artifact.setVersion( "2.1-SNAPSHOT" ); assertFalse( plugin.snapshotMatch( artifact, bundleName ) ); } public void testNoReBundling() throws Exception { - File testFile = getTestFile( "target/group.artifact_1.0.0.0.jar" ); + File testFile = getTestFile( "target/classes/org.apache.maven.maven-model_1.0.0.0.jar" ); if ( testFile.exists() ) { testFile.delete(); } ArtifactStub artifact = new ArtifactStub(); artifact.setGroupId( "group" ); artifact.setArtifactId( "artifact" ); artifact.setVersion( "1.0.0.0" ); MavenProject project = new MavenProjectStub(); project.setVersion( artifact.getVersion() ); project.setArtifact( artifact ); project.setArtifacts( Collections.EMPTY_SET ); project.setDependencyArtifacts( Collections.EMPTY_SET ); File bundleFile = getTestFile( "src/test/resources/org.apache.maven.maven-model_2.1.0.SNAPSHOT.jar" ); artifact.setFile( bundleFile ); BundleInfo bundleInfo = plugin.bundle( project ); Map exports = bundleInfo.getExportedPackages(); String[] packages = new String[] { "org.apache.maven.model.io.jdom", "org.apache.maven.model" }; for ( int i = 0; i < packages.length; i++ ) { assertTrue( "Bundle info does not contain a package that it is exported in the manifest: " + packages[i], exports.containsKey( packages[i] ) ); } assertFalse( "Bundle info contains a package that it is not exported in the manifest", exports .containsKey( "org.apache.maven.model.io.xpp3" ) ); } // public void testRewriting() // throws Exception // { // // MavenProjectStub project = new MavenProjectStub(); // project.setArtifact( getArtifactStub() ); // project.getArtifact().setFile( getTestBundle() ); // project.setDependencyArtifacts( Collections.EMPTY_SET ); // project.setVersion( project.getArtifact().getVersion() ); // // File output = new File( plugin.getBuildDirectory(), plugin.getBundleName( project ) ); // boolean delete = output.delete(); // // plugin.bundle( project ); // // init(); // try // { // plugin.bundle( project ); // fail(); // } // catch ( RuntimeException e ) // { // // expected // } // } }
true
true
public void testNoReBundling() throws Exception { File testFile = getTestFile( "target/group.artifact_1.0.0.0.jar" ); if ( testFile.exists() ) { testFile.delete(); } ArtifactStub artifact = new ArtifactStub(); artifact.setGroupId( "group" ); artifact.setArtifactId( "artifact" ); artifact.setVersion( "1.0.0.0" ); MavenProject project = new MavenProjectStub(); project.setVersion( artifact.getVersion() ); project.setArtifact( artifact ); project.setArtifacts( Collections.EMPTY_SET ); project.setDependencyArtifacts( Collections.EMPTY_SET ); File bundleFile = getTestFile( "src/test/resources/org.apache.maven.maven-model_2.1.0.SNAPSHOT.jar" ); artifact.setFile( bundleFile ); BundleInfo bundleInfo = plugin.bundle( project ); Map exports = bundleInfo.getExportedPackages(); String[] packages = new String[] { "org.apache.maven.model.io.jdom", "org.apache.maven.model" }; for ( int i = 0; i < packages.length; i++ ) { assertTrue( "Bundle info does not contain a package that it is exported in the manifest: " + packages[i], exports.containsKey( packages[i] ) ); } assertFalse( "Bundle info contains a package that it is not exported in the manifest", exports .containsKey( "org.apache.maven.model.io.xpp3" ) ); }
public void testNoReBundling() throws Exception { File testFile = getTestFile( "target/classes/org.apache.maven.maven-model_1.0.0.0.jar" ); if ( testFile.exists() ) { testFile.delete(); } ArtifactStub artifact = new ArtifactStub(); artifact.setGroupId( "group" ); artifact.setArtifactId( "artifact" ); artifact.setVersion( "1.0.0.0" ); MavenProject project = new MavenProjectStub(); project.setVersion( artifact.getVersion() ); project.setArtifact( artifact ); project.setArtifacts( Collections.EMPTY_SET ); project.setDependencyArtifacts( Collections.EMPTY_SET ); File bundleFile = getTestFile( "src/test/resources/org.apache.maven.maven-model_2.1.0.SNAPSHOT.jar" ); artifact.setFile( bundleFile ); BundleInfo bundleInfo = plugin.bundle( project ); Map exports = bundleInfo.getExportedPackages(); String[] packages = new String[] { "org.apache.maven.model.io.jdom", "org.apache.maven.model" }; for ( int i = 0; i < packages.length; i++ ) { assertTrue( "Bundle info does not contain a package that it is exported in the manifest: " + packages[i], exports.containsKey( packages[i] ) ); } assertFalse( "Bundle info contains a package that it is not exported in the manifest", exports .containsKey( "org.apache.maven.model.io.xpp3" ) ); }
diff --git a/src/org/openstreetmap/josm/io/GpxImporter.java b/src/org/openstreetmap/josm/io/GpxImporter.java index 50d2b18a..5fbe6e7b 100644 --- a/src/org/openstreetmap/josm/io/GpxImporter.java +++ b/src/org/openstreetmap/josm/io/GpxImporter.java @@ -1,77 +1,79 @@ // License: GPL. For details, see LICENSE file. package org.openstreetmap.josm.io; import static org.openstreetmap.josm.tools.I18n.tr; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; import javax.swing.SwingUtilities; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.actions.ExtensionFileFilter; import org.openstreetmap.josm.gui.layer.GpxLayer; import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer; import org.xml.sax.SAXException; public class GpxImporter extends FileImporter { public GpxImporter() { super(new ExtensionFileFilter("gpx,gpx.gz", "gpx", tr("GPX Files") + " (*.gpx *.gpx.gz)")); } @Override public void importData(final File file) throws IOException { final String fn = file.getName(); try { InputStream is; if (file.getName().endsWith(".gpx.gz")) { is = new GZIPInputStream(new FileInputStream(file)); } else { is = new FileInputStream(file); } // Workaround for SAX BOM bug // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6206835 if (!((is.read() == 0xef) && (is.read() == 0xbb) && (is.read() == 0xbf))) { is.close(); if (file.getName().endsWith(".gpx.gz")) { is = new GZIPInputStream(new FileInputStream(file)); } else { is = new FileInputStream(file); } } final GpxReader r = new GpxReader(is, file.getAbsoluteFile().getParentFile()); r.data.storageFile = file; final GpxLayer gpxLayer = new GpxLayer(r.data, fn, true); // FIXME: remove UI stuff from the IO subsystem // Runnable task = new Runnable() { public void run() { - Main.main.addLayer(gpxLayer); - if (Main.pref.getBoolean("marker.makeautomarkers", true)) { + if (!r.data.tracks.isEmpty() || ! r.data.routes.isEmpty()) { + Main.main.addLayer(gpxLayer); + } + if (Main.pref.getBoolean("marker.makeautomarkers", true) && !r.data.waypoints.isEmpty()) { MarkerLayer ml = new MarkerLayer(r.data, tr("Markers from {0}", fn), file, gpxLayer); if (ml.data.size() > 0) { Main.main.addLayer(ml); } } } }; if (SwingUtilities.isEventDispatchThread()) { task.run(); } else { SwingUtilities.invokeLater(task); } } catch (FileNotFoundException e) { e.printStackTrace(); throw new IOException(tr("File \"{0}\" does not exist", file.getName())); } catch (SAXException e) { e.printStackTrace(); throw new IOException(tr("Parsing file \"{0}\" failed", file.getName())); } } }
true
true
@Override public void importData(final File file) throws IOException { final String fn = file.getName(); try { InputStream is; if (file.getName().endsWith(".gpx.gz")) { is = new GZIPInputStream(new FileInputStream(file)); } else { is = new FileInputStream(file); } // Workaround for SAX BOM bug // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6206835 if (!((is.read() == 0xef) && (is.read() == 0xbb) && (is.read() == 0xbf))) { is.close(); if (file.getName().endsWith(".gpx.gz")) { is = new GZIPInputStream(new FileInputStream(file)); } else { is = new FileInputStream(file); } } final GpxReader r = new GpxReader(is, file.getAbsoluteFile().getParentFile()); r.data.storageFile = file; final GpxLayer gpxLayer = new GpxLayer(r.data, fn, true); // FIXME: remove UI stuff from the IO subsystem // Runnable task = new Runnable() { public void run() { Main.main.addLayer(gpxLayer); if (Main.pref.getBoolean("marker.makeautomarkers", true)) { MarkerLayer ml = new MarkerLayer(r.data, tr("Markers from {0}", fn), file, gpxLayer); if (ml.data.size() > 0) { Main.main.addLayer(ml); } } } }; if (SwingUtilities.isEventDispatchThread()) { task.run(); } else { SwingUtilities.invokeLater(task); } } catch (FileNotFoundException e) { e.printStackTrace(); throw new IOException(tr("File \"{0}\" does not exist", file.getName())); } catch (SAXException e) { e.printStackTrace(); throw new IOException(tr("Parsing file \"{0}\" failed", file.getName())); } }
@Override public void importData(final File file) throws IOException { final String fn = file.getName(); try { InputStream is; if (file.getName().endsWith(".gpx.gz")) { is = new GZIPInputStream(new FileInputStream(file)); } else { is = new FileInputStream(file); } // Workaround for SAX BOM bug // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6206835 if (!((is.read() == 0xef) && (is.read() == 0xbb) && (is.read() == 0xbf))) { is.close(); if (file.getName().endsWith(".gpx.gz")) { is = new GZIPInputStream(new FileInputStream(file)); } else { is = new FileInputStream(file); } } final GpxReader r = new GpxReader(is, file.getAbsoluteFile().getParentFile()); r.data.storageFile = file; final GpxLayer gpxLayer = new GpxLayer(r.data, fn, true); // FIXME: remove UI stuff from the IO subsystem // Runnable task = new Runnable() { public void run() { if (!r.data.tracks.isEmpty() || ! r.data.routes.isEmpty()) { Main.main.addLayer(gpxLayer); } if (Main.pref.getBoolean("marker.makeautomarkers", true) && !r.data.waypoints.isEmpty()) { MarkerLayer ml = new MarkerLayer(r.data, tr("Markers from {0}", fn), file, gpxLayer); if (ml.data.size() > 0) { Main.main.addLayer(ml); } } } }; if (SwingUtilities.isEventDispatchThread()) { task.run(); } else { SwingUtilities.invokeLater(task); } } catch (FileNotFoundException e) { e.printStackTrace(); throw new IOException(tr("File \"{0}\" does not exist", file.getName())); } catch (SAXException e) { e.printStackTrace(); throw new IOException(tr("Parsing file \"{0}\" failed", file.getName())); } }
diff --git a/src/se/slide/sgu/PlayerFragment.java b/src/se/slide/sgu/PlayerFragment.java index ec35e08..8741b8a 100644 --- a/src/se/slide/sgu/PlayerFragment.java +++ b/src/se/slide/sgu/PlayerFragment.java @@ -1,59 +1,59 @@ package se.slide.sgu; import android.app.Fragment; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageButton; import android.widget.LinearLayout; public class PlayerFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_player, null); final LinearLayout playerLinearLayout = (LinearLayout) view.findViewById(R.id.player_linearlayout); - playerLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#88000000"))); + //playerLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#88000000"))); final LinearLayout playerMainInfoLinearLayout = (LinearLayout) view.findViewById(R.id.player_maininfo_linearlayout); - playerMainInfoLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#dd000000"))); + //playerMainInfoLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#dd000000"))); ImageButton showContentButton = (ImageButton) view.findViewById(R.id.showContentButton); showContentButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (playerMainInfoLinearLayout.getVisibility() == View.VISIBLE) { AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f); anim.setDuration(250); anim.setFillAfter(true); //anim.setRepeatMode(Animation.REVERSE); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.INVISIBLE); playerMainInfoLinearLayout.setClickable(false); } else { AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(250); anim.setFillAfter(true); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.VISIBLE); playerMainInfoLinearLayout.setClickable(true); } } }); return view; } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_player, null); final LinearLayout playerLinearLayout = (LinearLayout) view.findViewById(R.id.player_linearlayout); playerLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#88000000"))); final LinearLayout playerMainInfoLinearLayout = (LinearLayout) view.findViewById(R.id.player_maininfo_linearlayout); playerMainInfoLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#dd000000"))); ImageButton showContentButton = (ImageButton) view.findViewById(R.id.showContentButton); showContentButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (playerMainInfoLinearLayout.getVisibility() == View.VISIBLE) { AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f); anim.setDuration(250); anim.setFillAfter(true); //anim.setRepeatMode(Animation.REVERSE); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.INVISIBLE); playerMainInfoLinearLayout.setClickable(false); } else { AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(250); anim.setFillAfter(true); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.VISIBLE); playerMainInfoLinearLayout.setClickable(true); } } }); return view; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_player, null); final LinearLayout playerLinearLayout = (LinearLayout) view.findViewById(R.id.player_linearlayout); //playerLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#88000000"))); final LinearLayout playerMainInfoLinearLayout = (LinearLayout) view.findViewById(R.id.player_maininfo_linearlayout); //playerMainInfoLinearLayout.setBackground(new ColorDrawable(Color.parseColor("#dd000000"))); ImageButton showContentButton = (ImageButton) view.findViewById(R.id.showContentButton); showContentButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (playerMainInfoLinearLayout.getVisibility() == View.VISIBLE) { AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f); anim.setDuration(250); anim.setFillAfter(true); //anim.setRepeatMode(Animation.REVERSE); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.INVISIBLE); playerMainInfoLinearLayout.setClickable(false); } else { AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f); anim.setDuration(250); anim.setFillAfter(true); playerMainInfoLinearLayout.startAnimation(anim); playerMainInfoLinearLayout.setVisibility(View.VISIBLE); playerMainInfoLinearLayout.setClickable(true); } } }); return view; }